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)
41 #include "fetchmail.h"
44 /* Defines to allow BeOS and Cygwin to play nice... */
47 #define fm_close(a) closesocket(a)
48 #define fm_write(a,b,c) send(a,b,c,0)
49 #define fm_peek(a,b,c) recv(a,b,c,0)
50 #define fm_read(a,b,c) recv(a,b,c,0)
52 #define fm_close(a) close(a)
53 #define fm_write(a,b,c) write(a,b,c)
54 #define fm_peek(a,b,c) recv(a,b,c, MSG_PEEK)
56 #define fm_read(a,b,c) cygwin_read(a,b,c)
57 static ssize_t cygwin_read(int sock, void *buf, size_t count);
58 #else /* ! __CYGWIN__ */
59 #define fm_read(a,b,c) read(a,b,c)
60 #endif /* __CYGWIN__ */
63 /* We need to define h_errno only if it is not already */
66 #ifdef HAVE_RES_SEARCH
67 /* some versions of FreeBSD should declare this but don't */
70 /* pretend we have h_errno to avoid some #ifdef's later */
74 #endif /* ndef h_errno */
77 #include <net/security.h>
78 #endif /* NET_SECURITY */
80 #ifdef HAVE_SOCKETPAIR
81 static char *const *parse_plugin(const char *plugin, const char *host, const char *service)
82 { const char **argvec;
84 char *cp, *plugin_copy;
85 unsigned int plugin_copy_len;
86 unsigned int plugin_offset = 0, plugin_copy_offset = 0;
87 unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
88 unsigned int plugin_len = strlen(plugin);
89 unsigned int host_len = strlen(host);
90 unsigned int service_len = strlen(service);
92 for (c = p = plugin; *c; c++)
93 { if (isspace((unsigned char)*c) && !isspace((unsigned char)*p))
95 if (*p == '%' && *c == 'h')
97 if (*p == '%' && *c == 'p')
102 plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
103 plugin_copy = malloc(plugin_copy_len + 1);
106 report(stderr, GT_("fetchmail: malloc failed\n"));
110 while (plugin_copy_offset < plugin_copy_len)
111 { if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
112 { strcpy(plugin_copy + plugin_copy_offset, host);
114 plugin_copy_offset += host_len;
116 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
117 { strcpy(plugin_copy + plugin_copy_offset, service);
119 plugin_copy_offset += service_len;
122 { plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
124 plugin_copy_offset++;
127 plugin_copy[plugin_copy_len] = 0;
132 report(stderr, GT_("fetchmail: malloc failed\n"));
135 memset(argvec, 0, s);
136 for (c = p = plugin_copy, i = 0; *c; c++)
137 { if ((!isspace((unsigned char)*c)) && (c == p ? 1 : isspace((unsigned char)*p))) {
143 for (cp = plugin_copy; *cp; cp++)
144 { if (isspace((unsigned char)*cp))
147 return (char *const*)argvec;
150 static int handle_plugin(const char *host,
151 const char *service, const char *plugin)
152 /* get a socket mediated through a given external command */
158 * The author of this code, Felix von Leitner <felix@convergence.de>, says:
159 * he chose socketpair() instead of pipe() because socketpair creates
160 * bidirectional sockets while allegedly some pipe() implementations don't.
162 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
164 report(stderr, GT_("fetchmail: socketpair failed\n"));
170 report(stderr, GT_("fetchmail: fork failed\n"));
173 /* fds[1] is the parent's end; close it for proper EOF
175 (void) close(fds[1]);
176 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
177 report(stderr, GT_("dup2 failed\n"));
180 /* fds[0] is now connected to 0 and 1; close it */
181 (void) close(fds[0]);
182 if (outlevel >= O_VERBOSE)
183 report(stderr, GT_("running %s (host %s service %s)\n"), plugin, host, service);
184 argvec = parse_plugin(plugin,host,service);
185 execvp(*argvec, argvec);
186 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
189 default: /* parent */
193 /* fds[0] is the child's end; close it for proper EOF detection */
194 (void) close(fds[0]);
197 #endif /* HAVE_SOCKETPAIR */
201 int SockCheckOpen(int fd)
202 /* poll given socket; is it selectable? */
210 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
213 tv.tv_sec = 0; tv.tv_usec = 0;
214 rt = select(fd+1, &r, &w, &e, &tv);
215 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
221 #endif /* __UNUSED__ */
223 int UnixOpen(const char *path)
226 struct sockaddr_un ad;
227 memset(&ad, 0, sizeof(ad));
228 ad.sun_family = AF_UNIX;
229 strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
231 sock = socket( AF_UNIX, SOCK_STREAM, 0 );
238 /* Socket opened saved. Usefull if connect timeout
239 * because it can be closed.
241 mailserver_socket_temp = sock;
243 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
246 fm_close(sock); /* don't use SockClose, no traffic yet */
252 /* No connect timeout, then no need to set mailserver_socket_temp */
253 mailserver_socket_temp = -1;
259 int SockOpen(const char *host, const char *service, const char *options,
262 struct addrinfo *ai, *ai0, req;
265 void *request = NULL;
267 #endif /* NET_SECURITY */
269 #ifdef HAVE_SOCKETPAIR
271 return handle_plugin(host,service,plugin);
272 #endif /* HAVE_SOCKETPAIR */
273 memset(&req, 0, sizeof(struct addrinfo));
274 req.ai_socktype = SOCK_STREAM;
276 if (getaddrinfo(host, service, &req, &ai0)) {
277 report(stderr, GT_("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
285 if (net_security_strtorequest((char *)options, &request, &requestlen))
288 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
293 #else /* NET_SECURITY */
294 #ifdef HAVE_INNER_CONNECT
295 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
301 for (ai = ai0; ai; ai = ai->ai_next) {
302 i = socket(ai->ai_family, ai->ai_socktype, 0);
306 /* Socket opened saved. Usefull if connect timeout
307 * because it can be closed.
309 mailserver_socket_temp = i;
311 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
317 /* No connect timeout, then no need to set mailserver_socket_temp */
318 mailserver_socket_temp = -1;
324 #endif /* NET_SECURITY */
330 #else /* INET6_ENABLE */
331 #ifndef HAVE_INET_ATON
333 #ifdef INADDR_BROADCAST
334 #define INADDR_NONE INADDR_BROADCAST
336 #define INADDR_NONE -1
339 #endif /* HAVE_INET_ATON */
341 int SockOpen(const char *host, int clientPort, const char *options,
344 int sock = -1; /* pacify -Wall */
345 #ifndef HAVE_INET_ATON
346 unsigned long inaddr;
347 #endif /* HAVE_INET_ATON */
348 struct sockaddr_in ad, **pptr;
351 #ifdef HAVE_SOCKETPAIR
354 snprintf(buf, sizeof(buf), "%d", clientPort);
355 return handle_plugin(host,buf,plugin);
357 #endif /* HAVE_SOCKETPAIR */
359 memset(&ad, 0, sizeof(ad));
360 ad.sin_family = AF_INET;
362 /* we'll accept a quad address */
363 #ifndef HAVE_INET_ATON
364 inaddr = inet_addr((char*)host);
365 if (inaddr != INADDR_NONE)
367 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
369 if (inet_aton(host, &ad.sin_addr))
371 #endif /* HAVE_INET_ATON */
372 ad.sin_port = htons(clientPort);
374 sock = socket(AF_INET, SOCK_STREAM, 0);
381 /* Socket opened saved. Usefull if connect timeout because
384 mailserver_socket_temp = sock;
386 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
389 fm_close(sock); /* don't use SockClose, no traffic yet */
395 /* No connect timeout, then no need to set mailserver_socket_temp */
396 mailserver_socket_temp = -1;
398 #ifndef HAVE_INET_ATON
402 #endif /* HAVE_INET_ATON */
404 hp = gethostbyname((char*)host);
412 * Add a check to make sure the address has a valid IPv4 or IPv6
413 * length. This prevents buffer spamming by a broken DNS.
415 if(hp->h_length != 4 && hp->h_length != 8)
419 GT_("fetchmail: illegal address length received for host %s\n"),host);
423 * Try all addresses of a possibly multihomed host until we get
424 * a successful connect or until we run out of addresses.
426 pptr = (struct sockaddr_in **)hp->h_addr_list;
427 for(; *pptr != NULL; pptr++)
429 sock = socket(AF_INET, SOCK_STREAM, 0);
436 /* Socket opened saved. Usefull if connect timeout because
439 mailserver_socket_temp = sock;
441 ad.sin_port = htons(clientPort);
442 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
443 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0) {
444 /* No connect timeout, then no need to set mailserver_socket_temp */
445 mailserver_socket_temp = -1;
448 fm_close(sock); /* don't use SockClose, no traffic yet */
449 memset(&ad, 0, sizeof(ad));
450 ad.sin_family = AF_INET;
455 fm_close(sock); /* don't use SockClose, no traffic yet */
464 #endif /* INET6_ENABLE */
467 #if defined(HAVE_STDARG_H)
468 int SockPrintf(int sock, const char* format, ...)
471 int SockPrintf(sock,format,va_alist)
480 #if defined(HAVE_STDARG_H)
481 va_start(ap, format) ;
485 vsnprintf(buf, sizeof(buf), format, ap);
487 return SockWrite(sock, buf, strlen(buf));
492 #include <openssl/ssl.h>
493 #include <openssl/err.h>
494 #include <openssl/pem.h>
495 #include <openssl/x509.h>
496 #include <openssl/rand.h>
498 static SSL_CTX *_ctx = NULL;
499 static SSL *_ssl_context[FD_SETSIZE];
501 static SSL *SSLGetContext( int );
502 #endif /* SSL_ENABLE */
504 int SockWrite(int sock, char *buf, int len)
514 if( NULL != ( ssl = SSLGetContext( sock ) ) )
515 n = SSL_write(ssl, buf, len);
517 #endif /* SSL_ENABLE */
518 n = fm_write(sock, buf, len);
528 int SockRead(int sock, char *buf, int len)
530 char *newline, *bp = buf;
532 #ifdef FORCE_STUFFING
533 int maxavailable = 0;
551 * The reason for these gymnastics is that we want two things:
552 * (1) to read \n-terminated lines,
553 * (2) to return the true length of data read, even if the
554 * data coming in has embedded NULS.
557 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
559 /* OK... SSL_peek works a little different from MSG_PEEK
560 Problem is that SSL_peek can return 0 if there
561 is no data currently available. If, on the other
562 hand, we loose the socket, we also get a zero, but
563 the SSL_read then SEGFAULTS! To deal with this,
564 we'll check the error code any time we get a return
565 of zero from SSL_peek. If we have an error, we bail.
566 If we don't, we read one character in SSL_read and
567 loop. This should continue to work even if they
568 later change the behavior of SSL_peek
569 to "fix" this problem... :-( */
570 if ((n = SSL_peek(ssl, bp, len)) < 0) {
571 (void)SSL_get_error(ssl, n);
574 #ifdef FORCE_STUFFING
578 /* SSL_peek says no data... Does he mean no data
579 or did the connection blow up? If we got an error
581 if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
584 /* We didn't get an error so read at least one
585 character at this point and loop */
587 /* Make sure newline start out NULL!
588 * We don't have a string to pass through
589 * the strchr at this point yet */
591 } else if ((newline = memchr(bp, '\n', n)) != NULL)
592 n = newline - bp + 1;
593 /* Matthias Andree: SSL_read can return 0, in that case
594 * we must cal SSL_get_error to figure if there was
595 * an error or just a "no data" condition */
596 if ((n = SSL_read(ssl, bp, n)) <= 0) {
597 if ((n = SSL_get_error(ssl, n))) {
601 /* Check for case where our single character turned out to
602 * be a newline... (It wasn't going to get caught by
603 * the strchr above if it came from the hack... ). */
604 if( NULL == newline && 1 == n && '\n' == *bp ) {
605 /* Got our newline - this will break
606 out of the loop now */
611 #endif /* SSL_ENABLE */
615 if ((n = fm_read(sock, bp, 1)) <= 0)
617 if ((n = fm_peek(sock, bp, len)) <= 0)
620 #ifdef FORCE_STUFFING
623 if ((newline = memchr(bp, '\n', n)) != NULL)
624 n = newline - bp + 1;
626 if ((n = fm_read(sock, bp, n)) == -1)
628 #endif /* __BEOS__ */
636 #ifdef FORCE_STUFFING /* too ugly to live -- besides, there's IMAP */
637 /* OK, very weird hack coming up here:
638 * When POP3 servers send us a message, they're supposed to
639 * terminate the message with a line containing only a dot. To protect
640 * against lines in the real message that might contain only a dot,
641 * they're supposed to preface any line that starts with a dot with
642 * an additional dot, which will be removed on the client side. That
643 * process, called byte-stuffing (and unstuffing) is really not the
644 * concern of this low-level routine, ordinarily, but there are some
645 * POP servers (and maybe IMAP servers too, who knows) that fail to
646 * do the byte-stuffing, and this routine is the best place to try to
647 * identify and fix that fault.
649 * Since the DOT line is supposed to come only at the end of a
650 * message, the implication is that right after we see it, the server
651 * is supposed to go back to waiting for the next command. There
652 * isn't supposed to be any more data to read after we see the dot.
653 * THEREFORE, if we see more data to be read after something that
654 * looks like the dot line, then probably the server is failing to
655 * do byte-stuffing. In that case, we'll byte-pack it for them so
656 * that the higher-level routines see things as hunky-dorey.
657 * This is not a perfect test or fix by any means (it has an
658 * obvious race condition, for one thing), but it should at least
659 * reduce the nastiness that ensues when people don't know how
660 * to write POP servers.
662 if ((maxavailable > (bp-buf)) &&
669 (buf[1] == '\n')))) {
671 memmove(buf+1, buf, (bp-buf)+1);
675 #endif /* FORCE_STUFFING */
679 int SockPeek(int sock)
680 /* peek at the next socket character without actually reading it */
689 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
690 n = SSL_peek(ssl, &ch, 1);
692 (void)SSL_get_error(ssl, n);
696 /* This code really needs to implement a "hold back"
697 * to simulate a functioning SSL_peek()... sigh...
698 * Has to be coordinated with the read code above.
699 * Next on the list todo... */
701 /* SSL_peek says 0... Does that mean no data
702 or did the connection blow up? If we got an error
704 if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
708 /* Haven't seen this case actually occur, but...
709 if the problem in SockRead can occur, this should
710 be possible... Just not sure what to do here.
711 This should be a safe "punt" the "peek" but don't
712 "punt" the "session"... */
714 return 0; /* Give him a '\0' character */
718 #endif /* SSL_ENABLE */
719 n = fm_peek(sock, &ch, 1);
731 static char *_ssl_server_cname = NULL;
732 static int _check_fp;
733 static char *_check_digest;
734 static char *_server_label;
735 static int _depth0ck;
736 static int _prev_err;
738 SSL *SSLGetContext( int sock )
740 /* If SSLOpen has never initialized - just return NULL */
744 if( sock < 0 || sock > FD_SETSIZE )
746 return _ssl_context[sock];
750 /* ok_return (preverify_ok) is 1 if this stage of certificate verification
751 passed, or 0 if it failed. This callback lets us display informative
752 errors, and perform additional validation (e.g. CN matches) */
753 static int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
758 unsigned char digest[EVP_MAX_MD_SIZE];
759 char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
760 const EVP_MD *digest_tp;
761 unsigned int dsz, i, esz;
762 X509_NAME *subj, *issuer;
764 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
765 err = X509_STORE_CTX_get_error(ctx);
766 depth = X509_STORE_CTX_get_error_depth(ctx);
768 subj = X509_get_subject_name(x509_cert);
769 issuer = X509_get_issuer_name(x509_cert);
771 if (depth == 0 && !_depth0ck) {
774 if (outlevel == O_VERBOSE) {
775 if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
776 report(stdout, GT_("Issuer Organization: %s\n"), buf);
777 if (i >= sizeof(buf) - 1)
778 report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
780 report(stdout, GT_("Unknown Organization\n"));
781 if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
782 report(stdout, GT_("Issuer CommonName: %s\n"), buf);
783 if (i >= sizeof(buf) - 1)
784 report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
786 report(stdout, GT_("Unknown Issuer CommonName\n"));
788 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
789 if (outlevel == O_VERBOSE)
790 report(stdout, GT_("Server CommonName: %s\n"), buf);
791 if (i >= sizeof(buf) - 1) {
792 /* Possible truncation. In this case, this is a DNS name, so this
793 * is really bad. We do not tolerate this even in the non-strict case. */
794 report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
797 if (_ssl_server_cname != NULL) {
799 char *p2 = _ssl_server_cname;
804 n = strlen(p2) - strlen(p1);
808 if (0 != strcasecmp(p1, p2)) {
810 GT_("Server CommonName mismatch: %s != %s\n"),
811 buf, _ssl_server_cname );
812 if (ok_return && strict)
815 } else if (ok_return) {
816 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
817 if (strict) return (0);
820 if (outlevel == O_VERBOSE)
821 report(stdout, GT_("Unknown Server CommonName\n"));
822 if (ok_return && strict) {
823 report(stderr, GT_("Server name not specified in certificate!\n"));
827 /* Print the finger print. Note that on errors, we might print it more than once
828 * normally; we kluge around that by using a global variable. */
831 digest_tp = EVP_md5();
832 if (digest_tp == NULL) {
833 report(stderr, GT_("EVP_md5() failed!\n"));
836 if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
837 report(stderr, GT_("Out of memory!\n"));
841 te = text + sizeof(text);
842 for (i = 0; i < dsz; i++) {
843 esz = snprintf(tp, te - tp, i > 0 ? ":%02X" : "%02X", digest[i]);
844 if (esz >= te - tp) {
845 report(stderr, GT_("Digest text buffer too small!\n"));
850 if (outlevel > O_NORMAL)
851 report(stdout, GT_("%s key fingerprint: %s\n"), _server_label, text);
852 if (_check_digest != NULL) {
853 if (strcmp(text, _check_digest) == 0) {
854 if (outlevel > O_NORMAL)
855 report(stdout, GT_("%s fingerprints match.\n"), _server_label);
857 if (outlevel > O_SILENT)
858 report(stderr, GT_("%s fingerprints do not match!\n"), _server_label);
865 if (err != X509_V_OK && err != _prev_err) {
867 report(stderr, GT_("Server certificate verification error: %s\n"), X509_verify_cert_error_string(err));
868 /* We gave the error code, but maybe we can add some more details for debugging */
870 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
871 X509_NAME_oneline(issuer, buf, sizeof(buf));
872 buf[sizeof(buf) - 1] = '\0';
873 report(stderr, GT_("unknown issuer (first %d characters): %s\n"), sizeof(buf)-1, buf);
882 static int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
884 return SSL_verify_callback(ok_return, ctx, 0);
887 static int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
889 return SSL_verify_callback(ok_return, ctx, 1);
892 /* performs initial SSL handshake over the connected socket
893 * uses SSL *ssl global variable, which is currently defined
896 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, int certck, char *certpath,
897 char *fingerprint, char *servercname, char *label)
899 struct stat randstat;
902 SSL_load_error_strings();
903 SSLeay_add_ssl_algorithms();
906 if (stat("/dev/random", &randstat) &&
907 stat("/dev/urandom", &randstat)) {
908 /* Neither /dev/random nor /dev/urandom are present, so add
909 entropy to the SSL PRNG a hard way. */
910 for (i = 0; i < 10000 && ! RAND_status (); ++i) {
913 gettimeofday (&tv, 0);
914 buf[0] = tv.tv_usec & 0xF;
915 buf[2] = (tv.tv_usec & 0xF0) >> 4;
916 buf[3] = (tv.tv_usec & 0xF00) >> 8;
917 buf[1] = (tv.tv_usec & 0xF000) >> 12;
918 RAND_add (buf, sizeof buf, 0.1);
921 #endif /* SSL_ENABLE */
924 if( sock < 0 || sock > FD_SETSIZE ) {
925 report(stderr, GT_("File descriptor out of range for SSL") );
930 /* Be picky and make sure the memory is cleared */
931 memset( _ssl_context, 0, sizeof( _ssl_context ) );
933 if(!strcmp("ssl2",myproto)) {
934 _ctx = SSL_CTX_new(SSLv2_client_method());
935 } else if(!strcmp("ssl3",myproto)) {
936 _ctx = SSL_CTX_new(SSLv3_client_method());
937 } else if(!strcmp("tls1",myproto)) {
938 _ctx = SSL_CTX_new(TLSv1_client_method());
939 } else if (!strcmp("ssl23",myproto)) {
942 fprintf(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
947 _ctx = SSL_CTX_new(SSLv23_client_method());
950 ERR_print_errors_fp(stderr);
956 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_ck_verify_callback);
958 /* In this case, we do not fail if verification fails. However,
959 * we provide the callback for output and possible fingerprint checks. */
960 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_nock_verify_callback);
963 SSL_CTX_load_verify_locations(_ctx, NULL, certpath);
965 _ssl_context[sock] = SSL_new(_ctx);
967 if(_ssl_context[sock] == NULL) {
968 ERR_print_errors_fp(stderr);
972 /* This static is for the verify callback */
973 _ssl_server_cname = servercname;
974 _server_label = label;
976 _check_digest = fingerprint;
980 if( mycert || mykey ) {
982 /* Ok... He has a certificate file defined, so lets declare it. If
983 * he does NOT have a separate certificate and private key file then
984 * assume that it's a combined key and certificate file.
990 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
991 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
994 SSL_set_fd(_ssl_context[sock], sock);
996 if(SSL_connect(_ssl_context[sock]) < 1) {
997 ERR_print_errors_fp(stderr);
1001 /* Paranoia: was the callback not called as we expected? */
1003 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
1005 if (fingerprint != NULL || certck) {
1006 if( NULL != SSLGetContext( sock ) ) {
1007 /* Clean up the SSL stack */
1008 SSL_free( _ssl_context[sock] );
1009 _ssl_context[sock] = NULL;
1019 int SockClose(int sock)
1020 /* close a socket gracefully */
1023 if( NULL != SSLGetContext( sock ) ) {
1024 /* Clean up the SSL stack */
1025 SSL_free( _ssl_context[sock] );
1026 _ssl_context[sock] = NULL;
1032 * This hangs in RedHat 6.2 after fetchmail runs for a while a
1033 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
1034 * the recv system call. (Reported from jtnews
1035 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
1037 * Half-close the connection first so the other end gets notified.
1039 * This stops sends but allows receives (effectively, it sends a
1041 if (shutdown(sock, 1) == 0) {
1043 /* If there is any data still waiting in the queue, discard it.
1044 * Call recv() until either it returns 0 (meaning we received a FIN)
1045 * or any error occurs. This makes sure all data sent by the other
1046 * side is acknowledged at the TCP level.
1048 if (fm_peek(sock, &ch, 1) > 0)
1049 while (fm_read(sock, &ch, 1) > 0)
1052 #endif /* __UNUSED__ */
1054 /* if there's an error closing at this point, not much we can do */
1055 return(fm_close(sock)); /* this is guarded */
1060 * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1061 * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1064 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1069 if ((n = read(sock, bp, count)) == -1)
1074 if (outlevel >= O_VERBOSE)
1075 report(stdout, GT_("Cygwin socket read retry\n"));
1076 n2 = read(sock, bp + n, count - n);
1077 if (n2 == -1 || n + n2 != count) {
1078 report(stderr, GT_("Cygwin socket read retry failed!\n"));
1085 #endif /* __CYGWIN__ */
1089 * Use the chargen service to test input buffering directly.
1090 * You may have to uncomment the `chargen' service description in your
1091 * inetd.conf (and then SIGHUP inetd) for this to work. */
1094 int sock = SockOpen("localhost", 19, NULL);
1097 while (SockRead(sock, buf, sizeof(buf)-1))
1098 SockWrite(1, buf, strlen(buf));
1103 /* socket.c ends here */