1 /* -*- Mode: C; c-file-style: "bsd" -*- */
3 * easy-tls.c -- generic TLS proxy.
4 * $Id: easy-tls.c,v 1.4 2002/03/05 09:07:16 bodo Exp $
7 (c) Copyright 1999 Bodo Moeller. All rights reserved.
9 This is free software; you can redistributed and/or modify it
10 unter the terms of either
11 - the GNU General Public License as published by the
12 Free Software Foundation, version 1, or (at your option)
15 - the following license:
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that each of the following
22 * 1. Redistributions qualify as "freeware" or "Open Source Software" under
23 * one of the following terms:
25 * (a) Redistributions are made at no charge beyond the reasonable cost of
26 * materials and delivery.
28 * (b) Redistributions are accompanied by a copy of the Source Code
29 * or by an irrevocable offer to provide a copy of the Source Code
30 * for up to three years at the cost of materials and delivery.
31 * Such redistributions must allow further use, modification, and
32 * redistribution of the Source Code under substantially the same
33 * terms as this license.
35 * 2. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
38 * 3. Redistributions in binary form must reproduce the above copyright
39 * notice, this list of conditions and the following disclaimer in
40 * the documentation and/or other materials provided with the
43 * 4. All advertising materials mentioning features or use of this
44 * software must display the following acknowledgment:
45 * "This product includes software developed by Bodo Moeller."
46 * (If available, substitute umlauted o for oe.)
48 * 5. Redistributions of any form whatsoever must retain the following
50 * "This product includes software developed by Bodo Moeller."
52 * THIS SOFTWARE IS PROVIDED BY BODO MOELLER ``AS IS'' AND ANY
53 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
55 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BODO MOELLER OR
56 * HIS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
57 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
58 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
59 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
61 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
62 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
63 * OF THE POSSIBILITY OF SUCH DAMAGE.
66 * Attribution for OpenSSL library:
68 * This product includes cryptographic software written by Eric Young
69 * (eay@cryptsoft.com). This product includes software written by Tim
70 * Hudson (tjh@cryptsoft.com).
71 * This product includes software developed by the OpenSSL Project
72 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)
75 static char const rcsid[] =
76 "$Id: easy-tls.c,v 1.4 2002/03/05 09:07:16 bodo Exp $";
85 #include <sys/select.h>
86 #include <sys/socket.h>
89 #include <sys/types.h>
90 #include <sys/utsname.h>
93 #include <openssl/crypto.h>
94 #include <openssl/dh.h>
95 #include <openssl/dsa.h>
96 #include <openssl/err.h>
97 #include <openssl/evp.h>
98 #include <openssl/opensslv.h>
99 #include <openssl/pem.h>
100 #include <openssl/rand.h>
102 #include <openssl/rsa.h>
104 #include <openssl/ssl.h>
105 #include <openssl/x509.h>
106 #include <openssl/x509_vfy.h>
108 #if OPENSSL_VERSION_NUMBER < 0x00904000L /* 0.9.4-dev */
109 # error "This program needs OpenSSL 0.9.4 or later."
112 #include "easy-tls.h" /* include after <openssl/ssl.h> if both are needed */
114 #if TLS_INFO_SIZE > PIPE_BUF
116 # error "PIPE_BUF < 512" /* non-POSIX */
118 # error "TLS_INFO_SIZE > PIPE_BUF"
121 /*****************************************************************************/
127 /* Applications can define:
128 * TLS_APP_PROCESS_INIT -- void ...(int fd, int client_p, void *apparg)
129 * TLS_CUMULATE_ERRORS
131 * TLS_APP_ERRFLUSH -- void ...(int child_p, char *, size_t, void *apparg)
134 #ifndef TLS_APP_PROCESS_INIT
135 # define TLS_APP_PROCESS_INIT(fd, client_p, apparg) ((void) 0)
138 #ifndef TLS_ERROR_BUFSIZ
139 # define TLS_ERROR_BUFSIZ (10*160)
141 #if TLS_ERROR_BUFSIZ < 2 /* {'\n',0} */
142 # error "TLS_ERROR_BUFSIZE is too small."
145 #ifndef TLS_APP_ERRFLUSH
146 # define TLS_APP_ERRFLUSH tls_app_errflush
148 tls_app_errflush(int child_p, char *errbuf, size_t num, void *apparg)
150 fputs(errbuf, stderr);
154 /*****************************************************************************/
157 # define DEBUG_MSG(x) fprintf(stderr," %s\n",x)
158 # define DEBUG_MSG2(x,y) fprintf(stderr, " %s: %d\n",x,y)
159 static int tls_loop_count = 0;
160 static int tls_select_count = 0;
162 # define DEBUG_MSG(x) (void)0
163 # define DEBUG_MSG2(x,y) (void)0
166 static void tls_rand_seed_uniquely(void);
167 static void tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p);
168 static int tls_socket_nonblocking(int fd);
170 static int tls_child_p = 0;
171 static void *tls_child_apparg;
174 struct tls_start_proxy_args
175 tls_start_proxy_defaultargs(void)
177 struct tls_start_proxy_args ret;
188 /* Slice in TLS proxy process at fd.
190 * 0 ok (*pid is set to child's PID if pid != NULL),
193 * (return value encodes place of error)
197 tls_start_proxy(struct tls_start_proxy_args a, void *apparg)
199 int fds[2] = {-1, -1};
200 int infofds[2] = {-1, -1};
204 DEBUG_MSG2("tls_start_proxy fd", a.fd);
205 DEBUG_MSG2("tls_start_proxy client_p", a.client_p);
207 if (a.fd == -1 || a.client_p == -1 || a.ctx == NULL)
213 if (a.infofd != NULL) {
217 r = socketpair(AF_UNIX, SOCK_STREAM, 0, fds);
220 if (a.fd >= FD_SETSIZE || fds[0] >= FD_SETSIZE) {
224 if (a.infofd != NULL) {
240 tls_child_apparg = apparg;
242 if (infofds[0] != -1)
244 TLS_APP_PROCESS_INIT(a.fd, a.client_p, apparg);
245 DEBUG_MSG("TLS_APP_PROCESS_INIT");
246 tls_proxy(fds[0], a.fd, infofds[1], a.ctx, a.client_p);
251 if (infofds[1] != -1) {
255 /* install fds[1] in place of fd: */
258 getfd = fcntl(a.fd, F_GETFD);
259 getfl = fcntl(a.fd, F_GETFL);
260 r = dup2(fds[1], a.fd);
268 fcntl(a.fd, F_SETFD, getfd);
269 if (getfl & O_NONBLOCK)
270 (void)tls_socket_nonblocking(a.fd);
271 if (a.infofd != NULL)
272 *a.infofd = infofds[0];
280 if (infofds[0] != -1)
282 if (infofds[1] != -1)
287 /*****************************************************************************/
289 static char errbuf[TLS_ERROR_BUFSIZ];
290 static size_t errbuf_i = 0;
293 tls_errflush(void *apparg)
298 assert(errbuf_i < sizeof errbuf);
299 assert(errbuf[errbuf_i] == 0);
300 if (errbuf_i == sizeof errbuf - 1) {
301 /* make sure we have a newline, even if string has been truncated */
302 errbuf[errbuf_i - 1] = '\n';
305 /* TLS_APP_ERRFLUSH may modify the string as needed,
306 * e.g. substitute other characters for \n for convenience */
307 TLS_APP_ERRFLUSH(tls_child_p, errbuf, errbuf_i, apparg);
313 tls_errprintf(int flush, void *apparg, const char *fmt, ...)
318 if (errbuf_i < sizeof errbuf - 1) {
322 n = (sizeof errbuf) - errbuf_i;
323 r = vsnprintf(errbuf + errbuf_i, n, fmt, args);
329 errbuf_i = sizeof errbuf - 1;
330 errbuf[errbuf_i] = '\0';
332 assert(errbuf_i < sizeof errbuf);
333 assert(errbuf[errbuf_i] == 0);
335 #ifndef TLS_CUMULATE_ERRORS
336 tls_errflush(apparg);
339 tls_errflush(apparg);
343 /* app_prefix.. are for additional information provided by caller.
344 * If OpenSSL error queue is empty, print default_text ("???" if NULL).
347 tls_openssl_errors(const char *app_prefix_1, const char *app_prefix_2, const char *default_text, void *apparg)
349 static char reasons[255];
357 int printed_something = 0;
361 assert(app_prefix_1 != NULL);
362 assert(app_prefix_2 != NULL);
364 if (default_text == NULL)
365 default_text = "?""?""?";
367 while ((err = ERR_get_error_line_data(&file,&line,&data,&flags)) != 0) {
368 if (reasons_i < sizeof reasons) {
372 n = (sizeof reasons) - reasons_i;
373 r = snprintf(reasons + reasons_i, n, "%s%s", (reasons_i > 0 ? ", " : ""), ERR_reason_error_string(err));
379 reasons_i = sizeof reasons;
381 assert(reasons_i <= sizeof reasons);
384 errstring = ERR_error_string(err, NULL);
385 assert(errstring != NULL);
386 tls_errprintf(0, apparg, "OpenSSL error%s%s: %s:%s:%d:%s\n", app_prefix_1, app_prefix_2, errstring, file, line, (flags & ERR_TXT_STRING) ? data : "");
387 printed_something = 1;
390 if (!printed_something) {
391 assert(reasons_i == 0);
392 snprintf(reasons, sizeof reasons, "%s", default_text);
393 tls_errprintf(0, apparg, "OpenSSL error%s%s: %s\n", app_prefix_1, app_prefix_2, default_text);
396 #ifdef TLS_CUMULATE_ERRORS
397 tls_errflush(apparg);
399 assert(errbuf_i == 0);
404 /*****************************************************************************/
406 static int tls_init_done = 0;
409 tls_init(void *apparg)
414 SSL_load_error_strings();
415 if (!SSL_library_init() /* aka SSLeay_add_ssl_algorithms() */ ) {
416 tls_errprintf(1, apparg, "SSL_library_init failed.\n");
424 /*****************************************************************************/
427 tls_rand_seed_uniquely(void)
436 data.time = time(NULL);
437 data.stack = (void *)&data;
439 RAND_seed((const void *)&data, sizeof data);
446 struct utsname uname;
455 data.uname_1 = uname(&data.uname);
456 data.uname_2 = errno; /* Let's hope that uname fails randomly :-) */
459 data.euid = geteuid();
461 data.egid = getegid();
463 RAND_seed((const void *)&data, sizeof data);
464 tls_rand_seed_uniquely();
467 static int tls_rand_seeded_p = 0;
469 #define my_MIN_SEED_BYTES 256 /* struct stat can be larger than 128 */
471 tls_rand_seed_from_file(const char *filename, size_t n, void *apparg)
473 /* Seed OpenSSL's random number generator from file.
474 Try to read n bytes if n > 0, whole file if n == 0. */
478 if (tls_init(apparg) == -1)
482 r = RAND_load_file(filename, (n > 0 && n < LONG_MAX) ? (long)n : LONG_MAX);
483 /* r is the number of bytes filled into the random number generator,
484 * which are taken from "stat(filename, ...)" in addition to the
487 assert(1 < my_MIN_SEED_BYTES);
488 /* We need to detect at least those cases when the file does not exist
489 * at all. With current versions of OpenSSL, this should do it: */
491 n = my_MIN_SEED_BYTES;
493 tls_errprintf(1, apparg, "rand_seed_from_file: could not read %d bytes from %s.\n", n, filename);
496 tls_rand_seeded_p = 1;
502 tls_rand_seed_from_memory(const void *buf, size_t n)
508 int chunk = rest < INT_MAX ? (int)rest : INT_MAX;
509 RAND_seed((const char *)buf + i, chunk);
512 tls_rand_seeded_p = 1;
516 /*****************************************************************************/
518 struct tls_x509_name_string {
523 tls_get_x509_subject_name_oneline(X509 *cert, struct tls_x509_name_string *namestring)
528 namestring->str[0] = '\0';
532 name = X509_get_subject_name(cert); /* does not increment any reference counter */
534 assert(sizeof namestring->str >= 4); /* "?" or "...", plus 0 */
537 namestring->str[0] = '?';
538 namestring->str[1] = 0;
542 X509_NAME_oneline(name, namestring->str, sizeof namestring->str);
543 len = strlen(namestring->str);
544 assert(namestring->str[len] == 0);
545 assert(len < sizeof namestring->str);
547 if (len+1 == sizeof namestring->str) {
548 /* (Probably something was cut off.)
549 * Does not really work -- X509_NAME_oneline truncates after
550 * name components, we cannot tell from the result whether
551 * anything is missing. */
553 assert(namestring->str[len] == 0);
554 namestring->str[--len] = '.';
555 namestring->str[--len] = '.';
556 namestring->str[--len] = '.';
561 /*****************************************************************************/
563 /* to hinder OpenSSL from asking for passphrases */
565 no_passphrase_callback(char *buf, int num, int w, void *arg)
570 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
572 verify_dont_fail_cb(X509_STORE_CTX *c, void *unused_arg)
575 verify_dont_fail_cb(X509_STORE_CTX *c)
580 i = X509_verify_cert(c); /* sets c->error */
581 #if OPENSSL_VERSION_NUMBER >= 0x00905000L /* don't allow unverified
582 * certificates -- they could
583 * survive session reuse, but
584 * OpenSSL < 0.9.5-dev does not
585 * preserve their verify_result */
593 static DH *tls_dhe1024 = NULL; /* generating these takes a while, so do it just once */
596 tls_set_dhe1024(int i, void *apparg)
600 const char *seed[] = { ";-) :-( :-) :-( ",
602 "Random String no. 12",
604 "hackers have even mo", /* from jargon file */
606 unsigned char seedbuf[20];
610 i %= sizeof seed / sizeof seed[0];
611 assert(strlen(seed[i]) == 20);
612 memcpy(seedbuf, seed[i], 20);
613 dsaparams = DSA_generate_parameters(1024, seedbuf, 20, NULL, NULL, 0, NULL);
615 /* random parameters (may take a while) */
616 dsaparams = DSA_generate_parameters(1024, NULL, 0, NULL, NULL, 0, NULL);
619 if (dsaparams == NULL) {
620 tls_openssl_errors("", "", NULL, apparg);
623 dhparams = DSA_dup_DH(dsaparams);
625 if (dhparams == NULL) {
626 tls_openssl_errors("", "", NULL, apparg);
629 if (tls_dhe1024 != NULL)
630 DH_free(tls_dhe1024);
631 tls_dhe1024 = dhparams;
634 struct tls_create_ctx_args
635 tls_create_ctx_defaultargs(void)
637 struct tls_create_ctx_args ret;
640 ret.certificate_file = NULL;
643 ret.verify_depth = -1;
644 ret.fail_unless_verified = 0;
651 tls_create_ctx(struct tls_create_ctx_args a, void *apparg)
654 static long context_num = 0;
656 const char *err_pref_1 = "", *err_pref_2 = "";
658 if (tls_init(apparg) == -1)
661 ret = SSL_CTX_new((a.client_p? SSLv23_client_method:SSLv23_server_method)());
666 SSL_CTX_set_default_passwd_cb(ret, no_passphrase_callback);
667 SSL_CTX_set_mode(ret, SSL_MODE_ENABLE_PARTIAL_WRITE);
669 if ((a.certificate_file != NULL) || (a.key_file != NULL)) {
670 if (a.key_file == NULL) {
671 tls_errprintf(1, apparg, "Need a key file.\n");
674 if (a.certificate_file == NULL) {
675 tls_errprintf(1, apparg, "Need a certificate chain file.\n");
679 if (!SSL_CTX_use_PrivateKey_file(ret, a.key_file, SSL_FILETYPE_PEM))
681 if (!tls_rand_seeded_p) {
682 /* particularly paranoid people may not like this --
683 * so provide your own random seeding before calling this */
684 if (tls_rand_seed_from_file(a.key_file, 0, apparg) == -1)
687 if (!SSL_CTX_use_certificate_chain_file(ret, a.certificate_file))
689 if (!SSL_CTX_check_private_key(ret)) {
690 tls_errprintf(1, apparg, "Private key \"%s\" does not match certificate \"%s\".\n", a.key_file, a.certificate_file);
695 if ((a.ca_file != NULL) || (a.verify_depth > 0)) {
697 r = SSL_CTX_set_session_id_context(ret, (const void *)&context_num, (unsigned int)sizeof context_num);
701 SSL_CTX_set_verify(ret, SSL_VERIFY_PEER | (a.fail_unless_verified ? SSL_VERIFY_FAIL_IF_NO_PEER_CERT : 0), 0);
702 if (!a.fail_unless_verified)
703 SSL_CTX_set_cert_verify_callback(ret, verify_dont_fail_cb, NULL);
705 if (a.verify_depth > 0)
706 SSL_CTX_set_verify_depth(ret, a.verify_depth);
708 if (a.ca_file != NULL) {
709 r = SSL_CTX_load_verify_locations(ret, a.ca_file, NULL /* no CA-directory */); /* does not report failure if file does not exist ... */
711 err_pref_1 = " while processing certificate file ";
712 err_pref_2 = a.ca_file;
717 /* SSL_load_client_CA_file is a misnomer, it just creates a list of CNs. */
718 SSL_CTX_set_client_CA_list(ret, SSL_load_client_CA_file(a.ca_file));
719 /* SSL_CTX_set_client_CA_list does not have a return value;
720 * it does not really need one, but make sure
721 * (we really test if SSL_load_client_CA_file worked) */
722 if (SSL_CTX_get_client_CA_list(ret) == NULL) {
723 tls_errprintf(1, apparg, "Could not set client CA list from \"%s\".\n", a.ca_file);
731 if (tls_dhe1024 == NULL) {
734 RAND_bytes((unsigned char *) &i, sizeof i);
735 /* make sure that i is non-negative -- pick one of the provided
741 tls_set_dhe1024(i, apparg);
742 if (tls_dhe1024 == NULL)
746 if (!SSL_CTX_set_tmp_dh(ret, tls_dhe1024))
749 /* avoid small subgroup attacks: */
750 SSL_CTX_set_options(ret, SSL_OP_SINGLE_DH_USE);
754 if (!a.client_p && a.export_p) {
757 tmpkey = RSA_generate_key(512, RSA_F4, 0, NULL);
760 if (!SSL_CTX_set_tmp_rsa(ret, tmpkey)) {
764 RSA_free(tmpkey); /* SSL_CTX_set_tmp_rsa uses a duplicate. */
771 if (!ERR_peek_error())
774 tls_openssl_errors(err_pref_1, err_pref_2, NULL, apparg);
782 /*****************************************************************************/
785 tls_socket_nonblocking(int fd)
789 v = fcntl(fd, F_GETFL, 0);
792 return 0; /* already shut down -- ignore */
795 r = fcntl(fd, F_SETFL, v | O_NONBLOCK);
798 return 0; /* already shut down -- ignore */
807 return a > b ? a : b;
811 tls_sockets_select(int read_select_1, int read_select_2, int write_select_1, int write_select_2, int seconds /* timeout, -1 means no timeout */)
814 fd_set reads, writes;
815 struct timeval timeout;
816 struct timeval *timeout_p;
818 assert(read_select_1 >= -1 && read_select_2 >= -1 && write_select_1 >= -1 && write_select_2 >= -1);
819 assert(read_select_1 < FD_SETSIZE && read_select_2 < FD_SETSIZE -1 && write_select_1 < FD_SETSIZE -1 && write_select_2 < FD_SETSIZE -1);
821 maxfd = max(max(read_select_1, read_select_2), max(write_select_1, write_select_2));
827 for(n = 0; n < 4; ++n) {
830 /* loop over all (i, w) in {0,1}x{0,1} */
833 if (i == 0 && w == 0)
835 else if (i == 1 && w == 0)
837 else if (i == 0 && w == 1)
840 assert(i == 1 && w == 1);
853 timeout.tv_sec = seconds;
855 timeout_p = &timeout;
859 DEBUG_MSG2("select no.", ++tls_select_count);
860 select(maxfd + 1, &reads, &writes, (fd_set *) NULL, timeout_p);
864 /*****************************************************************************/
866 #define TUNNELBUFSIZE (16*1024)
868 char buf[TUNNELBUFSIZE];
873 static int tls_connect_attempt(SSL *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
875 static int tls_accept_attempt(SSL *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
877 static int tls_write_attempt(SSL *, struct tunnelbuf *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
879 static int tls_read_attempt(SSL *, struct tunnelbuf *, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref);
881 static int write_attempt(int fd, struct tunnelbuf *, int *select, int *closed, int *progress);
883 static int read_attempt(int fd, struct tunnelbuf *, int *select, int *closed, int *progress);
885 static void write_info(SSL *ssl, int *info_fd)
887 if (*info_fd != -1) {
890 struct tls_x509_name_string peer;
891 char infobuf[TLS_INFO_SIZE];
894 DEBUG_MSG("write_info");
895 v = SSL_get_verify_result(ssl);
896 v_ok = (v == X509_V_OK) ? 'A' : 'E'; /* Auth./Error */
900 peercert = SSL_get_peer_certificate(ssl);
901 tls_get_x509_subject_name_oneline(peercert, &peer);
902 if (peercert != NULL)
905 if (peer.str[0] == '\0')
906 v_ok = '0'; /* no cert at all */
908 if (strchr(peer.str, '\n')) {
909 /* should not happen, but make sure */
910 *strchr(peer.str, '\n') = '\0';
912 r = snprintf(infobuf, sizeof infobuf, "%c:%s\n%s\n", v_ok, X509_verify_cert_error_string(v), peer.str);
913 DEBUG_MSG2("snprintf", r);
914 if (r == -1 || r >= sizeof infobuf)
915 r = sizeof infobuf - 1;
916 write(*info_fd, infobuf, r);
923 /* tls_proxy expects that all fds are closed after return */
925 tls_proxy(int clear_fd, int tls_fd, int info_fd, SSL_CTX *ctx, int client_p)
927 struct tunnelbuf clear_to_tls, tls_to_clear;
930 int closed, in_handshake;
931 const char *err_pref_1 = "", *err_pref_2 = "";
932 const char *err_def = NULL;
934 assert(clear_fd != -1);
935 assert(tls_fd != -1);
936 assert(clear_fd < FD_SETSIZE);
937 assert(tls_fd < FD_SETSIZE);
938 /* info_fd may be -1 */
941 tls_rand_seed_uniquely();
943 tls_socket_nonblocking(clear_fd);
944 DEBUG_MSG2("clear_fd", clear_fd);
945 tls_socket_nonblocking(tls_fd);
946 DEBUG_MSG2("tls_fd", tls_fd);
951 DEBUG_MSG("SSL_new");
952 if (!SSL_set_fd(ssl, tls_fd))
954 rbio = SSL_get_rbio(ssl);
955 wbio = SSL_get_wbio(ssl); /* should be the same, but who cares */
956 assert(rbio != NULL);
957 assert(wbio != NULL);
959 SSL_set_connect_state(ssl);
961 SSL_set_accept_state(ssl);
965 tls_to_clear.len = 0;
966 tls_to_clear.offset = 0;
967 clear_to_tls.len = 0;
968 clear_to_tls.offset = 0;
970 err_def = "I/O error";
972 /* loop finishes as soon as we detect that one side closed;
973 * when all (program and OS) buffers have enough space,
974 * the data from the last succesful read in each direction is transferred
977 int clear_read_select = 0, clear_write_select = 0,
978 tls_read_select = 0, tls_write_select = 0,
981 unsigned long num_read = BIO_number_read(rbio),
982 num_written = BIO_number_written(wbio);
984 DEBUG_MSG2("loop iteration", ++tls_loop_count);
987 DEBUG_MSG("in_handshake");
989 r = tls_connect_attempt(ssl, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
991 r = tls_accept_attempt(ssl, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
993 write_info(ssl, &info_fd);
998 if (!SSL_in_init(ssl)) {
1000 write_info(ssl, &info_fd);
1004 if (clear_to_tls.len != 0 && !in_handshake) {
1007 r = tls_write_attempt(ssl, &clear_to_tls, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
1012 tls_to_clear.offset = 0;
1013 tls_to_clear.len = 0;
1017 if (tls_to_clear.len != 0) {
1020 r = write_attempt(clear_fd, &tls_to_clear, &clear_write_select, &closed, &progress);
1025 clear_to_tls.offset = 0;
1026 clear_to_tls.len = 0;
1031 if (clear_to_tls.offset + clear_to_tls.len < sizeof clear_to_tls.buf) {
1032 r = read_attempt(clear_fd, &clear_to_tls, &clear_read_select, &closed, &progress);
1036 r = SSL_shutdown(ssl);
1037 DEBUG_MSG2("SSL_shutdown", r);
1042 if (!closed && !in_handshake) {
1043 if (tls_to_clear.offset + tls_to_clear.len < sizeof tls_to_clear.buf) {
1044 r = tls_read_attempt(ssl, &tls_to_clear, &tls_write_select, &tls_read_select, &closed, &progress, &err_pref_1);
1048 r = SSL_shutdown(ssl);
1049 DEBUG_MSG2("SSL_shutdown", r);
1055 DEBUG_MSG("!progress?");
1056 if (num_read != BIO_number_read(rbio) || num_written != BIO_number_written(wbio))
1060 DEBUG_MSG("!progress");
1061 assert(clear_read_select || tls_read_select || clear_write_select || tls_write_select);
1062 tls_sockets_select(clear_read_select ? clear_fd : -1, tls_read_select ? tls_fd : -1, clear_write_select ? clear_fd : -1, tls_write_select ? tls_fd : -1, -1);
1069 tls_openssl_errors(err_pref_1, err_pref_2, err_def, tls_child_apparg);
1076 tls_get_error(SSL *ssl, int r, int *write_select, int *read_select, int *closed, int *progress)
1078 int err = SSL_get_error(ssl, r);
1080 if (err == SSL_ERROR_NONE) {
1089 case SSL_ERROR_ZERO_RETURN:
1095 case SSL_ERROR_WANT_WRITE:
1099 case SSL_ERROR_WANT_READ:
1108 tls_connect_attempt(SSL *ssl, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1112 DEBUG_MSG("tls_connect_attempt");
1113 n = SSL_connect(ssl);
1114 DEBUG_MSG2("SSL_connect",n);
1115 r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1117 *err_pref = " during SSL_connect";
1122 tls_accept_attempt(SSL *ssl, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1126 DEBUG_MSG("tls_accept_attempt");
1127 n = SSL_accept(ssl);
1128 DEBUG_MSG2("SSL_accept",n);
1129 r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1131 *err_pref = " during SSL_accept";
1136 tls_write_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1140 DEBUG_MSG("tls_write_attempt");
1141 n = SSL_write(ssl, buf->buf + buf->offset, buf->len);
1142 DEBUG_MSG2("SSL_write",n);
1143 r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1146 assert(buf->len >= 0);
1153 *err_pref = " during SSL_write";
1158 tls_read_attempt(SSL *ssl, struct tunnelbuf *buf, int *write_select, int *read_select, int *closed, int *progress, const char **err_pref)
1163 DEBUG_MSG("tls_read_attempt");
1164 total = buf->offset + buf->len;
1165 assert(total < sizeof buf->buf);
1166 n = SSL_read(ssl, buf->buf + total, (sizeof buf->buf) - total);
1167 DEBUG_MSG2("SSL_read",n);
1168 r = tls_get_error(ssl, n, write_select, read_select, closed, progress);
1171 assert(buf->offset + buf->len <= sizeof buf->buf);
1174 *err_pref = " during SSL_read";
1179 get_error(int r, int *select, int *closed, int *progress)
1188 if (errno == EAGAIN || errno == EWOULDBLOCK) {
1191 } else if (errno == EPIPE) {
1200 static int write_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed, int *progress)
1204 DEBUG_MSG("write_attempt");
1205 n = write(fd, buf->buf + buf->offset, buf->len);
1206 DEBUG_MSG2("write",n);
1207 r = get_error(n, select, closed, progress);
1210 assert(buf->len >= 0);
1217 tls_errprintf(1, tls_child_apparg, "write error: %s\n", strerror(errno));
1222 read_attempt(int fd, struct tunnelbuf *buf, int *select, int *closed, int *progress)
1227 DEBUG_MSG("read_attempt");
1228 total = buf->offset + buf->len;
1229 assert(total < sizeof buf->buf);
1230 n = read(fd, buf->buf + total, (sizeof buf->buf) - total);
1231 DEBUG_MSG2("read",n);
1232 r = get_error(n, select, closed, progress);
1235 assert(buf->offset + buf->len <= sizeof buf->buf);
1238 tls_errprintf(1, tls_child_apparg, "read error: %s\n", strerror(errno));