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>
17 #ifndef HAVE_NET_SOCKET_H
18 #include <sys/socket.h>
20 #include <net/socket.h>
23 #include <netinet/in.h>
24 #ifdef HAVE_ARPA_INET_H
25 #include <arpa/inet.h>
28 #if defined(STDC_HEADERS)
31 #if defined(HAVE_UNISTD_H)
34 #if defined(HAVE_STDARG_H)
40 #include "fetchmail.h"
43 /* Defines to allow BeOS to play nice... */
46 #define fm_close(a) closesocket(a)
47 #define fm_write(a,b,c) send(a,b,c,0)
48 #define fm_peek(a,b,c) recv(a,b,c,0)
49 #define fm_read(a,b,c) recv(a,b,c,0)
51 #define fm_close(a) close(a)
52 #define fm_write(a,b,c) write(a,b,c)
53 #define fm_peek(a,b,c) recv(a,b,c, MSG_PEEK)
54 #define fm_read(a,b,c) read(a,b,c)
57 /* We need to define h_errno only if it is not already */
60 #ifdef HAVE_RES_SEARCH
61 /* some versions of FreeBSD should declare this but don't */
64 /* pretend we have h_errno to avoid some #ifdef's later */
68 #endif /* ndef h_errno */
71 #include <net/security.h>
72 #endif /* NET_SECURITY */
74 #ifdef HAVE_SOCKETPAIR
75 char *const *parse_plugin(const char *plugin, const char *host, const char *service)
76 { const char **argvec;
78 char *cp, *plugin_copy;
79 unsigned int plugin_copy_len;
80 unsigned int plugin_offset = 0, plugin_copy_offset = 0;
81 unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
82 unsigned int plugin_len = strlen(plugin);
83 unsigned int host_len = strlen(host);
84 unsigned int service_len = strlen(service);
86 for (c = p = plugin; *c; c++)
87 { if (isspace(*c) && !isspace(*p))
89 if (*p == '%' && *c == 'h')
91 if (*p == '%' && *c == 'p')
96 plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
97 plugin_copy = malloc(plugin_copy_len + 1);
100 report(stderr, GT_("fetchmail: malloc failed\n"));
104 while (plugin_copy_offset < plugin_copy_len)
105 { if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
106 { strcpy(plugin_copy + plugin_copy_offset, host);
108 plugin_copy_offset += host_len;
110 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
111 { strcpy(plugin_copy + plugin_copy_offset, service);
113 plugin_copy_offset += service_len;
116 { plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
118 plugin_copy_offset++;
121 plugin_copy[plugin_copy_len] = 0;
126 report(stderr, GT_("fetchmail: malloc failed\n"));
129 memset(argvec, 0, s);
130 for (c = p = plugin_copy, i = 0; *c; c++)
131 { if ((!isspace(*c)) && (c == p ? 1 : isspace(*p))) {
137 for (cp = plugin_copy; *cp; cp++)
141 return (char *const*)argvec;
144 static int handle_plugin(const char *host,
145 const char *service, const char *plugin)
146 /* get a socket mediated through a given external command */
152 * The author of this code, Felix von Leitner <felix@convergence.de>, says:
153 * he chose socketpair() instead of pipe() because socketpair creates
154 * bidirectional sockets while allegedly some pipe() implementations don't.
156 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
158 report(stderr, GT_("fetchmail: socketpair failed\n"));
164 report(stderr, GT_("fetchmail: fork failed\n"));
168 /* fds[1] is the parent's end; close it for proper EOF
170 (void) close(fds[1]);
171 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
172 report(stderr, GT_("dup2 failed\n"));
175 /* fds[0] is now connected to 0 and 1; close it */
176 (void) close(fds[0]);
177 if (outlevel >= O_VERBOSE)
178 report(stderr, GT_("running %s (host %s service %s)\n"), plugin, host, service);
179 argvec = parse_plugin(plugin,host,service);
180 execvp(*argvec, argvec);
181 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
184 default: /* parent */
188 /* fds[0] is the child's end; close it for proper EOF detection */
189 (void) close(fds[0]);
192 #endif /* HAVE_SOCKETPAIR */
195 #include <sys/time.h>
197 int SockCheckOpen(int fd)
198 /* poll given socket; is it selectable? */
206 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
209 tv.tv_sec = 0; tv.tv_usec = 0;
210 rt = select(fd+1, &r, &w, &e, &tv);
211 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
217 #endif /* __UNUSED__ */
219 int UnixOpen(const char *path)
222 struct sockaddr_un ad;
223 memset(&ad, 0, sizeof(ad));
224 ad.sun_family = AF_UNIX;
225 strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
227 sock = socket( AF_UNIX, SOCK_STREAM, 0 );
233 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
236 fm_close(sock); /* don't use SockClose, no traffic yet */
245 int SockOpen(const char *host, const char *service, const char *options,
248 struct addrinfo *ai, *ai0, req;
251 void *request = NULL;
253 #endif /* NET_SECURITY */
255 #ifdef HAVE_SOCKETPAIR
257 return handle_plugin(host,service,plugin);
258 #endif /* HAVE_SOCKETPAIR */
259 memset(&req, 0, sizeof(struct addrinfo));
260 req.ai_socktype = SOCK_STREAM;
262 if (getaddrinfo(host, service, &req, &ai0)) {
263 report(stderr, GT_("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
271 if (net_security_strtorequest((char *)options, &request, &requestlen))
274 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
279 #else /* NET_SECURITY */
280 #ifdef HAVE_INNER_CONNECT
281 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
286 for (ai = ai0; ai; ai = ai->ai_next) {
287 i = socket(ai->ai_family, ai->ai_socktype, 0);
290 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
298 #endif /* NET_SECURITY */
304 #else /* INET6_ENABLE */
305 #ifndef HAVE_INET_ATON
307 #ifdef INADDR_BROADCAST
308 #define INADDR_NONE INADDR_BROADCAST
310 #define INADDR_NONE -1
313 #endif /* HAVE_INET_ATON */
315 int SockOpen(const char *host, int clientPort, const char *options,
318 int sock = -1; /* pacify -Wall */
319 #ifndef HAVE_INET_ATON
320 unsigned long inaddr;
321 #endif /* HAVE_INET_ATON */
322 struct sockaddr_in ad, **pptr;
325 #ifdef HAVE_SOCKETPAIR
329 snprintf(buf, sizeof(buf), /* Yeah, paranoic. So what? :P */
332 #endif /* HAVE_SNPRINTF */
334 return handle_plugin(host,buf,plugin);
336 #endif /* HAVE_SOCKETPAIR */
338 memset(&ad, 0, sizeof(ad));
339 ad.sin_family = AF_INET;
341 /* we'll accept a quad address */
342 #ifndef HAVE_INET_ATON
343 inaddr = inet_addr((char*)host);
344 if (inaddr != INADDR_NONE)
346 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
348 if (inet_aton(host, &ad.sin_addr))
350 #endif /* HAVE_INET_ATON */
351 ad.sin_port = htons(clientPort);
353 sock = socket(AF_INET, SOCK_STREAM, 0);
359 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
362 fm_close(sock); /* don't use SockClose, no traffic yet */
367 #ifndef HAVE_INET_ATON
371 #endif /* HAVE_INET_ATON */
373 hp = gethostbyname((char*)host);
381 * Add a check to make sure the address has a valid IPv4 or IPv6
382 * length. This prevents buffer spamming by a broken DNS.
384 if(hp->h_length != 4 && hp->h_length != 8)
388 GT_("fetchmail: illegal address length received for host %s\n"),host);
392 * Try all addresses of a possibly multihomed host until we get
393 * a successful connect or until we run out of addresses.
395 pptr = (struct sockaddr_in **)hp->h_addr_list;
396 for(; *pptr != NULL; pptr++)
398 sock = socket(AF_INET, SOCK_STREAM, 0);
404 ad.sin_port = htons(clientPort);
405 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
406 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
408 fm_close(sock); /* don't use SockClose, no traffic yet */
409 memset(&ad, 0, sizeof(ad));
410 ad.sin_family = AF_INET;
415 fm_close(sock); /* don't use SockClose, no traffic yet */
424 #endif /* INET6_ENABLE */
427 #if defined(HAVE_STDARG_H)
428 int SockPrintf(int sock, const char* format, ...)
431 int SockPrintf(sock,format,va_alist)
440 #if defined(HAVE_STDARG_H)
441 va_start(ap, format) ;
445 #ifdef HAVE_VSNPRINTF
446 vsnprintf(buf, sizeof(buf), format, ap);
448 vsprintf(buf, format, ap);
451 return SockWrite(sock, buf, strlen(buf));
456 #include "openssl/ssl.h"
457 #include "openssl/err.h"
458 #include "openssl/pem.h"
459 #include "openssl/x509.h"
461 static SSL_CTX *_ctx = NULL;
462 static SSL *_ssl_context[FD_SETSIZE];
464 SSL *SSLGetContext( int );
465 #endif /* SSL_ENABLE */
467 int SockWrite(int sock, char *buf, int len)
477 if( NULL != ( ssl = SSLGetContext( sock ) ) )
478 n = SSL_write(ssl, buf, len);
480 n = fm_write(sock, buf, len);
482 n = fm_write(sock, buf, len);
493 int SockRead(int sock, char *buf, int len)
495 char *newline, *bp = buf;
513 * The reason for these gymnastics is that we want two things:
514 * (1) to read \n-terminated lines,
515 * (2) to return the true length of data read, even if the
516 * data coming in has embedded NULS.
519 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
521 /* OK... SSL_peek works a little different from MSG_PEEK
522 Problem is that SSL_peek can return 0 if there
523 is no data currently available. If, on the other
524 hand, we loose the socket, we also get a zero, but
525 the SSL_read then SEGFAULTS! To deal with this,
526 we'll check the error code any time we get a return
527 of zero from SSL_peek. If we have an error, we bail.
528 If we don't, we read one character in SSL_read and
529 loop. This should continue to work even if they
530 later change the behavior of SSL_peek
531 to "fix" this problem... :-( */
532 if ((n = SSL_peek(ssl, bp, len)) < 0) {
536 /* SSL_peek says no data... Does he mean no data
537 or did the connection blow up? If we got an error
539 if( 0 != ( n = ERR_get_error() ) ) {
542 /* We didn't get an error so read at least one
543 character at this point and loop */
545 /* Make sure newline start out NULL!
546 * We don't have a string to pass through
547 * the strchr at this point yet */
549 } else if ((newline = memchr(bp, '\n', n)) != NULL)
550 n = newline - bp + 1;
551 if ((n = SSL_read(ssl, bp, n)) == -1) {
554 /* Check for case where our single character turned out to
555 * be a newline... (It wasn't going to get caught by
556 * the strchr above if it came from the hack... ). */
557 if( NULL == newline && 1 == n && '\n' == *bp ) {
558 /* Got our newline - this will break
559 out of the loop now */
563 if ((n = fm_peek(sock, bp, len)) <= 0)
565 if ((newline = memchr(bp, '\n', n)) != NULL)
566 n = newline - bp + 1;
567 if ((n = fm_read(sock, bp, n)) == -1)
573 if ((n = fm_read(sock, bp, 1)) <= 0)
575 if ((n = fm_peek(sock, bp, len)) <= 0)
578 if ((newline = memchr(bp, '\n', n)) != NULL)
579 n = newline - bp + 1;
581 if ((n = fm_read(sock, bp, n)) == -1)
583 #endif /* __BEOS__ */
593 int SockPeek(int sock)
594 /* peek at the next socket character without actually reading it */
603 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
604 n = SSL_peek(ssl, &ch, 1);
606 /* This code really needs to implement a "hold back"
607 * to simulate a functioning SSL_peek()... sigh...
608 * Has to be coordinated with the read code above.
609 * Next on the list todo... */
611 /* SSL_peek says no data... Does he mean no data
612 or did the connection blow up? If we got an error
614 if( 0 != ( n = ERR_get_error() ) ) {
618 /* Haven't seen this case actually occur, but...
619 if the problem in SockRead can occur, this should
620 be possible... Just not sure what to do here.
621 This should be a safe "punt" the "peek" but don't
622 "punt" the "session"... */
624 return 0; /* Give him a '\0' character */
627 n = fm_peek(sock, &ch, 1);
631 n = fm_peek(sock, &ch, 1);
633 #endif /* SSL_ENABLE */
645 static char *_ssl_server_cname = NULL;
646 static int _check_fp;
647 static char *_check_digest;
648 static char *_server_label;
649 static int _depth0ck;
651 SSL *SSLGetContext( int sock )
653 /* If SSLOpen has never initialized - just return NULL */
657 if( sock < 0 || sock > FD_SETSIZE )
659 return _ssl_context[sock];
663 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
668 unsigned char digest[EVP_MAX_MD_SIZE];
669 char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
671 unsigned int dsz, i, esz;
672 X509_NAME *subj, *issuer;
674 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
675 err = X509_STORE_CTX_get_error(ctx);
676 depth = X509_STORE_CTX_get_error_depth(ctx);
678 subj = X509_get_subject_name(x509_cert);
679 issuer = X509_get_issuer_name(x509_cert);
684 if (outlevel == O_VERBOSE) {
685 if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
686 report(stdout, GT_("Issuer Organization: %s\n"), buf);
687 if (i >= sizeof(buf) - 1)
688 report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
690 report(stdout, GT_("Unknown Organization\n"));
691 if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
692 report(stdout, GT_("Issuer CommonName: %s\n"), buf);
693 if (i >= sizeof(buf) - 1)
694 report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
696 report(stdout, GT_("Unknown Issuer CommonName\n"));
698 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
699 if (outlevel == O_VERBOSE)
700 report(stdout, GT_("Server CommonName: %s\n"), buf);
701 if (i >= sizeof(buf) - 1) {
702 /* Possible truncation. In this case, this is a DNS name, so this
703 * is really bad. We do not tolerate this even in the non-strict case. */
704 report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
707 if (_ssl_server_cname != NULL) {
709 char *p2 = _ssl_server_cname;
714 n = strlen(p2) - strlen(p1);
718 if (0 != strcasecmp(p1, p2)) {
720 GT_("Server CommonName mismatch: %s != %s\n"),
721 buf, _ssl_server_cname );
722 if (ok_return && strict)
725 } else if (ok_return && strict) {
726 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
730 if (outlevel == O_VERBOSE)
731 report(stdout, GT_("Unknown Server CommonName\n"));
732 if (ok_return && strict) {
733 report(stderr, GT_("Server name not specified in certificate!\n"));
737 /* Print the finger print. Note that on errors, we might print it more than once
738 * normally; we kluge around that by using a global variable. */
741 digest_tp = EVP_md5();
742 if (digest_tp == NULL) {
743 report(stderr, GT_("EVP_md5() failed!\n"));
746 if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
747 report(stderr, GT_("Out of memory!\n"));
751 te = text + sizeof(text);
752 for (i = 0; i < dsz; i++) {
754 esz = snprintf(tp, te - tp, i > 0 ? ":%02X" : "%02X", digest[i]);
756 esz = sprintf(tp, i > 0 ? ":%02X" : "%02X", digest[i]);
758 if (esz >= te - tp) {
759 report(stderr, GT_("Digest text buffer too small!\n"));
764 report(stdout, GT_("%s key fingerprint: %s\n"), _server_label, text);
765 if (_check_digest != NULL) {
766 if (strcmp(text, _check_digest) == 0)
767 report(stdout, GT_("%s fingerprints match.\n"), _server_label);
769 report(stderr, GT_("%s fingerprints do not match!\n"), _server_label);
776 if (err != X509_V_OK && (strict || outlevel == O_VERBOSE)) {
777 report(strict ? stderr : stdout, GT_("Warning: server certificate verification: %s\n"), X509_verify_cert_error_string(err));
778 /* We gave the error code, but maybe we can add some more details for debugging */
780 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
781 X509_NAME_oneline(issuer, buf, sizeof(buf));
782 buf[sizeof(buf) - 1] = '\0';
783 report(stdout, GT_("unknown issuer (first %d characters): %s\n"), sizeof(buf), buf);
792 int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
794 return SSL_verify_callback(ok_return, ctx, 0);
797 int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
799 return SSL_verify_callback(ok_return, ctx, 1);
802 /* performs initial SSL handshake over the connected socket
803 * uses SSL *ssl global variable, which is currently defined
806 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, int certck, char *certpath,
807 char *fingerprint, char *servercname, char *label)
811 SSL_load_error_strings();
812 SSLeay_add_ssl_algorithms();
814 if( sock < 0 || sock > FD_SETSIZE ) {
815 report(stderr, GT_("File descriptor out of range for SSL") );
820 /* Be picky and make sure the memory is cleared */
821 memset( _ssl_context, 0, sizeof( _ssl_context ) );
823 if(!strcmp("ssl2",myproto)) {
824 _ctx = SSL_CTX_new(SSLv2_client_method());
825 } else if(!strcmp("ssl3",myproto)) {
826 _ctx = SSL_CTX_new(SSLv3_client_method());
827 } else if(!strcmp("tls1",myproto)) {
828 _ctx = SSL_CTX_new(TLSv1_client_method());
830 fprintf(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
835 _ctx = SSL_CTX_new(SSLv23_client_method());
838 ERR_print_errors_fp(stderr);
844 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_ck_verify_callback);
846 SSL_CTX_load_verify_locations(_ctx, NULL, certpath);
848 /* In this case, we do not fail if verification fails. However,
849 * we provide the callback for output and possible fingerprint checks. */
850 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_nock_verify_callback);
853 _ssl_context[sock] = SSL_new(_ctx);
855 if(_ssl_context[sock] == NULL) {
856 ERR_print_errors_fp(stderr);
860 /* This static is for the verify callback */
861 _ssl_server_cname = servercname;
862 _server_label = label;
864 _check_digest = fingerprint;
867 if( mycert || mykey ) {
869 /* Ok... He has a certificate file defined, so lets declare it. If
870 * he does NOT have a separate certificate and private key file then
871 * assume that it's a combined key and certificate file.
877 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
878 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
881 SSL_set_fd(_ssl_context[sock], sock);
883 if(SSL_connect(_ssl_context[sock]) == -1) {
884 ERR_print_errors_fp(stderr);
888 /* Paranoia: was the callback not called as we expected? */
889 if ((fingerprint != NULL || certck) && !_depth0ck) {
890 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
892 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
893 /* Clean up the SSL stack */
894 SSL_free( _ssl_context[sock] );
895 _ssl_context[sock] = NULL;
904 int SockClose(int sock)
905 /* close a socket gracefully */
910 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
911 /* Clean up the SSL stack */
912 SSL_free( _ssl_context[sock] );
913 _ssl_context[sock] = NULL;
919 * This hangs in RedHat 6.2 after fetchmail runs for a while a
920 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
921 * the recv system call. (Reported from jtnews
922 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
924 * Half-close the connection first so the other end gets notified.
926 * This stops sends but allows receives (effectively, it sends a
928 if (shutdown(sock, 1) == 0) {
930 /* If there is any data still waiting in the queue, discard it.
931 * Call recv() until either it returns 0 (meaning we received a FIN)
932 * or any error occurs. This makes sure all data sent by the other
933 * side is acknowledged at the TCP level.
935 if (fm_peek(sock, &ch, 1) > 0)
936 while (fm_read(sock, &ch, 1) > 0)
939 #endif /* __UNUSED__ */
941 /* if there's an error closing at this point, not much we can do */
942 return(fm_close(sock)); /* this is guarded */
947 * Use the chargen service to test input buffering directly.
948 * You may have to uncomment the `chargen' service description in your
949 * inetd.conf (and then SIGHUP inetd) for this to work. */
952 int sock = SockOpen("localhost", 19, NULL);
955 while (SockRead(sock, buf, sizeof(buf)-1))
956 SockWrite(1, buf, strlen(buf));
961 /* socket.c ends here */