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(*c) && !isspace(*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(*c)) && (c == p ? 1 : isspace(*p))) {
143 for (cp = plugin_copy; *cp; 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
355 snprintf(buf, sizeof(buf), /* Yeah, paranoic. So what? :P */
358 #endif /* HAVE_SNPRINTF */
360 return handle_plugin(host,buf,plugin);
362 #endif /* HAVE_SOCKETPAIR */
364 memset(&ad, 0, sizeof(ad));
365 ad.sin_family = AF_INET;
367 /* we'll accept a quad address */
368 #ifndef HAVE_INET_ATON
369 inaddr = inet_addr((char*)host);
370 if (inaddr != INADDR_NONE)
372 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
374 if (inet_aton(host, &ad.sin_addr))
376 #endif /* HAVE_INET_ATON */
377 ad.sin_port = htons(clientPort);
379 sock = socket(AF_INET, SOCK_STREAM, 0);
386 /* Socket opened saved. Usefull if connect timeout because
389 mailserver_socket_temp = sock;
391 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
394 fm_close(sock); /* don't use SockClose, no traffic yet */
400 /* No connect timeout, then no need to set mailserver_socket_temp */
401 mailserver_socket_temp = -1;
403 #ifndef HAVE_INET_ATON
407 #endif /* HAVE_INET_ATON */
409 hp = gethostbyname((char*)host);
417 * Add a check to make sure the address has a valid IPv4 or IPv6
418 * length. This prevents buffer spamming by a broken DNS.
420 if(hp->h_length != 4 && hp->h_length != 8)
424 GT_("fetchmail: illegal address length received for host %s\n"),host);
428 * Try all addresses of a possibly multihomed host until we get
429 * a successful connect or until we run out of addresses.
431 pptr = (struct sockaddr_in **)hp->h_addr_list;
432 for(; *pptr != NULL; pptr++)
434 sock = socket(AF_INET, SOCK_STREAM, 0);
441 /* Socket opened saved. Usefull if connect timeout because
444 mailserver_socket_temp = sock;
446 ad.sin_port = htons(clientPort);
447 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
448 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0) {
449 /* No connect timeout, then no need to set mailserver_socket_temp */
450 mailserver_socket_temp = -1;
453 fm_close(sock); /* don't use SockClose, no traffic yet */
454 memset(&ad, 0, sizeof(ad));
455 ad.sin_family = AF_INET;
460 fm_close(sock); /* don't use SockClose, no traffic yet */
469 #endif /* INET6_ENABLE */
472 #if defined(HAVE_STDARG_H)
473 int SockPrintf(int sock, const char* format, ...)
476 int SockPrintf(sock,format,va_alist)
485 #if defined(HAVE_STDARG_H)
486 va_start(ap, format) ;
490 #ifdef HAVE_VSNPRINTF
491 vsnprintf(buf, sizeof(buf), format, ap);
493 vsprintf(buf, format, ap);
496 return SockWrite(sock, buf, strlen(buf));
501 #include <openssl/ssl.h>
502 #include <openssl/err.h>
503 #include <openssl/pem.h>
504 #include <openssl/x509.h>
505 #include <openssl/rand.h>
507 static SSL_CTX *_ctx = NULL;
508 static SSL *_ssl_context[FD_SETSIZE];
510 SSL *SSLGetContext( int );
511 #endif /* SSL_ENABLE */
513 int SockWrite(int sock, char *buf, int len)
523 if( NULL != ( ssl = SSLGetContext( sock ) ) )
524 n = SSL_write(ssl, buf, len);
526 #endif /* SSL_ENABLE */
527 n = fm_write(sock, buf, len);
537 int SockRead(int sock, char *buf, int len)
539 char *newline, *bp = buf;
541 int maxavailable = 0;
558 * The reason for these gymnastics is that we want two things:
559 * (1) to read \n-terminated lines,
560 * (2) to return the true length of data read, even if the
561 * data coming in has embedded NULS.
564 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
566 /* OK... SSL_peek works a little different from MSG_PEEK
567 Problem is that SSL_peek can return 0 if there
568 is no data currently available. If, on the other
569 hand, we loose the socket, we also get a zero, but
570 the SSL_read then SEGFAULTS! To deal with this,
571 we'll check the error code any time we get a return
572 of zero from SSL_peek. If we have an error, we bail.
573 If we don't, we read one character in SSL_read and
574 loop. This should continue to work even if they
575 later change the behavior of SSL_peek
576 to "fix" this problem... :-( */
577 if ((n = SSL_peek(ssl, bp, len)) < 0) {
578 (void)SSL_get_error(ssl, n);
583 /* SSL_peek says no data... Does he mean no data
584 or did the connection blow up? If we got an error
586 if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
589 /* We didn't get an error so read at least one
590 character at this point and loop */
592 /* Make sure newline start out NULL!
593 * We don't have a string to pass through
594 * the strchr at this point yet */
596 } else if ((newline = memchr(bp, '\n', n)) != NULL)
597 n = newline - bp + 1;
598 /* Matthias Andree: SSL_read can return 0, in that case
599 * we must cal SSL_get_error to figure if there was
600 * an error or just a "no data" condition */
601 if ((n = SSL_read(ssl, bp, n)) <= 0) {
602 if ((n = SSL_get_error(ssl, n))) {
606 /* Check for case where our single character turned out to
607 * be a newline... (It wasn't going to get caught by
608 * the strchr above if it came from the hack... ). */
609 if( NULL == newline && 1 == n && '\n' == *bp ) {
610 /* Got our newline - this will break
611 out of the loop now */
616 #endif /* SSL_ENABLE */
620 if ((n = fm_read(sock, bp, 1)) <= 0)
622 if ((n = fm_peek(sock, bp, len)) <= 0)
626 if ((newline = memchr(bp, '\n', n)) != NULL)
627 n = newline - bp + 1;
629 if ((n = fm_read(sock, bp, n)) == -1)
631 #endif /* __BEOS__ */
639 #ifdef FORCE_STUFFING /* too ugly to live -- besides, there's IMAP */
640 /* OK, very weird hack coming up here:
641 * When POP3 servers send us a message, they're supposed to
642 * terminate the message with a line containing only a dot. To protect
643 * against lines in the real message that might contain only a dot,
644 * they're supposed to preface any line that starts with a dot with
645 * an additional dot, which will be removed on the client side. That
646 * process, called byte-stuffing (and unstuffing) is really not the
647 * concern of this low-level routine, ordinarily, but there are some
648 * POP servers (and maybe IMAP servers too, who knows) that fail to
649 * do the byte-stuffing, and this routine is the best place to try to
650 * identify and fix that fault.
652 * Since the DOT line is supposed to come only at the end of a
653 * message, the implication is that right after we see it, the server
654 * is supposed to go back to waiting for the next command. There
655 * isn't supposed to be any more data to read after we see the dot.
656 * THEREFORE, if we see more data to be read after something that
657 * looks like the dot line, then probably the server is failing to
658 * do byte-stuffing. In that case, we'll byte-pack it for them so
659 * that the higher-level routines see things as hunky-dorey.
660 * This is not a perfect test or fix by any means (it has an
661 * obvious race condition, for one thing), but it should at least
662 * reduce the nastiness that ensues when people don't know how
663 * to write POP servers.
665 if ((maxavailable > (bp-buf)) &&
672 (buf[1] == '\n')))) {
674 memmove(buf+1, buf, (bp-buf)+1);
678 #endif /* FORCE_STUFFING */
682 int SockPeek(int sock)
683 /* peek at the next socket character without actually reading it */
692 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
693 n = SSL_peek(ssl, &ch, 1);
695 (void)SSL_get_error(ssl, n);
699 /* This code really needs to implement a "hold back"
700 * to simulate a functioning SSL_peek()... sigh...
701 * Has to be coordinated with the read code above.
702 * Next on the list todo... */
704 /* SSL_peek says 0... Does that mean no data
705 or did the connection blow up? If we got an error
707 if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
711 /* Haven't seen this case actually occur, but...
712 if the problem in SockRead can occur, this should
713 be possible... Just not sure what to do here.
714 This should be a safe "punt" the "peek" but don't
715 "punt" the "session"... */
717 return 0; /* Give him a '\0' character */
721 #endif /* SSL_ENABLE */
722 n = fm_peek(sock, &ch, 1);
734 static char *_ssl_server_cname = NULL;
735 static int _check_fp;
736 static char *_check_digest;
737 static char *_server_label;
738 static int _depth0ck;
740 SSL *SSLGetContext( int sock )
742 /* If SSLOpen has never initialized - just return NULL */
746 if( sock < 0 || sock > FD_SETSIZE )
748 return _ssl_context[sock];
752 static int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
757 unsigned char digest[EVP_MAX_MD_SIZE];
758 char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
759 const EVP_MD *digest_tp;
760 unsigned int dsz, i, esz;
761 X509_NAME *subj, *issuer;
763 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
764 err = X509_STORE_CTX_get_error(ctx);
765 depth = X509_STORE_CTX_get_error_depth(ctx);
767 subj = X509_get_subject_name(x509_cert);
768 issuer = X509_get_issuer_name(x509_cert);
773 if (outlevel == O_VERBOSE) {
774 if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
775 report(stdout, GT_("Issuer Organization: %s\n"), buf);
776 if (i >= sizeof(buf) - 1)
777 report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
779 report(stdout, GT_("Unknown Organization\n"));
780 if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
781 report(stdout, GT_("Issuer CommonName: %s\n"), buf);
782 if (i >= sizeof(buf) - 1)
783 report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
785 report(stdout, GT_("Unknown Issuer CommonName\n"));
787 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
788 if (outlevel == O_VERBOSE)
789 report(stdout, GT_("Server CommonName: %s\n"), buf);
790 if (i >= sizeof(buf) - 1) {
791 /* Possible truncation. In this case, this is a DNS name, so this
792 * is really bad. We do not tolerate this even in the non-strict case. */
793 report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
796 if (_ssl_server_cname != NULL) {
798 char *p2 = _ssl_server_cname;
803 n = strlen(p2) - strlen(p1);
807 if (0 != strcasecmp(p1, p2)) {
809 GT_("Server CommonName mismatch: %s != %s\n"),
810 buf, _ssl_server_cname );
811 if (ok_return && strict)
814 } else if (ok_return && strict) {
815 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
819 if (outlevel == O_VERBOSE)
820 report(stdout, GT_("Unknown Server CommonName\n"));
821 if (ok_return && strict) {
822 report(stderr, GT_("Server name not specified in certificate!\n"));
826 /* Print the finger print. Note that on errors, we might print it more than once
827 * normally; we kluge around that by using a global variable. */
830 digest_tp = EVP_md5();
831 if (digest_tp == NULL) {
832 report(stderr, GT_("EVP_md5() failed!\n"));
835 if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
836 report(stderr, GT_("Out of memory!\n"));
840 te = text + sizeof(text);
841 for (i = 0; i < dsz; i++) {
843 esz = snprintf(tp, te - tp, i > 0 ? ":%02X" : "%02X", digest[i]);
845 esz = sprintf(tp, i > 0 ? ":%02X" : "%02X", digest[i]);
847 if (esz >= te - tp) {
848 report(stderr, GT_("Digest text buffer too small!\n"));
853 if (outlevel > O_NORMAL)
854 report(stdout, GT_("%s key fingerprint: %s\n"), _server_label, text);
855 if (_check_digest != NULL) {
856 if (strcmp(text, _check_digest) == 0) {
857 if (outlevel > O_NORMAL)
858 report(stdout, GT_("%s fingerprints match.\n"), _server_label);
860 if (outlevel > O_SILENT)
861 report(stderr, GT_("%s fingerprints do not match!\n"), _server_label);
868 if (err != X509_V_OK && (strict || outlevel == O_VERBOSE)) {
869 report(strict ? stderr : stdout, GT_("Warning: server certificate verification: %s\n"), X509_verify_cert_error_string(err));
870 /* We gave the error code, but maybe we can add some more details for debugging */
872 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
873 X509_NAME_oneline(issuer, buf, sizeof(buf));
874 buf[sizeof(buf) - 1] = '\0';
875 report(stdout, GT_("unknown issuer (first %d characters): %s\n"), sizeof(buf), buf);
884 static int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
886 return SSL_verify_callback(ok_return, ctx, 0);
889 static int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
891 return SSL_verify_callback(ok_return, ctx, 1);
894 /* performs initial SSL handshake over the connected socket
895 * uses SSL *ssl global variable, which is currently defined
898 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, int certck, char *certpath,
899 char *fingerprint, char *servercname, char *label)
902 struct stat randstat;
905 SSL_load_error_strings();
906 SSLeay_add_ssl_algorithms();
909 if (stat("/dev/random", &randstat) &&
910 stat("/dev/urandom", &randstat)) {
911 /* Neither /dev/random nor /dev/urandom are present, so add
912 entropy to the SSL PRNG a hard way. */
913 for (i = 0; i < 10000 && ! RAND_status (); ++i) {
916 gettimeofday (&tv, 0);
917 buf[0] = tv.tv_usec & 0xF;
918 buf[2] = (tv.tv_usec & 0xF0) >> 4;
919 buf[3] = (tv.tv_usec & 0xF00) >> 8;
920 buf[1] = (tv.tv_usec & 0xF000) >> 12;
921 RAND_add (buf, sizeof buf, 0.1);
924 #endif /* SSL_ENABLE */
927 if( sock < 0 || sock > FD_SETSIZE ) {
928 report(stderr, GT_("File descriptor out of range for SSL") );
933 /* Be picky and make sure the memory is cleared */
934 memset( _ssl_context, 0, sizeof( _ssl_context ) );
936 if(!strcmp("ssl2",myproto)) {
937 _ctx = SSL_CTX_new(SSLv2_client_method());
938 } else if(!strcmp("ssl3",myproto)) {
939 _ctx = SSL_CTX_new(SSLv3_client_method());
940 } else if(!strcmp("tls1",myproto)) {
941 _ctx = SSL_CTX_new(TLSv1_client_method());
942 } else if (!strcmp("ssl23",myproto)) {
945 fprintf(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
950 _ctx = SSL_CTX_new(SSLv23_client_method());
953 ERR_print_errors_fp(stderr);
959 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_ck_verify_callback);
961 SSL_CTX_load_verify_locations(_ctx, NULL, certpath);
963 /* In this case, we do not fail if verification fails. However,
964 * we provide the callback for output and possible fingerprint checks. */
965 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_nock_verify_callback);
968 _ssl_context[sock] = SSL_new(_ctx);
970 if(_ssl_context[sock] == NULL) {
971 ERR_print_errors_fp(stderr);
975 /* This static is for the verify callback */
976 _ssl_server_cname = servercname;
977 _server_label = label;
979 _check_digest = fingerprint;
982 if( mycert || mykey ) {
984 /* Ok... He has a certificate file defined, so lets declare it. If
985 * he does NOT have a separate certificate and private key file then
986 * assume that it's a combined key and certificate file.
992 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
993 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
996 SSL_set_fd(_ssl_context[sock], sock);
998 if(SSL_connect(_ssl_context[sock]) < 1) {
999 ERR_print_errors_fp(stderr);
1003 /* Paranoia: was the callback not called as we expected? */
1004 if ((fingerprint != NULL || certck) && !_depth0ck) {
1005 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
1007 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
1008 /* Clean up the SSL stack */
1009 SSL_free( _ssl_context[sock] );
1010 _ssl_context[sock] = NULL;
1019 int SockClose(int sock)
1020 /* close a socket gracefully */
1025 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
1026 /* Clean up the SSL stack */
1027 SSL_free( _ssl_context[sock] );
1028 _ssl_context[sock] = NULL;
1034 * This hangs in RedHat 6.2 after fetchmail runs for a while a
1035 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
1036 * the recv system call. (Reported from jtnews
1037 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
1039 * Half-close the connection first so the other end gets notified.
1041 * This stops sends but allows receives (effectively, it sends a
1043 if (shutdown(sock, 1) == 0) {
1045 /* If there is any data still waiting in the queue, discard it.
1046 * Call recv() until either it returns 0 (meaning we received a FIN)
1047 * or any error occurs. This makes sure all data sent by the other
1048 * side is acknowledged at the TCP level.
1050 if (fm_peek(sock, &ch, 1) > 0)
1051 while (fm_read(sock, &ch, 1) > 0)
1054 #endif /* __UNUSED__ */
1056 /* if there's an error closing at this point, not much we can do */
1057 return(fm_close(sock)); /* this is guarded */
1062 * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1063 * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1066 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1071 if ((n = read(sock, bp, count)) == -1)
1076 if (outlevel >= O_VERBOSE)
1077 report(stdout, GT_("Cygwin socket read retry\n"));
1078 n2 = read(sock, bp + n, count - n);
1079 if (n2 == -1 || n + n2 != count) {
1080 report(stderr, GT_("Cygwin socket read retry failed!\n"));
1087 #endif /* __CYGWIN__ */
1091 * Use the chargen service to test input buffering directly.
1092 * You may have to uncomment the `chargen' service description in your
1093 * inetd.conf (and then SIGHUP inetd) for this to work. */
1096 int sock = SockOpen("localhost", 19, NULL);
1099 while (SockRead(sock, buf, sizeof(buf)-1))
1100 SockWrite(1, buf, strlen(buf));
1105 /* socket.c ends here */