2 * socket.c -- socket library functions
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
12 #include <ctype.h> /* isspace() */
15 #endif /* HAVE_MEMORY_H */
16 #include <sys/types.h>
18 #ifndef HAVE_NET_SOCKET_H
19 #include <sys/socket.h>
21 #include <net/socket.h>
24 #include <netinet/in.h>
25 #ifdef HAVE_ARPA_INET_H
26 #include <arpa/inet.h>
29 #if defined(STDC_HEADERS)
32 #if defined(HAVE_UNISTD_H)
35 #if defined(HAVE_STDARG_H)
40 #if TIME_WITH_SYS_TIME
41 # include <sys/time.h>
45 # include <sys/time.h>
52 #include "fetchmail.h"
53 #include "getaddrinfo.h"
57 /* Defines to allow BeOS and Cygwin to play nice... */
60 #define fm_close(a) closesocket(a)
61 #define fm_write(a,b,c) send(a,b,c,0)
62 #define fm_peek(a,b,c) recv(a,b,c,0)
63 #define fm_read(a,b,c) recv(a,b,c,0)
65 #define fm_close(a) close(a)
66 #define fm_write(a,b,c) write(a,b,c)
67 #define fm_peek(a,b,c) recv(a,b,c, MSG_PEEK)
69 #define fm_read(a,b,c) cygwin_read(a,b,c)
70 static ssize_t cygwin_read(int sock, void *buf, size_t count);
71 #else /* ! __CYGWIN__ */
72 #define fm_read(a,b,c) read(a,b,c)
73 #endif /* __CYGWIN__ */
76 /* We need to define h_errno only if it is not already */
79 #ifdef HAVE_RES_SEARCH
80 /* some versions of FreeBSD should declare this but don't */
83 /* pretend we have h_errno to avoid some #ifdef's later */
87 #endif /* ndef h_errno */
89 #ifdef HAVE_SOCKETPAIR
90 static char *const *parse_plugin(const char *plugin, const char *host, const char *service)
91 { const char **argvec;
93 char *cp, *plugin_copy;
94 unsigned int plugin_copy_len;
95 unsigned int plugin_offset = 0, plugin_copy_offset = 0;
96 unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
97 unsigned int plugin_len = strlen(plugin);
98 unsigned int host_len = strlen(host);
99 unsigned int service_len = strlen(service);
101 for (c = p = plugin; *c; c++)
102 { if (isspace((unsigned char)*c) && !isspace((unsigned char)*p))
104 if (*p == '%' && *c == 'h')
106 if (*p == '%' && *c == 'p')
111 plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
112 plugin_copy = (char *)malloc(plugin_copy_len + 1);
115 report(stderr, GT_("fetchmail: malloc failed\n"));
119 while (plugin_copy_offset < plugin_copy_len)
120 { if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
121 { strcpy(plugin_copy + plugin_copy_offset, host);
123 plugin_copy_offset += host_len;
125 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
126 { strcpy(plugin_copy + plugin_copy_offset, service);
128 plugin_copy_offset += service_len;
131 { plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
133 plugin_copy_offset++;
136 plugin_copy[plugin_copy_len] = 0;
138 argvec = (const char **)malloc(s);
141 report(stderr, GT_("fetchmail: malloc failed\n"));
144 memset(argvec, 0, s);
145 for (c = p = plugin_copy, i = 0; *c; c++)
146 { if ((!isspace((unsigned char)*c)) && (c == p ? 1 : isspace((unsigned char)*p))) {
152 for (cp = plugin_copy; *cp; cp++)
153 { if (isspace((unsigned char)*cp))
156 return (char *const*)argvec;
159 static int handle_plugin(const char *host,
160 const char *service, const char *plugin)
161 /* get a socket mediated through a given external command */
167 * The author of this code, Felix von Leitner <felix@convergence.de>, says:
168 * he chose socketpair() instead of pipe() because socketpair creates
169 * bidirectional sockets while allegedly some pipe() implementations don't.
171 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
173 report(stderr, GT_("fetchmail: socketpair failed\n"));
179 report(stderr, GT_("fetchmail: fork failed\n"));
182 /* fds[1] is the parent's end; close it for proper EOF
184 (void) close(fds[1]);
185 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
186 report(stderr, GT_("dup2 failed\n"));
189 /* fds[0] is now connected to 0 and 1; close it */
190 (void) close(fds[0]);
191 if (outlevel >= O_VERBOSE)
192 report(stderr, GT_("running %s (host %s service %s)\n"), plugin, host, service);
193 argvec = parse_plugin(plugin,host,service);
194 execvp(*argvec, argvec);
195 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
198 default: /* parent */
202 /* fds[0] is the child's end; close it for proper EOF detection */
203 (void) close(fds[0]);
206 #endif /* HAVE_SOCKETPAIR */
210 int SockCheckOpen(int fd)
211 /* poll given socket; is it selectable? */
219 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
222 tv.tv_sec = 0; tv.tv_usec = 0;
223 rt = select(fd+1, &r, &w, &e, &tv);
224 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
230 #endif /* __UNUSED__ */
232 int UnixOpen(const char *path)
235 struct sockaddr_un ad;
236 memset(&ad, 0, sizeof(ad));
237 ad.sun_family = AF_UNIX;
238 strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
240 sock = socket( AF_UNIX, SOCK_STREAM, 0 );
247 /* Socket opened saved. Usefull if connect timeout
248 * because it can be closed.
250 mailserver_socket_temp = sock;
252 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
255 fm_close(sock); /* don't use SockClose, no traffic yet */
261 /* No connect timeout, then no need to set mailserver_socket_temp */
262 mailserver_socket_temp = -1;
267 int SockOpen(const char *host, const char *service,
268 const char *plugin, struct addrinfo **ai0)
270 struct addrinfo *ai, req;
273 #ifdef HAVE_SOCKETPAIR
275 return handle_plugin(host,service,plugin);
276 #endif /* HAVE_SOCKETPAIR */
278 memset(&req, 0, sizeof(struct addrinfo));
279 req.ai_socktype = SOCK_STREAM;
281 req.ai_flags = AI_ADDRCONFIG;
284 i = fm_getaddrinfo(host, service, &req, ai0);
286 report(stderr, GT_("getaddrinfo(\"%s\",\"%s\") error: %s\n"),
287 host, service, gai_strerror(i));
288 if (i == EAI_SERVICE)
289 report(stderr, GT_("Try adding the --service option (see also FAQ item R12).\n"));
294 for (ai = *ai0; ai; ai = ai->ai_next) {
298 gnie = getnameinfo(ai->ai_addr, ai->ai_addrlen, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
300 snprintf(buf, sizeof(buf), GT_("unknown (%s)"), gai_strerror(gnie));
301 gnie = getnameinfo(ai->ai_addr, ai->ai_addrlen, NULL, 0, pb, sizeof(pb), NI_NUMERICSERV);
303 snprintf(pb, sizeof(pb), GT_("unknown (%s)"), gai_strerror(gnie));
305 if (outlevel >= O_VERBOSE)
306 report_build(stdout, GT_("Trying to connect to %s/%s..."), buf, pb);
307 i = socket(ai->ai_family, ai->ai_socktype, 0);
309 /* mask EAFNOSUPPORT errors, they confuse users for
310 * multihomed hosts */
311 if (errno != EAFNOSUPPORT)
313 if (outlevel >= O_VERBOSE)
314 report_complete(stdout, GT_("cannot create socket: %s\n"), strerror(errno));
318 /* Save socket descriptor.
319 * Used to close the socket after connect timeout. */
320 mailserver_socket_temp = i;
322 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
325 /* additionally, suppress IPv4 network unreach errors */
326 if (e != EAFNOSUPPORT)
329 if (outlevel >= O_VERBOSE)
330 report_complete(stdout, GT_("connection failed.\n"));
331 if (outlevel > O_SILENT)
332 report(stderr, GT_("connection to %s:%s [%s/%s] failed: %s.\n"), host, service, buf, pb, strerror(e));
337 if (outlevel >= O_VERBOSE)
338 report_complete(stdout, GT_("connected.\n"));
341 /* No connect timeout, then no need to set mailserver_socket_temp */
342 mailserver_socket_temp = -1;
347 fm_freeaddrinfo(*ai0);
357 #if defined(HAVE_STDARG_H)
358 int SockPrintf(int sock, const char* format, ...)
361 int SockPrintf(sock,format,va_alist)
370 #if defined(HAVE_STDARG_H)
371 va_start(ap, format) ;
375 vsnprintf(buf, sizeof(buf), format, ap);
377 return SockWrite(sock, buf, strlen(buf));
382 #include <openssl/ssl.h>
383 #include <openssl/err.h>
384 #include <openssl/pem.h>
385 #include <openssl/x509v3.h>
386 #include <openssl/rand.h>
388 static SSL_CTX *_ctx[FD_SETSIZE];
389 static SSL *_ssl_context[FD_SETSIZE];
391 static SSL *SSLGetContext( int );
392 #endif /* SSL_ENABLE */
394 int SockWrite(int sock, char *buf, int len)
404 if( NULL != ( ssl = SSLGetContext( sock ) ) )
405 n = SSL_write(ssl, buf, len);
407 #endif /* SSL_ENABLE */
408 n = fm_write(sock, buf, len);
418 int SockRead(int sock, char *buf, int len)
420 char *newline, *bp = buf;
438 * The reason for these gymnastics is that we want two things:
439 * (1) to read \n-terminated lines,
440 * (2) to return the true length of data read, even if the
441 * data coming in has embedded NULS.
444 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
446 /* OK... SSL_peek works a little different from MSG_PEEK
447 Problem is that SSL_peek can return 0 if there
448 is no data currently available. If, on the other
449 hand, we loose the socket, we also get a zero, but
450 the SSL_read then SEGFAULTS! To deal with this,
451 we'll check the error code any time we get a return
452 of zero from SSL_peek. If we have an error, we bail.
453 If we don't, we read one character in SSL_read and
454 loop. This should continue to work even if they
455 later change the behavior of SSL_peek
456 to "fix" this problem... :-( */
457 if ((n = SSL_peek(ssl, bp, len)) < 0) {
458 (void)SSL_get_error(ssl, n);
462 /* SSL_peek says no data... Does he mean no data
463 or did the connection blow up? If we got an error
465 if (0 != SSL_get_error(ssl, n)) {
468 /* We didn't get an error so read at least one
469 character at this point and loop */
471 /* Make sure newline start out NULL!
472 * We don't have a string to pass through
473 * the strchr at this point yet */
475 } else if ((newline = (char *)memchr(bp, '\n', n)) != NULL)
476 n = newline - bp + 1;
477 /* Matthias Andree: SSL_read can return 0, in that case
478 * we must call SSL_get_error to figure if there was
479 * an error or just a "no data" condition */
480 if ((n = SSL_read(ssl, bp, n)) <= 0) {
481 if ((n = SSL_get_error(ssl, n))) {
485 /* Check for case where our single character turned out to
486 * be a newline... (It wasn't going to get caught by
487 * the strchr above if it came from the hack... ). */
488 if( NULL == newline && 1 == n && '\n' == *bp ) {
489 /* Got our newline - this will break
490 out of the loop now */
495 #endif /* SSL_ENABLE */
499 if ((n = fm_read(sock, bp, 1)) <= 0)
501 if ((n = fm_peek(sock, bp, len)) <= 0)
504 if ((newline = (char *)memchr(bp, '\n', n)) != NULL)
505 n = newline - bp + 1;
507 if ((n = fm_read(sock, bp, n)) == -1)
509 #endif /* __BEOS__ */
520 int SockPeek(int sock)
521 /* peek at the next socket character without actually reading it */
530 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
531 n = SSL_peek(ssl, &ch, 1);
533 (void)SSL_get_error(ssl, n);
537 /* This code really needs to implement a "hold back"
538 * to simulate a functioning SSL_peek()... sigh...
539 * Has to be coordinated with the read code above.
540 * Next on the list todo... */
542 /* SSL_peek says 0... Does that mean no data
543 or did the connection blow up? If we got an error
545 if(0 != SSL_get_error(ssl, n)) {
549 /* Haven't seen this case actually occur, but...
550 if the problem in SockRead can occur, this should
551 be possible... Just not sure what to do here.
552 This should be a safe "punt" the "peek" but don't
553 "punt" the "session"... */
555 return 0; /* Give him a '\0' character */
559 #endif /* SSL_ENABLE */
560 n = fm_peek(sock, &ch, 1);
572 static char *_ssl_server_cname = NULL;
573 static int _check_fp;
574 static char *_check_digest;
575 static char *_server_label;
576 static int _depth0ck;
577 static int _prev_err;
579 SSL *SSLGetContext( int sock )
581 if( sock < 0 || (unsigned)sock > FD_SETSIZE )
583 if( _ctx[sock] == NULL )
585 return _ssl_context[sock];
589 /* ok_return (preverify_ok) is 1 if this stage of certificate verification
590 passed, or 0 if it failed. This callback lets us display informative
591 errors, and perform additional validation (e.g. CN matches) */
592 static int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
597 unsigned char digest[EVP_MAX_MD_SIZE];
598 char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
599 const EVP_MD *digest_tp;
600 unsigned int dsz, esz;
601 X509_NAME *subj, *issuer;
604 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
605 err = X509_STORE_CTX_get_error(ctx);
606 depth = X509_STORE_CTX_get_error_depth(ctx);
608 subj = X509_get_subject_name(x509_cert);
609 issuer = X509_get_issuer_name(x509_cert);
611 if (depth == 0 && !_depth0ck) {
614 if (outlevel >= O_VERBOSE) {
615 if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
616 report(stdout, GT_("Issuer Organization: %s\n"), (tt = sdump(buf, i)));
618 if ((size_t)i >= sizeof(buf) - 1)
619 report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
621 report(stdout, GT_("Unknown Organization\n"));
622 if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
623 report(stdout, GT_("Issuer CommonName: %s\n"), (tt = sdump(buf, i)));
625 if ((size_t)i >= sizeof(buf) - 1)
626 report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
628 report(stdout, GT_("Unknown Issuer CommonName\n"));
630 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
631 if (outlevel >= O_VERBOSE) {
632 report(stdout, GT_("Server CommonName: %s\n"), (tt = sdump(buf, i)));
635 if ((size_t)i >= sizeof(buf) - 1) {
636 /* Possible truncation. In this case, this is a DNS name, so this
637 * is really bad. We do not tolerate this even in the non-strict case. */
638 report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
641 if ((size_t)i > strlen(buf)) {
642 /* Name contains embedded NUL characters, so we complain. This is likely
643 * a certificate spoofing attack. */
644 report(stderr, GT_("Bad certificate: Subject CommonName contains NUL, aborting!\n"));
647 if (_ssl_server_cname != NULL) {
649 char *p2 = _ssl_server_cname;
652 STACK_OF(GENERAL_NAME) *gens;
654 /* RFC 2595 section 2.4: find a matching name
655 * first find a match among alternative names */
656 gens = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i(x509_cert, NID_subject_alt_name, NULL, NULL);
659 for (j = 0, r = sk_GENERAL_NAME_num(gens); j < r; ++j) {
660 const GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, j);
661 if (gn->type == GEN_DNS) {
662 char *p1 = (char *)gn->d.ia5->data;
663 char *p2 = _ssl_server_cname;
664 if (outlevel >= O_VERBOSE) {
665 report(stdout, GT_("Subject Alternative Name: %s\n"), (tt = sdump(p1, (size_t)gn->d.ia5->length)));
668 /* Name contains embedded NUL characters, so we complain. This
669 * is likely a certificate spoofing attack. */
670 if ((size_t)gn->d.ia5->length != strlen(p1)) {
671 report(stderr, GT_("Bad certificate: Subject Alternative Name contains NUL, aborting!\n"));
672 sk_GENERAL_NAME_free(gens);
677 n = strlen(p2) - strlen(p1);
681 if (0 == strcasecmp(p1, p2)) {
686 sk_GENERAL_NAME_free(gens);
690 n = strlen(p2) - strlen(p1);
694 if (0 == strcasecmp(p1, p2)) {
699 GT_("Server CommonName mismatch: %s != %s\n"),
700 (tt = sdump(buf, i)), _ssl_server_cname );
702 if (ok_return && strict)
705 } else if (ok_return) {
706 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
707 if (strict) return (0);
710 if (outlevel >= O_VERBOSE)
711 report(stdout, GT_("Unknown Server CommonName\n"));
712 if (ok_return && strict) {
713 report(stderr, GT_("Server name not specified in certificate!\n"));
717 /* Print the finger print. Note that on errors, we might print it more than once
718 * normally; we kluge around that by using a global variable. */
719 if (_check_fp == 1) {
723 digest_tp = EVP_md5();
724 if (digest_tp == NULL) {
725 report(stderr, GT_("EVP_md5() failed!\n"));
728 if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
729 report(stderr, GT_("Out of memory!\n"));
733 te = text + sizeof(text);
734 for (dp = 0; dp < dsz; dp++) {
735 esz = snprintf(tp, te - tp, dp > 0 ? ":%02X" : "%02X", digest[dp]);
736 if (esz >= (size_t)(te - tp)) {
737 report(stderr, GT_("Digest text buffer too small!\n"));
742 if (outlevel > O_NORMAL)
743 report(stdout, GT_("%s key fingerprint: %s\n"), _server_label, text);
744 if (_check_digest != NULL) {
745 if (strcasecmp(text, _check_digest) == 0) {
746 if (outlevel > O_NORMAL)
747 report(stdout, GT_("%s fingerprints match.\n"), _server_label);
749 report(stderr, GT_("%s fingerprints do not match!\n"), _server_label);
752 } /* if (_check_digest != NULL) */
753 } /* if (_check_fp) */
754 } /* if (depth == 0 && !_depth0ck) */
756 if (err != X509_V_OK && err != _prev_err && !(_check_fp != 0 && _check_digest && !strict)) {
758 report(stderr, GT_("Server certificate verification error: %s\n"), X509_verify_cert_error_string(err));
759 /* We gave the error code, but maybe we can add some more details for debugging */
761 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
762 X509_NAME_oneline(issuer, buf, sizeof(buf));
763 buf[sizeof(buf) - 1] = '\0';
764 report(stderr, GT_("unknown issuer (first %d characters): %s\n"), (int)(sizeof(buf)-1), buf);
769 * If not in strict checking mode (--sslcertck), override this
770 * and pretend that verification had succeeded.
777 static int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
779 return SSL_verify_callback(ok_return, ctx, 0);
782 static int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
784 return SSL_verify_callback(ok_return, ctx, 1);
788 /* get commonName from certificate set in file.
789 * commonName is stored in buffer namebuffer, limited with namebufferlen
791 static const char *SSLCertGetCN(const char *mycert,
792 char *namebuffer, size_t namebufferlen)
794 const char *ret = NULL;
796 X509 *x509_cert = NULL;
797 X509_NAME *certname = NULL;
799 if (namebuffer && namebufferlen > 0) {
800 namebuffer[0] = 0x00;
801 certBio = BIO_new_file(mycert,"r");
803 x509_cert = PEM_read_bio_X509(certBio,NULL,NULL,NULL);
807 certname = X509_get_subject_name(x509_cert);
809 X509_NAME_get_text_by_NID(certname, NID_commonName,
810 namebuffer, namebufferlen) > 0)
812 X509_free(x509_cert);
818 /* performs initial SSL handshake over the connected socket
819 * uses SSL *ssl global variable, which is currently defined
822 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, int certck, char *certpath,
823 char *fingerprint, char *servercname, char *label, char **remotename)
825 struct stat randstat;
828 SSL_load_error_strings();
829 SSLeay_add_ssl_algorithms(); /* synonym for SSL_library_init() */
832 if (stat("/dev/random", &randstat) &&
833 stat("/dev/urandom", &randstat)) {
834 /* Neither /dev/random nor /dev/urandom are present, so add
835 entropy to the SSL PRNG a hard way. */
836 for (i = 0; i < 10000 && ! RAND_status (); ++i) {
839 gettimeofday (&tv, 0);
840 buf[0] = tv.tv_usec & 0xF;
841 buf[2] = (tv.tv_usec & 0xF0) >> 4;
842 buf[3] = (tv.tv_usec & 0xF00) >> 8;
843 buf[1] = (tv.tv_usec & 0xF000) >> 12;
844 RAND_add (buf, sizeof buf, 0.1);
847 #endif /* SSL_ENABLE */
850 if( sock < 0 || (unsigned)sock > FD_SETSIZE ) {
851 report(stderr, GT_("File descriptor out of range for SSL") );
855 /* Make sure a connection referring to an older context is not left */
856 _ssl_context[sock] = NULL;
858 if(!strcasecmp("ssl2",myproto)) {
859 _ctx[sock] = SSL_CTX_new(SSLv2_client_method());
860 } else if(!strcasecmp("ssl3",myproto)) {
861 _ctx[sock] = SSL_CTX_new(SSLv3_client_method());
862 } else if(!strcasecmp("tls1",myproto)) {
863 _ctx[sock] = SSL_CTX_new(TLSv1_client_method());
864 } else if (!strcasecmp("ssl23",myproto)) {
867 fprintf(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
872 _ctx[sock] = SSL_CTX_new(SSLv23_client_method());
874 if(_ctx[sock] == NULL) {
875 ERR_print_errors_fp(stderr);
879 SSL_CTX_set_options(_ctx[sock], SSL_OP_ALL);
882 SSL_CTX_set_verify(_ctx[sock], SSL_VERIFY_PEER, SSL_ck_verify_callback);
884 /* In this case, we do not fail if verification fails. However,
885 * we provide the callback for output and possible fingerprint checks. */
886 SSL_CTX_set_verify(_ctx[sock], SSL_VERIFY_PEER, SSL_nock_verify_callback);
889 SSL_CTX_load_verify_locations(_ctx[sock], NULL, certpath);
891 SSL_CTX_set_default_verify_paths(_ctx[sock]);
893 _ssl_context[sock] = SSL_new(_ctx[sock]);
895 if(_ssl_context[sock] == NULL) {
896 ERR_print_errors_fp(stderr);
897 SSL_CTX_free(_ctx[sock]);
902 /* This static is for the verify callback */
903 _ssl_server_cname = servercname;
904 _server_label = label;
906 _check_digest = fingerprint;
910 if( mycert || mykey ) {
912 /* Ok... He has a certificate file defined, so lets declare it. If
913 * he does NOT have a separate certificate and private key file then
914 * assume that it's a combined key and certificate file.
923 if ((!*remotename || !**remotename) && SSLCertGetCN(mycert, buffer, sizeof(buffer))) {
925 *remotename = xstrdup(buffer);
927 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
928 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
931 if (SSL_set_fd(_ssl_context[sock], sock) == 0
932 || SSL_connect(_ssl_context[sock]) < 1) {
933 ERR_print_errors_fp(stderr);
934 SSL_free( _ssl_context[sock] );
935 _ssl_context[sock] = NULL;
936 SSL_CTX_free(_ctx[sock]);
941 /* Paranoia: was the callback not called as we expected? */
943 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
945 if (fingerprint != NULL || certck) {
946 if( NULL != SSLGetContext( sock ) ) {
947 /* Clean up the SSL stack */
948 SSL_shutdown( _ssl_context[sock] );
949 SSL_free( _ssl_context[sock] );
950 _ssl_context[sock] = NULL;
951 SSL_CTX_free(_ctx[sock]);
962 int SockClose(int sock)
963 /* close a socket gracefully */
966 if( NULL != SSLGetContext( sock ) ) {
967 /* Clean up the SSL stack */
968 SSL_shutdown( _ssl_context[sock] );
969 SSL_free( _ssl_context[sock] );
970 _ssl_context[sock] = NULL;
971 SSL_CTX_free(_ctx[sock]);
978 * This hangs in RedHat 6.2 after fetchmail runs for a while a
979 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
980 * the recv system call. (Reported from jtnews
981 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
983 * Half-close the connection first so the other end gets notified.
985 * This stops sends but allows receives (effectively, it sends a
987 if (shutdown(sock, 1) == 0) {
989 /* If there is any data still waiting in the queue, discard it.
990 * Call recv() until either it returns 0 (meaning we received a FIN)
991 * or any error occurs. This makes sure all data sent by the other
992 * side is acknowledged at the TCP level.
994 if (fm_peek(sock, &ch, 1) > 0)
995 while (fm_read(sock, &ch, 1) > 0)
998 #endif /* __UNUSED__ */
1000 /* if there's an error closing at this point, not much we can do */
1001 return(fm_close(sock)); /* this is guarded */
1006 * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1007 * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1010 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1015 if ((n = read(sock, bp, count)) == -1)
1020 if (outlevel >= O_VERBOSE)
1021 report(stdout, GT_("Cygwin socket read retry\n"));
1022 n2 = read(sock, bp + n, count - n);
1023 if (n2 == -1 || n + n2 != count) {
1024 report(stderr, GT_("Cygwin socket read retry failed!\n"));
1031 #endif /* __CYGWIN__ */
1035 * Use the chargen service to test input buffering directly.
1036 * You may have to uncomment the `chargen' service description in your
1037 * inetd.conf (and then SIGHUP inetd) for this to work. */
1040 int sock = SockOpen("localhost", "chargen", NULL);
1043 while (SockRead(sock, buf, sizeof(buf)-1))
1044 SockWrite(1, buf, strlen(buf));
1049 /* socket.c ends here */