tls_server.c

Go to the documentation of this file.
00001 /*
00002  * $Id$
00003  *
00004  * TLS module - main server part
00005  * 
00006  * Copyright (C) 2001-2003 FhG FOKUS
00007  * Copyright (C) 2005-2010 iptelorg GmbH
00008  *
00009  * This file is part of SIP-router, a free SIP server.
00010  *
00011  * Permission to use, copy, modify, and distribute this software for any
00012  * purpose with or without fee is hereby granted, provided that the above
00013  * copyright notice and this permission notice appear in all copies.
00014  *
00015  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
00016  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
00017  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
00018  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
00019  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
00020  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
00021  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
00022  */
00023 /*
00024  * History:
00025  * --------
00026  *  2007-01-26  openssl kerberos malloc bug detection/workaround (andrei)
00027  *  2007-02-23  openssl low memory bugs workaround (andrei)
00028  *  2009-09-21  tls connection state is now kept in c->extra_data (no
00029  *               longer shared with tcp state) (andrei)
00030  */
00038 #include <sys/poll.h>
00039 #include <openssl/err.h>
00040 #include <openssl/ssl.h>
00041 #include "../../dprint.h"
00042 #include "../../ip_addr.h"
00043 #include "../../mem/shm_mem.h"
00044 #include "../../pt.h"
00045 #include "../../timer.h"
00046 #include "../../globals.h"
00047 #include "../../pt.h"
00048 #include "../../tcp_int_send.h"
00049 #include "../../tcp_read.h"
00050 #include "../../cfg/cfg.h"
00051 
00052 #include "tls_init.h"
00053 #include "tls_domain.h"
00054 #include "tls_util.h"
00055 #include "tls_mod.h"
00056 #include "tls_server.h"
00057 #include "tls_bio.h"
00058 #include "tls_dump_vf.h"
00059 #include "tls_cfg.h"
00060 
00061 /* low memory treshold for openssl bug #1491 workaround */
00062 #define LOW_MEM_NEW_CONNECTION_TEST() \
00063         (cfg_get(tls, tls_cfg, low_mem_threshold1) && \
00064           (shm_available() < cfg_get(tls, tls_cfg, low_mem_threshold1)))
00065 #define LOW_MEM_CONNECTED_TEST() \
00066         (cfg_get(tls, tls_cfg, low_mem_threshold2) && \
00067           (shm_available() <  cfg_get(tls, tls_cfg, low_mem_threshold2)))
00068 
00069 #define TLS_RD_MBUF_SZ  65536
00070 #define TLS_WR_MBUF_SZ  65536
00071 
00072 
00073 /* debugging */
00074 #ifdef NO_TLS_RD_DEBUG
00075 #undef TLS_RD_DEBUG
00076 #endif
00077 
00078 #ifdef NO_TLS_WR_DEBUG
00079 #undef TLS_WR_DEBUG
00080 #endif
00081 #if defined TLS_RD_DEBUG || defined TLS_WR_DEBUG
00082 #define TLS_F_DEBUG
00083 #endif
00084 
00085 /* if NO_TLS_F_DEBUG or NO_TLS_DEBUG => no debug code */
00086 #if defined NO_TLS_F_DEBUG || defined NO_TLS_DEBUG
00087 #undef TLS_F_DEBUG
00088 #endif
00089 
00090 #ifdef TLS_F_DEBUG
00091         #ifdef __SUNPRO_C
00092                 #define TLS_F_TRACE(fmt, ...) \
00093                         LOG_(DEFAULT_FACILITY, cfg_get(tls, tls_cfg, debug),\
00094                                         "TLS_TRACE: " LOC_INFO, " %s" fmt,\
00095                                         _FUNC_NAME_,  __VA_ARGS__)
00096         #else
00097                 #define TLS_F_TRACE(fmt, args...) \
00098                         LOG_(DEFAULT_FACILITY, cfg_get(tls, tls_cfg, debug),\
00099                                         "TLS_TRACE: " LOC_INFO, " %s" fmt,\
00100                                         _FUNC_NAME_, ## args)
00101         #endif /* __SUNPRO_c */
00102 #else /* TLS_F_DEBUG */
00103         #ifdef __SUNPRO_C
00104                 #define TLS_F_TRACE(...)
00105         #else
00106                 #define TLS_F_TRACE(fmt, args...)
00107         #endif /* __SUNPRO_c */
00108 #endif /* TLS_F_DEBUG */
00109 
00110 /* tls_read debugging */
00111 #ifdef TLS_RD_DEBUG
00112         #define TLS_RD_TRACE TLS_F_TRACE
00113 #else /* TLS_RD_DEBUG */
00114         #ifdef __SUNPRO_C
00115                 #define TLS_RD_TRACE(...)
00116         #else
00117                 #define TLS_RD_TRACE(fmt, args...)
00118         #endif /* __SUNPRO_c */
00119 #endif /* TLS_RD_DEBUG */
00120 
00121 /* tls_write debugging */
00122 #ifdef TLS_WR_DEBUG
00123         #define TLS_WR_TRACE TLS_F_TRACE
00124 #else /* TLS_RD_DEBUG */
00125         #ifdef __SUNPRO_C
00126                 #define TLS_WR_TRACE(...)
00127         #else
00128                 #define TLS_WR_TRACE(fmt, args...)
00129         #endif /* __SUNPRO_c */
00130 #endif /* TLS_RD_DEBUG */
00131 
00132 
00141 static int tls_complete_init(struct tcp_connection* c)
00142 {
00143         tls_domain_t* dom;
00144         struct tls_extra_data* data = 0;
00145         tls_domains_cfg_t* cfg;
00146         enum tls_conn_states state;
00147 
00148         if (LOW_MEM_NEW_CONNECTION_TEST()){
00149                 ERR("tls: ssl bug #1491 workaround: not enough memory for safe"
00150                                 " operation: %lu\n", shm_available());
00151                 goto error2;
00152         }
00153              /* Get current TLS configuration and increase reference
00154               * count immediately. There is no need to lock the structure
00155               * here, because it does not get deleted immediately. When
00156               * SER reloads TLS configuration it will put the old configuration
00157               * on a garbage queue and delete it later, so we know here that
00158               * the pointer we get from *tls_domains_cfg will be valid for a while,
00159                   * at least by the time this function finishes
00160               */
00161         cfg = *tls_domains_cfg;
00162 
00163              /* Increment the reference count in the configuration structure, this
00164               * is to ensure that, while on the garbage queue, the configuration does
00165               * not get deleted if there are still connection referencing its SSL_CTX
00166               */
00167         cfg->ref_count++;
00168 
00169         if (c->flags & F_CONN_PASSIVE) {
00170                 state=S_TLS_ACCEPTING;
00171                 dom = tls_lookup_cfg(cfg, TLS_DOMAIN_SRV,
00172                                                                 &c->rcv.dst_ip, c->rcv.dst_port);
00173         } else {
00174                 state=S_TLS_CONNECTING;
00175                 dom = tls_lookup_cfg(cfg, TLS_DOMAIN_CLI,
00176                                                                 &c->rcv.dst_ip, c->rcv.dst_port);
00177         }
00178         if (unlikely(c->state<0)) {
00179                 BUG("Invalid connection (state %d)\n", c->state);
00180                 goto error;
00181         }
00182         DBG("Using TLS domain %s\n", tls_domain_str(dom));
00183 
00184         data = (struct tls_extra_data*)shm_malloc(sizeof(struct tls_extra_data));
00185         if (!data) {
00186                 ERR("Not enough shared memory left\n");
00187                 goto error;
00188         }
00189         memset(data, '\0', sizeof(struct tls_extra_data));
00190         data->ssl = SSL_new(dom->ctx[process_no]);
00191         data->rwbio = tls_BIO_new_mbuf(0, 0);
00192         data->cfg = cfg;
00193         data->state = state;
00194 
00195         if (unlikely(data->ssl == 0 || data->rwbio == 0)) {
00196                 TLS_ERR("Failed to create SSL or BIO structure:");
00197                 if (data->ssl)
00198                         SSL_free(data->ssl);
00199                 if (data->rwbio)
00200                         BIO_free(data->rwbio);
00201                 goto error;
00202         }
00203 #ifdef TLS_KSSL_WORKARROUND
00204          /* if needed apply workaround for openssl bug #1467 */
00205         if (data->ssl->kssl_ctx && openssl_kssl_malloc_bug){
00206                 kssl_ctx_free(data->ssl->kssl_ctx);
00207                 data->ssl->kssl_ctx=0;
00208         }
00209 #endif
00210         SSL_set_bio(data->ssl, data->rwbio, data->rwbio);
00211         c->extra_data = data;
00212 
00213         /* link the extra data struct inside ssl connection*/
00214         SSL_set_app_data(data->ssl, data);
00215 
00216         return 0;
00217 
00218  error:
00219         cfg->ref_count--;
00220         if (data) shm_free(data);
00221  error2:
00222         return -1;
00223 }
00224 
00225 
00226 
00233 static int tls_fix_connection_unsafe(struct tcp_connection* c)
00234 {
00235         if (unlikely(!c->extra_data)) {
00236                 if (unlikely(tls_complete_init(c) < 0)) {
00237                         return -1;
00238                 }
00239         }else if (unlikely(LOW_MEM_CONNECTED_TEST())){
00240                 ERR("tls: ssl bug #1491 workaround: not enough memory for safe"
00241                                 " operation: %lu\n", shm_available());
00242                 return -1;
00243         }
00244         return 0;
00245 }
00246 
00247 
00248 
00256 static int tls_fix_connection(struct tcp_connection* c)
00257 {
00258         int ret;
00259         
00260         if (unlikely(c->extra_data == 0)) {
00261                 lock_get(&c->write_lock);
00262                         if (unlikely(c->extra_data == 0)) {
00263                                 ret = tls_complete_init(c);
00264                                 lock_release(&c->write_lock);
00265                                 return ret;
00266                         }
00267                 lock_release(&c->write_lock);
00268         }
00269         if (unlikely(LOW_MEM_CONNECTED_TEST())){
00270                 ERR("tls: ssl bug #1491 workaround: not enough memory for safe"
00271                                 " operation: %lu\n", shm_available());
00272                 return -1;
00273         }
00274         return 0;
00275 }
00276 
00277 
00278 
00283 static int tls_set_mbufs(struct tcp_connection *c,
00284                                                         struct tls_mbuf* rd,
00285                                                         struct tls_mbuf* wr)
00286 {
00287         BIO *rwbio;
00288         
00289         rwbio = ((struct tls_extra_data*)c->extra_data)->rwbio;
00290         if (unlikely(tls_BIO_mbuf_set(rwbio, rd, wr)<=0)) {
00291                 /* it should be always 1 */
00292                 ERR("failed to set mbufs");
00293                 return -1;
00294         }
00295         return 0;
00296 }
00297 
00298 
00299 static void tls_dump_cert_info(char* s, X509* cert)
00300 {
00301         char* subj;
00302         char* issuer;
00303         
00304         subj=issuer=0;
00305         subj = X509_NAME_oneline(X509_get_subject_name(cert), 0 , 0);
00306         issuer = X509_NAME_oneline(X509_get_issuer_name(cert), 0 , 0);
00307         
00308         if (subj){
00309                 LOG(cfg_get(tls, tls_cfg, log), "%s subject:%s\n", s ? s : "", subj);
00310                 OPENSSL_free(subj);
00311         }
00312         if (issuer){
00313                 LOG(cfg_get(tls, tls_cfg, log), "%s issuer:%s\n", s ? s : "", issuer);
00314                 OPENSSL_free(issuer);
00315         }
00316 }
00317 
00318 
00319 
00334 int tls_accept(struct tcp_connection *c, int* error)
00335 {
00336         int ret;
00337         SSL *ssl;
00338         X509* cert;
00339         struct tls_extra_data* tls_c;
00340         int tls_log;
00341 
00342         *error = SSL_ERROR_NONE;
00343         tls_c=(struct tls_extra_data*)c->extra_data;
00344         ssl=tls_c->ssl;
00345         
00346         if (unlikely(tls_c->state != S_TLS_ACCEPTING)) {
00347                 BUG("Invalid connection state %d (bug in TLS code)\n", tls_c->state);
00348                 goto err;
00349         }
00350         ret = SSL_accept(ssl);
00351         if (unlikely(ret == 1)) {
00352                 DBG("TLS accept successful\n");
00353                 tls_c->state = S_TLS_ESTABLISHED;
00354                 tls_log = cfg_get(tls, tls_cfg, log);
00355                 LOG(tls_log, "tls_accept: new connection from %s:%d using %s %s %d\n",
00356                     ip_addr2a(&c->rcv.src_ip), c->rcv.src_port,
00357                     SSL_get_cipher_version(ssl), SSL_get_cipher_name(ssl), 
00358                     SSL_get_cipher_bits(ssl, 0)
00359                     );
00360                 LOG(tls_log, "tls_accept: local socket: %s:%d\n", 
00361                     ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port
00362                     );
00363                 cert = SSL_get_peer_certificate(ssl);
00364                 if (cert != 0) { 
00365                         tls_dump_cert_info("tls_accept: client certificate", cert);
00366                         if (SSL_get_verify_result(ssl) != X509_V_OK) {
00367                                 LOG(tls_log, "WARNING: tls_accept: client certificate "
00368                                     "verification failed!!!\n");
00369                                 tls_dump_verification_failure(SSL_get_verify_result(ssl));
00370                         }
00371                         X509_free(cert);
00372                 } else {
00373                         LOG(tls_log, "tls_accept: client did not present a certificate\n");
00374                 }
00375         } else { /* ret == 0 or < 0 */
00376                 *error = SSL_get_error(ssl, ret);
00377         }
00378         return ret;
00379 err:
00380         /* internal non openssl related errors */
00381         return -2;
00382 }
00383 
00384 
00399 int tls_connect(struct tcp_connection *c, int* error)
00400 {
00401         SSL *ssl;
00402         int ret;
00403         X509* cert;
00404         struct tls_extra_data* tls_c;
00405         int tls_log;
00406 
00407         *error = SSL_ERROR_NONE;
00408         tls_c=(struct tls_extra_data*)c->extra_data;
00409         ssl=tls_c->ssl;
00410         
00411         if (unlikely(tls_c->state != S_TLS_CONNECTING)) {
00412                 BUG("Invalid connection state %d (bug in TLS code)\n", tls_c->state);
00413                 goto err;
00414         }
00415         ret = SSL_connect(ssl);
00416         if (unlikely(ret == 1)) {
00417                 DBG("TLS connect successful\n");
00418                 tls_c->state = S_TLS_ESTABLISHED;
00419                 tls_log = cfg_get(tls, tls_cfg, log);
00420                 LOG(tls_log, "tls_connect: new connection to %s:%d using %s %s %d\n", 
00421                     ip_addr2a(&c->rcv.src_ip), c->rcv.src_port,
00422                     SSL_get_cipher_version(ssl), SSL_get_cipher_name(ssl),
00423                     SSL_get_cipher_bits(ssl, 0)
00424                     );
00425                 LOG(tls_log, "tls_connect: sending socket: %s:%d \n", 
00426                     ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port
00427                     );
00428                 cert = SSL_get_peer_certificate(ssl);
00429                 if (cert != 0) { 
00430                         tls_dump_cert_info("tls_connect: server certificate", cert);
00431                         if (SSL_get_verify_result(ssl) != X509_V_OK) {
00432                                 LOG(tls_log, "WARNING: tls_connect: server certificate "
00433                                     "verification failed!!!\n");
00434                                 tls_dump_verification_failure(SSL_get_verify_result(ssl));
00435                         }
00436                         X509_free(cert);
00437                 } else {
00438                         /* this should not happen, servers always present a cert */
00439                         LOG(tls_log, "tls_connect: server did not "
00440                                                         "present a certificate\n");
00441                 }
00442         } else { /* 0 or < 0 */
00443                 *error = SSL_get_error(ssl, ret);
00444         }
00445         return ret;
00446 err:
00447         /* internal non openssl related errors */
00448         return -2;
00449 }
00450 
00451 
00452 /*
00453  * wrapper around SSL_shutdown, returns -1 on error, 0 on success.
00454  */
00455 static int tls_shutdown(struct tcp_connection *c)
00456 {
00457         int ret, err, ssl_err;
00458         struct tls_extra_data* tls_c;
00459         SSL *ssl;
00460 
00461         tls_c=(struct tls_extra_data*)c->extra_data;
00462         if (unlikely(tls_c == 0 || tls_c->ssl == 0)) {
00463                 ERR("No SSL data to perform tls_shutdown\n");
00464                 return -1;
00465         }
00466         ssl = tls_c->ssl;
00467         /* it doesn't make sense to try a TLS level shutdown
00468            if the connection is not fully initialized */
00469         if (unlikely(tls_c->state != S_TLS_ESTABLISHED))
00470                 return 0;
00471         if (unlikely(LOW_MEM_CONNECTED_TEST())){
00472                 ERR("tls: ssl bug #1491 workaround: not enough memory for safe"
00473                                 " operation: %lu\n", shm_available());
00474                 goto err;
00475         }
00476         
00477         ret = SSL_shutdown(ssl);
00478         if (ret == 1) {
00479                 DBG("TLS shutdown successful\n");
00480                 return 0;
00481         } else if (ret == 0) {
00482                 DBG("First phase of 2-way handshake completed succesfuly\n");
00483                 return 0;
00484         } else {
00485                 err = SSL_get_error(ssl, ret);
00486                 switch (err) {
00487                 case SSL_ERROR_ZERO_RETURN:
00488                         DBG("TLS shutdown failed cleanly\n");
00489                         goto err;
00490                         
00491                 case SSL_ERROR_WANT_READ:
00492                         DBG("Need to get more data to finish TLS shutdown\n");
00493                         break;
00494                         
00495                 case SSL_ERROR_WANT_WRITE:
00496                         DBG("Need to send more data to finish TLS shutdown\n");
00497                         break;
00498                         
00499 #if OPENSSL_VERSION_NUMBER >= 0x00907000L /*0.9.7*/
00500                 case SSL_ERROR_WANT_CONNECT:
00501                         DBG("Need to retry connect\n");
00502                         break;
00503                         
00504                 case SSL_ERROR_WANT_ACCEPT:
00505                         DBG("Need to retry accept\n");
00506                         break;
00507 #endif
00508                 case SSL_ERROR_WANT_X509_LOOKUP:
00509                         DBG("Application callback asked to be called again\n");
00510                         break;
00511                         
00512                 case SSL_ERROR_SYSCALL:
00513                         TLS_ERR_RET(ssl_err, "TLS shutdown");
00514                         if (!ssl_err) {
00515                                 if (ret == 0) {
00516                                         WARN("Unexpected EOF occurred while performing TLS shutdown\n");
00517                                 } else {
00518                                         ERR("IO error: (%d) %s\n", errno, strerror(errno));
00519                                 }
00520                         }
00521                         goto err;
00522                         
00523                 case SSL_ERROR_SSL:
00524                 default:
00525                         TLS_ERR("SSL error:");
00526                         goto err;
00527                 }
00528         }
00529         
00530         return 0;
00531  err:
00532         return -1;
00533 }
00534 
00535 
00536 
00549 int tls_h_tcpconn_init(struct tcp_connection *c, int sock)
00550 {
00551         c->type = PROTO_TLS;
00552         c->rcv.proto = PROTO_TLS;
00553         c->timeout = get_ticks_raw() + cfg_get(tls, tls_cfg, con_lifetime);
00554         c->extra_data = 0;
00555         return 0;
00556 }
00557 
00558 
00561 void tls_h_tcpconn_clean(struct tcp_connection *c)
00562 {
00563         struct tls_extra_data* extra;
00564         /*
00565         * runs within global tcp lock
00566         */
00567         if (c->type != PROTO_TLS) {
00568                 BUG("Bad connection structure\n");
00569                 abort();
00570         }
00571         if (c->extra_data) {
00572                 extra = (struct tls_extra_data*)c->extra_data;
00573                 SSL_free(extra->ssl);
00574                 extra->cfg->ref_count--;
00575                 if (extra->ct_wq)
00576                         tls_ct_wq_free(&extra->ct_wq);
00577                 if (extra->enc_rd_buf) {
00578                         shm_free(extra->enc_rd_buf);
00579                         extra->enc_rd_buf = 0;
00580                 }
00581                 shm_free(c->extra_data);
00582                 c->extra_data = 0;
00583         }
00584 }
00585 
00586 
00589 void tls_h_close(struct tcp_connection *c, int fd)
00590 {
00591         unsigned char wr_buf[TLS_WR_MBUF_SZ];
00592         struct tls_mbuf rd, wr;
00593         
00594         /*
00595          * runs either within global tcp lock or after the connection has
00596          * been "detached" and is unreachable from any other process.
00597          * Unfortunately when called via
00598          * tcpconn_put_destroy()+tcpconn_close_main_fd() the connection might
00599          * still be in a writer, so in this case locking is needed.
00600          */
00601         DBG("Closing SSL connection %p\n", c->extra_data);
00602         if (unlikely(cfg_get(tls, tls_cfg, send_close_notify) && c->extra_data)) {
00603                 lock_get(&c->write_lock);
00604                         if (unlikely(c->extra_data == 0)) {
00605                                 /* changed in the meanwhile */
00606                                 lock_release(&c->write_lock);
00607                                 return;
00608                         }
00609                         tls_mbuf_init(&rd, 0, 0); /* no read */
00610                         tls_mbuf_init(&wr, wr_buf, sizeof(wr_buf));
00611                         if (tls_set_mbufs(c, &rd, &wr)==0) {
00612                                 tls_shutdown(c); /* shudown only on succesfull set fd */
00613                                 /* write as much as possible and update wr.
00614                                  * Since this is a close, we don't want to queue the write
00615                                  * (if it can't write immediately, just fail silently)
00616                                  */
00617                                 if (wr.used)
00618                                         _tcpconn_write_nb(fd, c, (char*)wr.buf, wr.used);
00619                                 /* we don't bother reading anything (we don't want to wait
00620                                 on close) */
00621                         }
00622                 lock_release(&c->write_lock);
00623         }
00624 }
00625 
00626 
00627 
00628 /* generic tcpconn_{do,1st}_send() function pointer type */
00629 typedef int (*tcp_low_level_send_t)(int fd, struct tcp_connection *c,
00630                                                                         char* buf, unsigned len,
00631                                                                         snd_flags_t send_flags,
00632                                                                         long* resp, int locked);
00633 
00634 
00635 
00661 int tls_encode_f(struct tcp_connection *c,
00662                                                 const char** pbuf, unsigned int* plen,
00663                                                 const char** rest_buf, unsigned int* rest_len,
00664                                                 snd_flags_t* send_flags)
00665 {
00666         int n, offs;
00667         SSL* ssl;
00668         struct tls_extra_data* tls_c;
00669         static unsigned char wr_buf[TLS_WR_MBUF_SZ];
00670         struct tls_mbuf rd, wr;
00671         int ssl_error;
00672         char* err_src;
00673         const char* buf;
00674         unsigned int len;
00675         int x;
00676         
00677         buf = *pbuf;
00678         len = *plen;
00679         *rest_buf = 0;
00680         *rest_len = 0;
00681         TLS_WR_TRACE("(%p, %p, %d, ... 0x%0x) start (%s:%d* -> %s)\n",
00682                                         c, buf, len, send_flags->f,
00683                                         ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port,
00684                                         su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)));
00685         n = 0;
00686         offs = 0;
00687         ssl_error = SSL_ERROR_NONE;
00688         err_src = "TLS write:";
00689         if (unlikely(tls_fix_connection_unsafe(c) < 0)) {
00690                 /* c->extra_data might be null => exit immediately */
00691                 TLS_WR_TRACE("(%p) end: tls_fix_connection_unsafe failed =>"
00692                                                 " immediate error exit\n", c);
00693                 return -1;
00694         }
00695         tls_c = (struct tls_extra_data*)c->extra_data;
00696         ssl = tls_c->ssl;
00697         tls_mbuf_init(&rd, 0, 0); /* no read */
00698         tls_mbuf_init(&wr, wr_buf, sizeof(wr_buf));
00699         /* clear text already queued (WANTS_READ) queue directly*/
00700         if (unlikely(tls_write_wants_read(tls_c))) {
00701                 TLS_WR_TRACE("(%p) WANTS_READ queue present => queueing"
00702                                                 " (%d bytes,  %p + %d)\n", c, len - offs, buf, offs);
00703                 if (unlikely(tls_ct_wq_add(&tls_c->ct_wq, buf+offs, len -offs) < 0)) {
00704                                 ERR("ct write buffer full for %p (%d bytes)\n",
00705                                                 c, tls_c->ct_wq?tls_c->ct_wq->queued:0);
00706                                 goto error_wq_full;
00707                 }
00708                 /* buffer queued for a future send attempt, after first reading
00709                    some data (key exchange) => don't allow immediate closing of
00710                    the connection */
00711                 send_flags->f &= ~SND_F_CON_CLOSE;
00712                 goto end;
00713         }
00714         if (unlikely(tls_set_mbufs(c, &rd, &wr) < 0)) {
00715                 ERR("tls_set_mbufs failed\n");
00716                 goto error;
00717         }
00718 redo_wr:
00719         if (unlikely(tls_c->state == S_TLS_CONNECTING)) {
00720                 n = tls_connect(c, &ssl_error);
00721                 TLS_WR_TRACE("(%p) tls_connect() => %d (err=%d)\n", c, n, ssl_error);
00722                 if (unlikely(n>=1)) {
00723                         n = SSL_write(ssl, buf + offs, len - offs);
00724                         if (unlikely(n <= 0))
00725                                 ssl_error = SSL_get_error(ssl, n);
00726                 } else {
00727                         /* tls_connect failed/needs more IO */
00728                         if (unlikely(n < 0 && ssl_error == SSL_ERROR_NONE))
00729                                 goto error;
00730                         err_src = "TLS connect:";
00731                 }
00732         } else if (unlikely(tls_c->state == S_TLS_ACCEPTING)) {
00733                 n = tls_accept(c, &ssl_error);
00734                 TLS_WR_TRACE("(%p) tls_accept() => %d (err=%d)\n", c, n, ssl_error);
00735                 if (unlikely(n>=1)) {
00736                         n = SSL_write(ssl, buf + offs, len - offs);
00737                         if (unlikely(n <= 0))
00738                                 ssl_error = SSL_get_error(ssl, n);
00739                 } else {
00740                         /* tls_accept failed/needs more IO */
00741                         if (unlikely(n < 0 && ssl_error == SSL_ERROR_NONE))
00742                                 goto error;
00743                         err_src = "TLS accept:";
00744                 }
00745         } else {
00746                 n = SSL_write(ssl, buf + offs, len - offs);
00747                 if (unlikely(n <= 0))
00748                         ssl_error = SSL_get_error(ssl, n);
00749         }
00750         TLS_WR_TRACE("(%p) SSL_write(%p + %d, %d) => %d (err=%d)\n",
00751                                         c, buf, offs, len - offs, n, ssl_error);
00752         /* check for possible ssl errors */
00753         if (unlikely(n <= 0)){
00754                 switch(ssl_error) {
00755                         case SSL_ERROR_NONE:
00756                                 BUG("unexpected SSL_ERROR_NONE for n=%d\n", n);
00757                                 goto error;
00758                                 break;
00759                         case SSL_ERROR_ZERO_RETURN:
00760                                 /* SSL EOF */
00761                                 ERR("ssl level EOF\n");
00762                                 goto ssl_eof;
00763                         case SSL_ERROR_WANT_READ:
00764                                 /* queue write buffer */
00765                                 TLS_WR_TRACE("(%p) SSL_ERROR_WANT_READ => queueing for read"
00766                                                                 " (%p + %d, %d)\n", c, buf, offs, len -offs);
00767                                 if (unlikely(tls_ct_wq_add(&tls_c->ct_wq, buf+offs, len -offs)
00768                                                                 < 0)) {
00769                                         ERR("ct write buffer full (%d bytes)\n",
00770                                                         tls_c->ct_wq?tls_c->ct_wq->queued:0);
00771                                         goto error_wq_full;
00772                                 }
00773                                 tls_c->flags |= F_TLS_CON_WR_WANTS_RD;
00774                                 /* buffer queued for a future send attempt, after first
00775                                    reading some data (key exchange) => don't allow immediate
00776                                    closing of the connection */
00777                                 send_flags->f &= ~SND_F_CON_CLOSE;
00778                                 break; /* or goto end */
00779                         case SSL_ERROR_WANT_WRITE:
00780                                 if (unlikely(offs == 0)) {
00781                                         /*  error, no record fits in the buffer or
00782                                           no partial write enabled and buffer to small to fit
00783                                           all the records */
00784                                         BUG("write buffer too small (%d/%d bytes)\n",
00785                                                         wr.used, wr.size);
00786                                         goto bug;
00787                                 } else {
00788                                         /* offs != 0 => something was "written"  */
00789                                         *rest_buf = buf + offs;
00790                                         *rest_len = len - offs;
00791                                         /* this function should be called again => disallow
00792                                            immediate closing of the connection */
00793                                         send_flags->f &= ~SND_F_CON_CLOSE;
00794                                         TLS_WR_TRACE("(%p) SSL_ERROR_WANT_WRITE partial write"
00795                                                                 " (written %p , %d, rest_buf=%p"
00796                                                                 " rest_len=%d))\n", c, buf, offs,
00797                                                                 *rest_buf, *rest_len);
00798                                 }
00799                                 break; /* or goto end */
00800                         case SSL_ERROR_SSL:
00801                                 /* protocol level error */
00802                                 TLS_ERR(err_src);
00803                                 goto error;
00804 #if OPENSSL_VERSION_NUMBER >= 0x00907000L /*0.9.7*/
00805                         case SSL_ERROR_WANT_CONNECT:
00806                                 /* only if the underlying BIO is not yet connected
00807                                    and the call would block in connect().
00808                                    (not possible in our case) */
00809                                 BUG("unexpected SSL_ERROR_WANT_CONNECT\n");
00810                                 break;
00811                         case SSL_ERROR_WANT_ACCEPT:
00812                                 /* only if the underlying BIO is not yet connected
00813                                    and call would block in accept()
00814                                    (not possible in our case) */
00815                                 BUG("unexpected SSL_ERROR_WANT_ACCEPT\n");
00816                                 break;
00817 #endif
00818                         case SSL_ERROR_WANT_X509_LOOKUP:
00819                                 /* can only appear on client application and it indicates that
00820                                    an installed client cert. callback should be called again
00821                                    (it returned < 0 indicated that it wants to be called
00822                                    later). Not possible in our case */
00823                                 BUG("unsupported SSL_ERROR_WANT_X509_LOOKUP");
00824                                 goto bug;
00825                         case SSL_ERROR_SYSCALL:
00826                                 TLS_ERR_RET(x, err_src);
00827                                 if (!x) {
00828                                         if (n == 0) {
00829                                                 WARN("Unexpected EOF\n");
00830                                         } else
00831                                                 /* should never happen */
00832                                                 BUG("IO error (%d) %s\n", errno, strerror(errno));
00833                                 }
00834                                 goto error;
00835                         default:
00836                                 TLS_ERR(err_src);
00837                                 BUG("unexpected SSL error %d\n", ssl_error);
00838                                 goto bug;
00839                 }
00840         } else if (unlikely(n < (len - offs))) {
00841                 /* partial ssl write (possible if SSL_MODE_ENABLE_PARTIAL_WRITE) =>
00842                    retry with the rest */
00843                 TLS_WR_TRACE("(%p) partial write (%d < %d, offset %d), retry\n",
00844                                                 c, n, len - offs, offs);
00845                 offs += n;
00846                 goto redo_wr;
00847         }
00848         tls_set_mbufs(c, 0, 0);
00849 end:
00850         *pbuf = (const char*)wr.buf;
00851         *plen = wr.used;
00852         TLS_WR_TRACE("(%p) end (offs %d, rest_buf=%p rest_len=%d 0x%0x) => %d \n",
00853                                         c, offs, *rest_buf, *rest_len, send_flags->f, *plen);
00854         return *plen;
00855 error:
00856 /*error_send:*/
00857 error_wq_full:
00858 bug:
00859         tls_set_mbufs(c, 0, 0);
00860         TLS_WR_TRACE("(%p) end error (offs %d, %d encoded) => -1\n",
00861                                         c, offs, wr.used);
00862         return -1;
00863 ssl_eof:
00864         c->state = S_CONN_EOF;
00865         c->flags |= F_CONN_FORCE_EOF;
00866         *pbuf = (const char*)wr.buf;
00867         *plen = wr.used;
00868         DBG("TLS connection has been closed\n");
00869         TLS_WR_TRACE("(%p) end EOF (offs %d) => (%d\n",
00870                                         c, offs, *plen);
00871         return *plen;
00872 }
00873 
00874 
00875 
00902 int tls_read_f(struct tcp_connection* c, int* flags)
00903 {
00904         struct tcp_req* r;
00905         int bytes_free, bytes_read, read_size, ssl_error, ssl_read;
00906         SSL* ssl;
00907         unsigned char rd_buf[TLS_RD_MBUF_SZ];
00908         unsigned char wr_buf[TLS_WR_MBUF_SZ];
00909         struct tls_mbuf rd, wr;
00910         struct tls_extra_data* tls_c;
00911         struct tls_rd_buf* enc_rd_buf;
00912         int n, flush_flags;
00913         char* err_src;
00914         int x;
00915         int tls_dbg;
00916         
00917         TLS_RD_TRACE("(%p, %p (%d)) start (%s -> %s:%d*)\n",
00918                                         c, flags, *flags,
00919                                         su2a(&c->rcv.src_su, sizeof(c->rcv.src_su)),
00920                                         ip_addr2a(&c->rcv.dst_ip), c->rcv.dst_port);
00921         ssl_read = 0;
00922         r = &c->req;
00923         enc_rd_buf = 0;
00924         *flags &= ~RD_CONN_REPEAT_READ;
00925         if (unlikely(tls_fix_connection(c) < 0)) {
00926                 TLS_RD_TRACE("(%p, %p) end: tls_fix_connection failed =>"
00927                                                 " immediate error exit\n", c, flags);
00928                 return -1;
00929         }
00930         /* here it's safe to use c->extra_data in read-only mode.
00931            If it's != 0 is changed only on destroy. It's not possible to have
00932            parallel reads.*/
00933         tls_c = c->extra_data;
00934         bytes_free = c->req.b_size - (int)(r->pos - r->buf);
00935         if (unlikely(bytes_free == 0)) {
00936                 ERR("Buffer overrun, dropping\n");
00937                 r->error = TCP_REQ_OVERRUN;
00938                 return -1;
00939         }
00940 redo_read:
00941         /* if data queued from a previous read(), use it (don't perform
00942          * a real read()).
00943         */
00944         if (unlikely(tls_c->enc_rd_buf)) {
00945                 /* use queued data */
00946                 /* safe to use without locks, because only read changes it and
00947                    there can't be parallel reads on the same connection */
00948                 enc_rd_buf = tls_c->enc_rd_buf;
00949                 tls_c->enc_rd_buf = 0;
00950                 TLS_RD_TRACE("(%p, %p) using queued data (%p: %p %d bytes)\n", c,
00951                                         flags, enc_rd_buf, enc_rd_buf->buf + enc_rd_buf->pos,
00952                                         enc_rd_buf->size - enc_rd_buf->pos);
00953                 tls_mbuf_init(&rd, enc_rd_buf->buf + enc_rd_buf->pos,
00954                                                 enc_rd_buf->size - enc_rd_buf->pos);
00955                 rd.used = enc_rd_buf->size - enc_rd_buf->pos;
00956         } else {
00957                 /* if we were using using queued data before, free & reset the
00958                         the queued read data before performing the real read() */
00959                 if (unlikely(enc_rd_buf)) {
00960                         TLS_RD_TRACE("(%p, %p) reset prev. used enc_rd_buf (%p)\n", c,
00961                                                         flags, enc_rd_buf);
00962                         shm_free(enc_rd_buf);
00963                         enc_rd_buf = 0;
00964                 }
00965                 /* real read() */
00966                 tls_mbuf_init(&rd, rd_buf, sizeof(rd_buf));
00967                 /* read() only if no previously detected EOF, or previous
00968                    short read (which means the socket buffer was emptied) */
00969                 if (likely(!(*flags & (RD_CONN_EOF|RD_CONN_SHORT_READ)))) {
00970                         /* don't read more then the free bytes in the tcp req buffer */
00971                         read_size = MIN_unsigned(rd.size, bytes_free);
00972                         bytes_read = tcp_read_data(c->fd, c, (char*)rd.buf, read_size,
00973                                                                                 flags);
00974                         TLS_RD_TRACE("(%p, %p) tcp_read_data(..., %d, *%d) => %d bytes\n",
00975                                                 c, flags, read_size, *flags, bytes_read);
00976                         /* try SSL_read even on 0 bytes read, it might have
00977                            internally buffered data */
00978                         if (unlikely(bytes_read < 0)) {
00979                                         goto error;
00980                         }
00981                         rd.used = bytes_read;
00982                 }
00983         }
00984         
00985 continue_ssl_read:
00986         tls_mbuf_init(&wr, wr_buf, sizeof(wr_buf));
00987         ssl_error = SSL_ERROR_NONE;
00988         err_src = "TLS read:";
00989         /* we have to avoid to run in the same time 
00990          * with a tls_write because of the
00991          * update bio stuff  (we don't want a write
00992          * stealing the wbio or rbio under us or vice versa)
00993          * => lock on con->write_lock (ugly hack) */
00994         lock_get(&c->write_lock);
00995                 tls_set_mbufs(c, &rd, &wr);
00996                 ssl = tls_c->ssl;
00997                 n = 0;
00998                 if (unlikely(tls_write_wants_read(tls_c) &&
00999                                                 !(*flags & RD_CONN_EOF))) {
01000                         n = tls_ct_wq_flush(c, &tls_c->ct_wq, &flush_flags,
01001                                                                 &ssl_error);
01002                         TLS_RD_TRACE("(%p, %p) tls write on read (WRITE_WANTS_READ):"
01003                                                         " ct_wq_flush()=> %d (ff=%d ssl_error=%d))\n",
01004                                                         c, flags, n, flush_flags, ssl_error);
01005                         if (unlikely(n < 0 )) {
01006                                 tls_set_mbufs(c, 0, 0);
01007                                 lock_release(&c->write_lock);
01008                                 ERR("write flush error (%d)\n", n);
01009                                 goto error;
01010                         }
01011                         if (likely(flush_flags & F_BUFQ_EMPTY))
01012                                 tls_c->flags &= ~F_TLS_CON_WR_WANTS_RD;
01013                         if (unlikely(flush_flags & F_BUFQ_ERROR_FLUSH))
01014                                 err_src = "TLS write:";
01015                 }
01016                 if (likely(ssl_error == SSL_ERROR_NONE)) {
01017                         if (unlikely(tls_c->state == S_TLS_CONNECTING)) {
01018                                 n = tls_connect(c, &ssl_error);
01019                                 TLS_RD_TRACE("(%p, %p) tls_connect() => %d (err=%d)\n",
01020                                                                 c, flags, n, ssl_error);
01021                                 if (unlikely(n>=1)) {
01022                                         n = SSL_read(ssl, r->pos, bytes_free);
01023                                 } else {
01024                                         /* tls_connect failed/needs more IO */
01025                                         if (unlikely(n < 0 && ssl_error == SSL_ERROR_NONE)) {
01026                                                 lock_release(&c->write_lock);
01027                                                 goto error;
01028                                         }
01029                                         err_src = "TLS connect:";
01030                                         goto ssl_read_skipped;
01031                                 }
01032                         } else if (unlikely(tls_c->state == S_TLS_ACCEPTING)) {
01033                                 n = tls_accept(c, &ssl_error);
01034                                 TLS_RD_TRACE("(%p, %p) tls_accept() => %d (err=%d)\n",
01035                                                                 c, flags, n, ssl_error);
01036                                 if (unlikely(n>=1)) {
01037                                         n = SSL_read(ssl, r->pos, bytes_free);
01038                                 } else {
01039                                         /* tls_accept failed/needs more IO */
01040                                         if (unlikely(n < 0 && ssl_error == SSL_ERROR_NONE)) {
01041                                                 lock_release(&c->write_lock);
01042                                                 goto error;
01043                                         }
01044                                         err_src = "TLS accept:";
01045                                         goto ssl_read_skipped;
01046                                 }
01047                         } else {
01048                                 /* if bytes in then decrypt read buffer into tcpconn req.
01049                                    buffer */
01050                                 n = SSL_read(ssl, r->pos, bytes_free);
01051                         }
01101                         if (unlikely(tls_c->flags & F_TLS_CON_RENEGOTIATION)) {
01102                                 /* Fix CVE-2009-3555 - disable renegotiation if started by client
01103                                  * - simulate SSL EOF to force close connection*/
01104                                 tls_dbg = cfg_get(tls, tls_cfg, debug);
01105                                 LOG(tls_dbg, "Reading on a renegotiation of connection (n:%d) (%d)\n",
01106                                                 n, SSL_get_error(ssl, n));
01107                                 err_src = "TLS R-N read:";
01108                                 ssl_error = SSL_ERROR_ZERO_RETURN;
01109                         } else {
01110                                 if (unlikely(n <= 0)) {
01111                                         ssl_error = SSL_get_error(ssl, n);
01112                                         err_src = "TLS read:";
01113                                         /*  errors handled below, outside the lock */
01114                                 } else {
01115                                         ssl_error = SSL_ERROR_NONE;
01116                                         r->pos += n;
01117                                         ssl_read += n;
01118                                         bytes_free -=n;
01119                                 }
01120                         }
01121                         TLS_RD_TRACE("(%p, %p) SSL_read() => %d (err=%d) ssl_read=%d"
01122                                                         " *flags=%d tls_c->flags=%d\n",
01123                                                         c, flags, n, ssl_error, ssl_read, *flags,
01124                                                         tls_c->flags);
01125 ssl_read_skipped:
01126                         ;
01127                 }
01128                 if (unlikely(wr.used != 0 && ssl_error != SSL_ERROR_ZERO_RETURN)) {
01129                         TLS_RD_TRACE("(%p, %p) tcpconn_send_unsafe %d bytes\n",
01130                                                         c, flags, wr.used);
01131                         /* something was written and it's not ssl EOF*/
01132                         if (unlikely(tcpconn_send_unsafe(c->fd, c, (char*)wr.buf,
01133                                                                                         wr.used, c->send_flags) < 0)) {
01134                                 tls_set_mbufs(c, 0, 0);
01135                                 lock_release(&c->write_lock);
01136                                 TLS_RD_TRACE("(%p, %p) tcpconn_send_unsafe error\n", c, flags);
01137                                 goto error_send;
01138                         }
01139                 }
01140         /* quickly catch bugs: segfault if accessed and not set */
01141         tls_set_mbufs(c, 0, 0);
01142         lock_release(&c->write_lock);
01143         switch(ssl_error) {
01144                 case SSL_ERROR_NONE:
01145                         if (unlikely(n < 0)) {
01146                                 BUG("unexpected SSL_ERROR_NONE for n=%d\n", n);
01147                                 goto error;
01148                         }
01149                         break;
01150                 case SSL_ERROR_ZERO_RETURN:
01151                         /* SSL EOF */
01152                         TLS_RD_TRACE("(%p, %p) SSL EOF (fd=%d)\n", c, flags, c->fd);
01153                         goto ssl_eof;
01154                 case SSL_ERROR_WANT_READ:
01155                         TLS_RD_TRACE("(%p, %p) SSL_ERROR_WANT_READ *flags=%d\n",
01156                                                         c, flags, *flags);
01157                         /* needs to read more data */
01158                         if (unlikely(rd.pos != rd.used)) {
01159                                 /* data still in the read buffer */
01160                                 BUG("SSL_ERROR_WANT_READ but data still in"
01161                                                 " the rbio (%p, %d bytes at %d)\n", rd.buf,
01162                                                 rd.used - rd.pos, rd.pos);
01163                                 goto bug;
01164                         }
01165                         if (unlikely((*flags & (RD_CONN_EOF | RD_CONN_SHORT_READ)) == 0) &&
01166                                                         bytes_free){
01167                                 /* there might still be data to read and there is space
01168                                    to decrypt it in tcp_req (no byte has been written into
01169                                     tcp_req in this case) */
01170                                 TLS_RD_TRACE("(%p, %p) redo read *flags=%d bytes_free=%d\n",
01171                                                                 c, flags, *flags, bytes_free);
01172                                 goto redo_read;
01173                         }
01174                         goto end; /* no more data to read */
01175                 case SSL_ERROR_WANT_WRITE:
01176                         if (wr.used) {
01177                                 /* something was written => buffer not big enough to hold
01178                                    everything => reset buffer & retry (the tcp_write already
01179                                    happened if we are here) */
01180                                 TLS_RD_TRACE("(%p) SSL_ERROR_WANT_WRITE partial write"
01181                                                         " (written  %d), retrying\n", c, wr.used);
01182                                 goto continue_ssl_read;
01183                         }
01184                         /* else write buffer too small, nothing written */
01185                         BUG("write buffer too small (%d/%d bytes)\n",
01186                                                 wr.used, wr.size);
01187                         goto bug;
01188                 case SSL_ERROR_SSL:
01189                         /* protocol level error */
01190                         TLS_ERR(err_src);
01191                         goto error;
01192 #if OPENSSL_VERSION_NUMBER >= 0x00907000L /*0.9.7*/
01193                 case SSL_ERROR_WANT_CONNECT:
01194                         /* only if the underlying BIO is not yet connected
01195                            and the call would block in connect().
01196                            (not possible in our case) */
01197                         BUG("unexpected SSL_ERROR_WANT_CONNECT\n");
01198                         goto bug;
01199                 case SSL_ERROR_WANT_ACCEPT:
01200                         /* only if the underlying BIO is not yet connected
01201                            and call would block in accept()
01202                            (not possible in our case) */
01203                         BUG("unexpected SSL_ERROR_WANT_ACCEPT\n");
01204                         goto bug;
01205 #endif
01206                 case SSL_ERROR_WANT_X509_LOOKUP:
01207                         /* can only appear on client application and it indicates that
01208                            an installed client cert. callback should be called again
01209                            (it returned < 0 indicated that it wants to be called
01210                            later). Not possible in our case */
01211                         BUG("unsupported SSL_ERROR_WANT_X509_LOOKUP");
01212                         goto bug;
01213                 case SSL_ERROR_SYSCALL:
01214                         TLS_ERR_RET(x, err_src);
01215                         if (!x) {
01216                                 if (n == 0) {
01217                                         WARN("Unexpected EOF\n");
01218                                 } else
01219                                         /* should never happen */
01220                                         BUG("IO error (%d) %s\n", errno, strerror(errno));
01221                         }
01222                         goto error;
01223                 default:
01224                         TLS_ERR(err_src);
01225                         BUG("unexpected SSL error %d\n", ssl_error);
01226                         goto bug;
01227         }
01228         if (unlikely(n < 0)) {
01229                 /* here n should always be >= 0 */
01230                 BUG("unexpected value (n = %d)\n", n);
01231                 goto bug;
01232         }
01233         if (unlikely(rd.pos != rd.used)) {
01234                 /* encrypted data still in the read buffer (SSL_read() did not
01235                    consume all of it) */
01236                 if (unlikely(n < 0))
01237                         /* here n should always be >= 0 */
01238                         BUG("unexpected value (n = %d)\n", n);
01239                 else {
01240                         if (unlikely(bytes_free != 0)) {
01241                                 /* 2i or 2ip: unconsumed input and output buffer not filled =>
01242                                   retry ssl read (SSL_read() will read will stop at
01243                                   record boundaries, unless readahead==1).
01244                                   No tcp_read() is attempted, since that would reset the
01245                                   current no-yet-consumed input data.
01246                                  */
01247                                 TLS_RD_TRACE("(%p, %p) input not fully consumed =>"
01248                                                                 " retry SSL_read"
01249                                                                 " (pos: %d, remaining %d, output free %d)\n",
01250                                                                 c, flags, rd.pos, rd.used-rd.pos, bytes_free);
01251                                 goto continue_ssl_read;
01252                         }
01253                         /* 1i or 1ip: bytes_free == 0
01254                            (unconsumed input, but filled output  buffer) =>
01255                             queue read data, and exit asking for repeating the call
01256                             once there is some space in the output buffer.
01257                          */
01258                         if (likely(!enc_rd_buf)) {
01259                                 TLS_RD_TRACE("(%p, %p) creating enc_rd_buf (for %d bytes)\n",
01260                                                                 c, flags, rd.used - rd.pos);
01261                                 enc_rd_buf = shm_malloc(sizeof(*enc_rd_buf) -
01262                                                                                 sizeof(enc_rd_buf->buf) +
01263                                                                                 rd.used - rd.pos);
01264                                 if (unlikely(enc_rd_buf == 0)) {
01265                                         ERR("memory allocation error (%d bytes requested)\n",
01266                                                 (int)(sizeof(*enc_rd_buf) + sizeof(enc_rd_buf->buf) +
01267                                                                                 rd.used - rd.pos));
01268                                         goto error;
01269                                 }
01270                                 enc_rd_buf->pos = 0;
01271                                 enc_rd_buf->size = rd.used - rd.pos;
01272                                 memcpy(enc_rd_buf->buf, rd.buf + rd.pos,
01273                                                                                 enc_rd_buf->size);
01274                         } else if ((enc_rd_buf->buf + enc_rd_buf->pos) == rd.buf) {
01275                                 TLS_RD_TRACE("(%p, %p) enc_rd_buf already in use,"
01276                                                                 " updating pos %d\n",
01277                                                                 c, flags, enc_rd_buf->pos);
01278                                 enc_rd_buf->pos += rd.pos;
01279                         } else {
01280                                 BUG("enc_rd_buf->buf = %p, pos = %d, rd_buf.buf = %p\n",
01281                                                 enc_rd_buf->buf, enc_rd_buf->pos, rd.buf);
01282                                 goto bug;
01283                         }
01284                         if (unlikely(tls_c->enc_rd_buf))
01285                                 BUG("tls_c->enc_rd_buf!=0 (%p)\n", tls_c->enc_rd_buf);
01286                         /* there can't be 2 reads in parallel, so no locking is needed
01287                            here */
01288                         tls_c->enc_rd_buf = enc_rd_buf;
01289                         enc_rd_buf = 0;
01290                         *flags |= RD_CONN_REPEAT_READ;
01291                 }
01292         } else if (bytes_free != 0) {
01293                 /*  2f or 2p: input fully consumed (rd.pos == rd.used),
01294                     output buffer not filled, still possible to have pending
01295                     data buffered by openssl */
01296                 if (unlikely((*flags & (RD_CONN_EOF|RD_CONN_SHORT_READ)) == 0)) {
01297                         /* still space in the tcp unenc. req. buffer, no SSL_read error,
01298                            not a short read and not an EOF (possible more data in
01299                            the socket buffer) => try a new tcp read too */
01300                         TLS_RD_TRACE("(%p, %p) retry read (still space and no short"
01301                                                         " tcp read: %d)\n", c, flags, *flags);
01302                         goto redo_read;
01303                 } else {
01304                         /* don't tcp_read() anymore, but there might still be data
01305                            buffered internally by openssl (e.g. if readahead==1) =>
01306                            retry SSL_read() with the current full input buffer
01307                            (if no more internally SSL buffered data => WANT_READ => exit).
01308                          */
01309                         TLS_RD_TRACE("(%p, %p) retry SSL_read only (*flags =%d)\n",
01310                                                         c, flags, *flags);
01311                         goto continue_ssl_read;
01312                 }
01313         } else {
01314                 /*   1p or 1f: rd.pos == rd.used && bytes_free == 0
01315                          (input fully consumed && output buffer filled) */
01316                 /* ask for a repeat when there is more buffer space
01317                    (there is no definitive way to know if ssl doesn't still have
01318                     some internal buffered data until we get WANT_READ, see
01319                         SSL_read() comment above) */
01320                 *flags |= RD_CONN_REPEAT_READ;
01321                 TLS_RD_TRACE("(%p, %p) output filled, exit asking to be called again"
01322                                                 " (*flags =%d)\n", c, flags, *flags);
01323         }
01324         
01325 end:
01326         if (enc_rd_buf)
01327                 shm_free(enc_rd_buf);
01328         TLS_RD_TRACE("(%p, %p) end => %d (*flags=%d)\n",
01329                                         c, flags, ssl_read, *flags);
01330         return ssl_read;
01331 ssl_eof:
01332         /* behave as an EOF would have been received at the tcp level */
01333         if (enc_rd_buf)
01334                 shm_free(enc_rd_buf);
01335         c->state = S_CONN_EOF;
01336         *flags |= RD_CONN_EOF;
01337         TLS_RD_TRACE("(%p, %p) end EOF => %d (*flags=%d)\n",
01338                                         c, flags, ssl_read, *flags);
01339         return ssl_read;
01340 error_send:
01341 error:
01342 bug:
01343         if (enc_rd_buf)
01344                 shm_free(enc_rd_buf);
01345         r->error=TCP_READ_ERROR;
01346         TLS_RD_TRACE("(%p, %p) end error => %d (*flags=%d)\n",
01347                                         c, flags, ssl_read, *flags);
01348         return -1;
01349 }