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"
55 /* Defines to allow BeOS and Cygwin to play nice... */
58 #define fm_close(a) closesocket(a)
59 #define fm_write(a,b,c) send(a,b,c,0)
60 #define fm_peek(a,b,c) recv(a,b,c,0)
61 #define fm_read(a,b,c) recv(a,b,c,0)
63 #define fm_close(a) close(a)
64 #define fm_write(a,b,c) write(a,b,c)
65 #define fm_peek(a,b,c) recv(a,b,c, MSG_PEEK)
67 #define fm_read(a,b,c) cygwin_read(a,b,c)
68 static ssize_t cygwin_read(int sock, void *buf, size_t count);
69 #else /* ! __CYGWIN__ */
70 #define fm_read(a,b,c) read(a,b,c)
71 #endif /* __CYGWIN__ */
74 /* We need to define h_errno only if it is not already */
77 #ifdef HAVE_RES_SEARCH
78 /* some versions of FreeBSD should declare this but don't */
81 /* pretend we have h_errno to avoid some #ifdef's later */
85 #endif /* ndef h_errno */
88 #include <net/security.h>
89 #endif /* NET_SECURITY */
91 #ifdef HAVE_SOCKETPAIR
92 static char *const *parse_plugin(const char *plugin, const char *host, const char *service)
93 { const char **argvec;
95 char *cp, *plugin_copy;
96 unsigned int plugin_copy_len;
97 unsigned int plugin_offset = 0, plugin_copy_offset = 0;
98 unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
99 unsigned int plugin_len = strlen(plugin);
100 unsigned int host_len = strlen(host);
101 unsigned int service_len = strlen(service);
103 for (c = p = plugin; *c; c++)
104 { if (isspace((unsigned char)*c) && !isspace((unsigned char)*p))
106 if (*p == '%' && *c == 'h')
108 if (*p == '%' && *c == 'p')
113 plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
114 plugin_copy = malloc(plugin_copy_len + 1);
117 report(stderr, GT_("fetchmail: malloc failed\n"));
121 while (plugin_copy_offset < plugin_copy_len)
122 { if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
123 { strcpy(plugin_copy + plugin_copy_offset, host);
125 plugin_copy_offset += host_len;
127 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
128 { strcpy(plugin_copy + plugin_copy_offset, service);
130 plugin_copy_offset += service_len;
133 { plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
135 plugin_copy_offset++;
138 plugin_copy[plugin_copy_len] = 0;
143 report(stderr, GT_("fetchmail: malloc failed\n"));
146 memset(argvec, 0, s);
147 for (c = p = plugin_copy, i = 0; *c; c++)
148 { if ((!isspace((unsigned char)*c)) && (c == p ? 1 : isspace((unsigned char)*p))) {
154 for (cp = plugin_copy; *cp; cp++)
155 { if (isspace((unsigned char)*cp))
158 return (char *const*)argvec;
161 static int handle_plugin(const char *host,
162 const char *service, const char *plugin)
163 /* get a socket mediated through a given external command */
169 * The author of this code, Felix von Leitner <felix@convergence.de>, says:
170 * he chose socketpair() instead of pipe() because socketpair creates
171 * bidirectional sockets while allegedly some pipe() implementations don't.
173 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
175 report(stderr, GT_("fetchmail: socketpair failed\n"));
181 report(stderr, GT_("fetchmail: fork failed\n"));
184 /* fds[1] is the parent's end; close it for proper EOF
186 (void) close(fds[1]);
187 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
188 report(stderr, GT_("dup2 failed\n"));
191 /* fds[0] is now connected to 0 and 1; close it */
192 (void) close(fds[0]);
193 if (outlevel >= O_VERBOSE)
194 report(stderr, GT_("running %s (host %s service %s)\n"), plugin, host, service);
195 argvec = parse_plugin(plugin,host,service);
196 execvp(*argvec, argvec);
197 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
200 default: /* parent */
204 /* fds[0] is the child's end; close it for proper EOF detection */
205 (void) close(fds[0]);
208 #endif /* HAVE_SOCKETPAIR */
212 int SockCheckOpen(int fd)
213 /* poll given socket; is it selectable? */
221 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
224 tv.tv_sec = 0; tv.tv_usec = 0;
225 rt = select(fd+1, &r, &w, &e, &tv);
226 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
232 #endif /* __UNUSED__ */
234 int UnixOpen(const char *path)
237 struct sockaddr_un ad;
238 memset(&ad, 0, sizeof(ad));
239 ad.sun_family = AF_UNIX;
240 strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
242 sock = socket( AF_UNIX, SOCK_STREAM, 0 );
249 /* Socket opened saved. Usefull if connect timeout
250 * because it can be closed.
252 mailserver_socket_temp = sock;
254 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
257 fm_close(sock); /* don't use SockClose, no traffic yet */
263 /* No connect timeout, then no need to set mailserver_socket_temp */
264 mailserver_socket_temp = -1;
270 int SockOpen(const char *host, const char *service, const char *options,
273 struct addrinfo *ai, *ai0, req;
276 void *request = NULL;
278 #endif /* NET_SECURITY */
280 #ifdef HAVE_SOCKETPAIR
282 return handle_plugin(host,service,plugin);
283 #endif /* HAVE_SOCKETPAIR */
284 memset(&req, 0, sizeof(struct addrinfo));
285 req.ai_socktype = SOCK_STREAM;
287 if (getaddrinfo(host, service, &req, &ai0)) {
288 report(stderr, GT_("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
296 if (net_security_strtorequest((char *)options, &request, &requestlen))
299 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
304 #else /* NET_SECURITY */
305 #ifdef HAVE_INNER_CONNECT
306 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
312 for (ai = ai0; ai; ai = ai->ai_next) {
313 i = socket(ai->ai_family, ai->ai_socktype, 0);
317 /* Socket opened saved. Usefull if connect timeout
318 * because it can be closed.
320 mailserver_socket_temp = i;
322 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
328 /* No connect timeout, then no need to set mailserver_socket_temp */
329 mailserver_socket_temp = -1;
335 #endif /* NET_SECURITY */
341 #else /* INET6_ENABLE */
342 #ifndef HAVE_INET_ATON
344 #ifdef INADDR_BROADCAST
345 #define INADDR_NONE INADDR_BROADCAST
347 #define INADDR_NONE -1
350 #endif /* HAVE_INET_ATON */
352 int SockOpen(const char *host, int clientPort, const char *options,
355 int sock = -1; /* pacify -Wall */
356 #ifndef HAVE_INET_ATON
357 unsigned long inaddr;
358 #endif /* HAVE_INET_ATON */
359 struct sockaddr_in ad, **pptr;
362 #ifdef HAVE_SOCKETPAIR
365 snprintf(buf, sizeof(buf), "%d", clientPort);
366 return handle_plugin(host,buf,plugin);
368 #endif /* HAVE_SOCKETPAIR */
370 memset(&ad, 0, sizeof(ad));
371 ad.sin_family = AF_INET;
373 /* we'll accept a quad address */
374 #ifndef HAVE_INET_ATON
375 inaddr = inet_addr((char*)host);
376 if (inaddr != INADDR_NONE)
378 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
380 if (inet_aton(host, &ad.sin_addr))
382 #endif /* HAVE_INET_ATON */
383 ad.sin_port = htons(clientPort);
385 sock = socket(AF_INET, SOCK_STREAM, 0);
392 /* Socket opened saved. Usefull if connect timeout because
395 mailserver_socket_temp = sock;
397 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
400 fm_close(sock); /* don't use SockClose, no traffic yet */
406 /* No connect timeout, then no need to set mailserver_socket_temp */
407 mailserver_socket_temp = -1;
409 #ifndef HAVE_INET_ATON
413 #endif /* HAVE_INET_ATON */
415 hp = gethostbyname((char*)host);
423 * Add a check to make sure the address has a valid IPv4 or IPv6
424 * length. This prevents buffer spamming by a broken DNS.
426 if(hp->h_length != 4 && hp->h_length != 8)
430 GT_("fetchmail: illegal address length received for host %s\n"),host);
434 * Try all addresses of a possibly multihomed host until we get
435 * a successful connect or until we run out of addresses.
437 pptr = (struct sockaddr_in **)hp->h_addr_list;
438 for(; *pptr != NULL; pptr++)
440 sock = socket(AF_INET, SOCK_STREAM, 0);
447 /* Socket opened saved. Usefull if connect timeout because
450 mailserver_socket_temp = sock;
452 ad.sin_port = htons(clientPort);
453 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
454 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0) {
455 /* No connect timeout, then no need to set mailserver_socket_temp */
456 mailserver_socket_temp = -1;
459 fm_close(sock); /* don't use SockClose, no traffic yet */
460 memset(&ad, 0, sizeof(ad));
461 ad.sin_family = AF_INET;
466 fm_close(sock); /* don't use SockClose, no traffic yet */
475 #endif /* INET6_ENABLE */
478 #if defined(HAVE_STDARG_H)
479 int SockPrintf(int sock, const char* format, ...)
482 int SockPrintf(sock,format,va_alist)
491 #if defined(HAVE_STDARG_H)
492 va_start(ap, format) ;
496 vsnprintf(buf, sizeof(buf), format, ap);
498 return SockWrite(sock, buf, strlen(buf));
503 #include <openssl/ssl.h>
504 #include <openssl/err.h>
505 #include <openssl/pem.h>
506 #include <openssl/x509.h>
507 #include <openssl/rand.h>
509 static SSL_CTX *_ctx = NULL;
510 static SSL *_ssl_context[FD_SETSIZE];
512 static SSL *SSLGetContext( int );
513 #endif /* SSL_ENABLE */
515 int SockWrite(int sock, char *buf, int len)
525 if( NULL != ( ssl = SSLGetContext( sock ) ) )
526 n = SSL_write(ssl, buf, len);
528 #endif /* SSL_ENABLE */
529 n = fm_write(sock, buf, len);
539 int SockRead(int sock, char *buf, int len)
541 char *newline, *bp = buf;
543 #ifdef FORCE_STUFFING
544 int maxavailable = 0;
562 * The reason for these gymnastics is that we want two things:
563 * (1) to read \n-terminated lines,
564 * (2) to return the true length of data read, even if the
565 * data coming in has embedded NULS.
568 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
570 /* OK... SSL_peek works a little different from MSG_PEEK
571 Problem is that SSL_peek can return 0 if there
572 is no data currently available. If, on the other
573 hand, we loose the socket, we also get a zero, but
574 the SSL_read then SEGFAULTS! To deal with this,
575 we'll check the error code any time we get a return
576 of zero from SSL_peek. If we have an error, we bail.
577 If we don't, we read one character in SSL_read and
578 loop. This should continue to work even if they
579 later change the behavior of SSL_peek
580 to "fix" this problem... :-( */
581 if ((n = SSL_peek(ssl, bp, len)) < 0) {
582 (void)SSL_get_error(ssl, n);
585 #ifdef FORCE_STUFFING
589 /* SSL_peek says no data... Does he mean no data
590 or did the connection blow up? If we got an error
592 if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
595 /* We didn't get an error so read at least one
596 character at this point and loop */
598 /* Make sure newline start out NULL!
599 * We don't have a string to pass through
600 * the strchr at this point yet */
602 } else if ((newline = memchr(bp, '\n', n)) != NULL)
603 n = newline - bp + 1;
604 /* Matthias Andree: SSL_read can return 0, in that case
605 * we must cal SSL_get_error to figure if there was
606 * an error or just a "no data" condition */
607 if ((n = SSL_read(ssl, bp, n)) <= 0) {
608 if ((n = SSL_get_error(ssl, n))) {
612 /* Check for case where our single character turned out to
613 * be a newline... (It wasn't going to get caught by
614 * the strchr above if it came from the hack... ). */
615 if( NULL == newline && 1 == n && '\n' == *bp ) {
616 /* Got our newline - this will break
617 out of the loop now */
622 #endif /* SSL_ENABLE */
626 if ((n = fm_read(sock, bp, 1)) <= 0)
628 if ((n = fm_peek(sock, bp, len)) <= 0)
631 #ifdef FORCE_STUFFING
634 if ((newline = memchr(bp, '\n', n)) != NULL)
635 n = newline - bp + 1;
637 if ((n = fm_read(sock, bp, n)) == -1)
639 #endif /* __BEOS__ */
647 #ifdef FORCE_STUFFING /* too ugly to live -- besides, there's IMAP */
648 /* OK, very weird hack coming up here:
649 * When POP3 servers send us a message, they're supposed to
650 * terminate the message with a line containing only a dot. To protect
651 * against lines in the real message that might contain only a dot,
652 * they're supposed to preface any line that starts with a dot with
653 * an additional dot, which will be removed on the client side. That
654 * process, called byte-stuffing (and unstuffing) is really not the
655 * concern of this low-level routine, ordinarily, but there are some
656 * POP servers (and maybe IMAP servers too, who knows) that fail to
657 * do the byte-stuffing, and this routine is the best place to try to
658 * identify and fix that fault.
660 * Since the DOT line is supposed to come only at the end of a
661 * message, the implication is that right after we see it, the server
662 * is supposed to go back to waiting for the next command. There
663 * isn't supposed to be any more data to read after we see the dot.
664 * THEREFORE, if we see more data to be read after something that
665 * looks like the dot line, then probably the server is failing to
666 * do byte-stuffing. In that case, we'll byte-pack it for them so
667 * that the higher-level routines see things as hunky-dorey.
668 * This is not a perfect test or fix by any means (it has an
669 * obvious race condition, for one thing), but it should at least
670 * reduce the nastiness that ensues when people don't know how
671 * to write POP servers.
673 if ((maxavailable > (bp-buf)) &&
680 (buf[1] == '\n')))) {
682 memmove(buf+1, buf, (bp-buf)+1);
686 #endif /* FORCE_STUFFING */
690 int SockPeek(int sock)
691 /* peek at the next socket character without actually reading it */
700 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
701 n = SSL_peek(ssl, &ch, 1);
703 (void)SSL_get_error(ssl, n);
707 /* This code really needs to implement a "hold back"
708 * to simulate a functioning SSL_peek()... sigh...
709 * Has to be coordinated with the read code above.
710 * Next on the list todo... */
712 /* SSL_peek says 0... Does that mean no data
713 or did the connection blow up? If we got an error
715 if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
719 /* Haven't seen this case actually occur, but...
720 if the problem in SockRead can occur, this should
721 be possible... Just not sure what to do here.
722 This should be a safe "punt" the "peek" but don't
723 "punt" the "session"... */
725 return 0; /* Give him a '\0' character */
729 #endif /* SSL_ENABLE */
730 n = fm_peek(sock, &ch, 1);
742 static char *_ssl_server_cname = NULL;
743 static int _check_fp;
744 static char *_check_digest;
745 static char *_server_label;
746 static int _depth0ck;
747 static int _prev_err;
749 SSL *SSLGetContext( int sock )
751 /* If SSLOpen has never initialized - just return NULL */
755 if( sock < 0 || sock > FD_SETSIZE )
757 return _ssl_context[sock];
761 /* ok_return (preverify_ok) is 1 if this stage of certificate verification
762 passed, or 0 if it failed. This callback lets us display informative
763 errors, and perform additional validation (e.g. CN matches) */
764 static int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
769 unsigned char digest[EVP_MAX_MD_SIZE];
770 char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
771 const EVP_MD *digest_tp;
772 unsigned int dsz, i, esz;
773 X509_NAME *subj, *issuer;
775 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
776 err = X509_STORE_CTX_get_error(ctx);
777 depth = X509_STORE_CTX_get_error_depth(ctx);
779 subj = X509_get_subject_name(x509_cert);
780 issuer = X509_get_issuer_name(x509_cert);
782 if (depth == 0 && !_depth0ck) {
785 if (outlevel == O_VERBOSE) {
786 if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
787 report(stdout, GT_("Issuer Organization: %s\n"), buf);
788 if (i >= sizeof(buf) - 1)
789 report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
791 report(stdout, GT_("Unknown Organization\n"));
792 if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
793 report(stdout, GT_("Issuer CommonName: %s\n"), buf);
794 if (i >= sizeof(buf) - 1)
795 report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
797 report(stdout, GT_("Unknown Issuer CommonName\n"));
799 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
800 if (outlevel == O_VERBOSE)
801 report(stdout, GT_("Server CommonName: %s\n"), buf);
802 if (i >= sizeof(buf) - 1) {
803 /* Possible truncation. In this case, this is a DNS name, so this
804 * is really bad. We do not tolerate this even in the non-strict case. */
805 report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
808 if (_ssl_server_cname != NULL) {
810 char *p2 = _ssl_server_cname;
815 n = strlen(p2) - strlen(p1);
819 if (0 != strcasecmp(p1, p2)) {
821 GT_("Server CommonName mismatch: %s != %s\n"),
822 buf, _ssl_server_cname );
823 if (ok_return && strict)
826 } else if (ok_return) {
827 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
828 if (strict) return (0);
831 if (outlevel == O_VERBOSE)
832 report(stdout, GT_("Unknown Server CommonName\n"));
833 if (ok_return && strict) {
834 report(stderr, GT_("Server name not specified in certificate!\n"));
838 /* Print the finger print. Note that on errors, we might print it more than once
839 * normally; we kluge around that by using a global variable. */
842 digest_tp = EVP_md5();
843 if (digest_tp == NULL) {
844 report(stderr, GT_("EVP_md5() failed!\n"));
847 if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
848 report(stderr, GT_("Out of memory!\n"));
852 te = text + sizeof(text);
853 for (i = 0; i < dsz; i++) {
854 esz = snprintf(tp, te - tp, i > 0 ? ":%02X" : "%02X", digest[i]);
855 if (esz >= te - tp) {
856 report(stderr, GT_("Digest text buffer too small!\n"));
861 if (outlevel > O_NORMAL)
862 report(stdout, GT_("%s key fingerprint: %s\n"), _server_label, text);
863 if (_check_digest != NULL) {
864 if (strcmp(text, _check_digest) == 0) {
865 if (outlevel > O_NORMAL)
866 report(stdout, GT_("%s fingerprints match.\n"), _server_label);
868 if (outlevel > O_SILENT)
869 report(stderr, GT_("%s fingerprints do not match!\n"), _server_label);
876 if (err != X509_V_OK && err != _prev_err) {
878 report(stderr, GT_("Server certificate verification error: %s\n"), X509_verify_cert_error_string(err));
879 /* We gave the error code, but maybe we can add some more details for debugging */
881 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
882 X509_NAME_oneline(issuer, buf, sizeof(buf));
883 buf[sizeof(buf) - 1] = '\0';
884 report(stderr, GT_("unknown issuer (first %d characters): %s\n"), sizeof(buf)-1, buf);
893 static int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
895 return SSL_verify_callback(ok_return, ctx, 0);
898 static int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
900 return SSL_verify_callback(ok_return, ctx, 1);
903 /* performs initial SSL handshake over the connected socket
904 * uses SSL *ssl global variable, which is currently defined
907 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, int certck, char *certpath,
908 char *fingerprint, char *servercname, char *label)
910 struct stat randstat;
913 SSL_load_error_strings();
914 SSLeay_add_ssl_algorithms();
917 if (stat("/dev/random", &randstat) &&
918 stat("/dev/urandom", &randstat)) {
919 /* Neither /dev/random nor /dev/urandom are present, so add
920 entropy to the SSL PRNG a hard way. */
921 for (i = 0; i < 10000 && ! RAND_status (); ++i) {
924 gettimeofday (&tv, 0);
925 buf[0] = tv.tv_usec & 0xF;
926 buf[2] = (tv.tv_usec & 0xF0) >> 4;
927 buf[3] = (tv.tv_usec & 0xF00) >> 8;
928 buf[1] = (tv.tv_usec & 0xF000) >> 12;
929 RAND_add (buf, sizeof buf, 0.1);
932 #endif /* SSL_ENABLE */
935 if( sock < 0 || sock > FD_SETSIZE ) {
936 report(stderr, GT_("File descriptor out of range for SSL") );
941 /* Be picky and make sure the memory is cleared */
942 memset( _ssl_context, 0, sizeof( _ssl_context ) );
944 if(!strcmp("ssl2",myproto)) {
945 _ctx = SSL_CTX_new(SSLv2_client_method());
946 } else if(!strcmp("ssl3",myproto)) {
947 _ctx = SSL_CTX_new(SSLv3_client_method());
948 } else if(!strcmp("tls1",myproto)) {
949 _ctx = SSL_CTX_new(TLSv1_client_method());
950 } else if (!strcmp("ssl23",myproto)) {
953 fprintf(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
958 _ctx = SSL_CTX_new(SSLv23_client_method());
961 ERR_print_errors_fp(stderr);
967 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_ck_verify_callback);
969 /* In this case, we do not fail if verification fails. However,
970 * we provide the callback for output and possible fingerprint checks. */
971 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_nock_verify_callback);
974 SSL_CTX_load_verify_locations(_ctx, NULL, certpath);
976 _ssl_context[sock] = SSL_new(_ctx);
978 if(_ssl_context[sock] == NULL) {
979 ERR_print_errors_fp(stderr);
983 /* This static is for the verify callback */
984 _ssl_server_cname = servercname;
985 _server_label = label;
987 _check_digest = fingerprint;
991 if( mycert || mykey ) {
993 /* Ok... He has a certificate file defined, so lets declare it. If
994 * he does NOT have a separate certificate and private key file then
995 * assume that it's a combined key and certificate file.
1001 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
1002 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
1005 SSL_set_fd(_ssl_context[sock], sock);
1007 if(SSL_connect(_ssl_context[sock]) < 1) {
1008 ERR_print_errors_fp(stderr);
1012 /* Paranoia: was the callback not called as we expected? */
1014 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
1016 if (fingerprint != NULL || certck) {
1017 if( NULL != SSLGetContext( sock ) ) {
1018 /* Clean up the SSL stack */
1019 SSL_free( _ssl_context[sock] );
1020 _ssl_context[sock] = NULL;
1030 int SockClose(int sock)
1031 /* close a socket gracefully */
1034 if( NULL != SSLGetContext( sock ) ) {
1035 /* Clean up the SSL stack */
1036 SSL_free( _ssl_context[sock] );
1037 _ssl_context[sock] = NULL;
1043 * This hangs in RedHat 6.2 after fetchmail runs for a while a
1044 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
1045 * the recv system call. (Reported from jtnews
1046 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
1048 * Half-close the connection first so the other end gets notified.
1050 * This stops sends but allows receives (effectively, it sends a
1052 if (shutdown(sock, 1) == 0) {
1054 /* If there is any data still waiting in the queue, discard it.
1055 * Call recv() until either it returns 0 (meaning we received a FIN)
1056 * or any error occurs. This makes sure all data sent by the other
1057 * side is acknowledged at the TCP level.
1059 if (fm_peek(sock, &ch, 1) > 0)
1060 while (fm_read(sock, &ch, 1) > 0)
1063 #endif /* __UNUSED__ */
1065 /* if there's an error closing at this point, not much we can do */
1066 return(fm_close(sock)); /* this is guarded */
1071 * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1072 * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1075 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1080 if ((n = read(sock, bp, count)) == -1)
1085 if (outlevel >= O_VERBOSE)
1086 report(stdout, GT_("Cygwin socket read retry\n"));
1087 n2 = read(sock, bp + n, count - n);
1088 if (n2 == -1 || n + n2 != count) {
1089 report(stderr, GT_("Cygwin socket read retry failed!\n"));
1096 #endif /* __CYGWIN__ */
1100 * Use the chargen service to test input buffering directly.
1101 * You may have to uncomment the `chargen' service description in your
1102 * inetd.conf (and then SIGHUP inetd) for this to work. */
1105 int sock = SockOpen("localhost", 19, NULL);
1108 while (SockRead(sock, buf, sizeof(buf)-1))
1109 SockWrite(1, buf, strlen(buf));
1114 /* socket.c ends here */