2 * socket.c -- socket library functions
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
14 #endif /* HAVE_MEMORY_H */
15 #include <sys/types.h>
16 #ifndef HAVE_NET_SOCKET_H
17 #include <sys/socket.h>
19 #include <net/socket.h>
22 #include <netinet/in.h>
23 #ifdef HAVE_ARPA_INET_H
24 #include <arpa/inet.h>
27 #if defined(STDC_HEADERS)
30 #if defined(HAVE_UNISTD_H)
33 #if defined(HAVE_STDARG_H)
39 #include "fetchmail.h"
42 /* Defines to allow BeOS to play nice... */
45 #define fm_close(a) closesocket(a)
46 #define fm_write(a,b,c) send(a,b,c,0)
47 #define fm_peek(a,b,c) recv(a,b,c,0)
48 #define fm_read(a,b,c) recv(a,b,c,0)
50 #define fm_close(a) close(a)
51 #define fm_write(a,b,c) write(a,b,c)
52 #define fm_peek(a,b,c) recv(a,b,c, MSG_PEEK)
53 #define fm_read(a,b,c) read(a,b,c)
56 /* We need to define h_errno only if it is not already */
59 #ifdef HAVE_RES_SEARCH
60 /* some versions of FreeBSD should declare this but don't */
63 /* pretend we have h_errno to avoid some #ifdef's later */
67 #endif /* ndef h_errno */
70 #include <net/security.h>
71 #endif /* NET_SECURITY */
73 #ifdef HAVE_SOCKETPAIR
74 char *const *parse_plugin(const char *plugin, const char *host, const char *service)
75 { const char **argvec;
77 char *cp, *plugin_copy;
78 unsigned int plugin_copy_len;
79 unsigned int plugin_offset = 0, plugin_copy_offset = 0;
80 unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
81 unsigned int plugin_len = strlen(plugin);
82 unsigned int host_len = strlen(host);
83 unsigned int service_len = strlen(service);
85 for (c = p = plugin; *c; c++)
86 { if (isspace(*c) && !isspace(*p))
88 if (*p == '%' && *c == 'h')
90 if (*p == '%' && *c == 'p')
95 plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
96 plugin_copy = malloc(plugin_copy_len + 1);
99 report(stderr, _("fetchmail: malloc failed\n"));
103 while (plugin_copy_offset < plugin_copy_len)
104 { if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
105 { strcat(plugin_copy + plugin_copy_offset, host);
107 plugin_copy_offset += host_len;
109 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
110 { strcat(plugin_copy + plugin_copy_offset, service);
112 plugin_copy_offset += service_len;
115 { plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
117 plugin_copy_offset++;
120 plugin_copy[plugin_copy_len] = 0;
125 report(stderr, _("fetchmail: malloc failed\n"));
128 memset(argvec, 0, s);
129 for (c = p = plugin_copy, i = 0; *c; c++)
130 { if ((!isspace(*c)) && (c == p ? 1 : isspace(*p))) {
136 for (cp = plugin_copy; *cp; cp++)
140 return (char *const*)argvec;
143 static int handle_plugin(const char *host,
144 const char *service, const char *plugin)
145 /* get a socket mediated through a given external command */
151 * The author of this code, Felix von Leitner <felix@convergence.de>, says:
152 * he chose socketpair() instead of pipe() because socketpair creates
153 * bidirectional sockets while allegedly some pipe() implementations don't.
155 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
157 report(stderr, _("fetchmail: socketpair failed\n"));
163 report(stderr, _("fetchmail: fork failed\n"));
167 /* fds[1] is the parent's end; close it for proper EOF
169 (void) close(fds[1]);
170 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
171 report(stderr, _("dup2 failed\n"));
174 /* fds[0] is now connected to 0 and 1; close it */
175 (void) close(fds[0]);
176 if (outlevel >= O_VERBOSE)
177 report(stderr, _("running %s (host %s service %s)\n"), plugin, host, service);
178 argvec = parse_plugin(plugin,host,service);
179 execvp(*argvec, argvec);
180 report(stderr, _("execvp(%s) failed\n"), *argvec);
183 default: /* parent */
187 /* fds[0] is the child's end; close it for proper EOF detection */
188 (void) close(fds[0]);
191 #endif /* HAVE_SOCKETPAIR */
194 #include <sys/time.h>
196 int SockCheckOpen(int fd)
197 /* poll given socket; is it selectable? */
205 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
208 tv.tv_sec = 0; tv.tv_usec = 0;
209 rt = select(fd+1, &r, &w, &e, &tv);
210 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
216 #endif /* __UNUSED__ */
218 int UnixOpen(const char *path)
221 struct sockaddr_un ad;
222 memset(&ad, 0, sizeof(ad));
223 ad.sun_family = AF_UNIX;
224 strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
226 sock = socket( AF_UNIX, SOCK_STREAM, 0 );
232 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
235 fm_close(sock); /* don't use SockClose, no traffic yet */
244 int SockOpen(const char *host, const char *service, const char *options,
247 struct addrinfo *ai, *ai0, req;
250 void *request = NULL;
252 #endif /* NET_SECURITY */
254 #ifdef HAVE_SOCKETPAIR
256 return handle_plugin(host,service,plugin);
257 #endif /* HAVE_SOCKETPAIR */
258 memset(&req, 0, sizeof(struct addrinfo));
259 req.ai_socktype = SOCK_STREAM;
261 if (getaddrinfo(host, service, &req, &ai0)) {
262 report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
270 if (net_security_strtorequest((char *)options, &request, &requestlen))
273 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
278 #else /* NET_SECURITY */
279 #ifdef HAVE_INNER_CONNECT
280 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
285 for (ai = ai0; ai; ai = ai->ai_next) {
286 i = socket(ai->ai_family, ai->ai_socktype, 0);
289 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
297 #endif /* NET_SECURITY */
303 #else /* INET6_ENABLE */
304 #ifndef HAVE_INET_ATON
306 #ifdef INADDR_BROADCAST
307 #define INADDR_NONE INADDR_BROADCAST
309 #define INADDR_NONE -1
312 #endif /* HAVE_INET_ATON */
314 int SockOpen(const char *host, int clientPort, const char *options,
317 int sock = -1; /* pacify -Wall */
318 #ifndef HAVE_INET_ATON
319 unsigned long inaddr;
320 #endif /* HAVE_INET_ATON */
321 struct sockaddr_in ad, **pptr;
324 #ifdef HAVE_SOCKETPAIR
327 sprintf(buf,"%d",clientPort);
328 return handle_plugin(host,buf,plugin);
330 #endif /* HAVE_SOCKETPAIR */
332 memset(&ad, 0, sizeof(ad));
333 ad.sin_family = AF_INET;
335 /* we'll accept a quad address */
336 #ifndef HAVE_INET_ATON
337 inaddr = inet_addr(host);
338 if (inaddr != INADDR_NONE)
340 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
342 if (inet_aton(host, &ad.sin_addr))
344 #endif /* HAVE_INET_ATON */
345 ad.sin_port = htons(clientPort);
347 sock = socket(AF_INET, SOCK_STREAM, 0);
353 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
356 fm_close(sock); /* don't use SockClose, no traffic yet */
361 #ifndef HAVE_INET_ATON
365 #endif /* HAVE_INET_ATON */
367 hp = gethostbyname(host);
375 * Add a check to make sure the address has a valid IPv4 or IPv6
376 * length. This prevents buffer spamming by a broken DNS.
378 if(hp->h_length != 4 && hp->h_length != 8)
382 _("fetchmail: illegal address length received for host %s\n"),host);
386 * Try all addresses of a possibly multihomed host until we get
387 * a successful connect or until we run out of addresses.
389 pptr = (struct sockaddr_in **)hp->h_addr_list;
390 for(; *pptr != NULL; pptr++)
392 sock = socket(AF_INET, SOCK_STREAM, 0);
398 ad.sin_port = htons(clientPort);
399 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
400 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
402 fm_close(sock); /* don't use SockClose, no traffic yet */
403 memset(&ad, 0, sizeof(ad));
404 ad.sin_family = AF_INET;
409 fm_close(sock); /* don't use SockClose, no traffic yet */
418 #endif /* INET6_ENABLE */
421 #if defined(HAVE_STDARG_H)
422 int SockPrintf(int sock, const char* format, ...)
425 int SockPrintf(sock,format,va_alist)
434 #if defined(HAVE_STDARG_H)
435 va_start(ap, format) ;
439 #ifdef HAVE_VSNPRINTF
440 vsnprintf(buf, sizeof(buf), format, ap);
442 vsprintf(buf, format, ap);
445 return SockWrite(sock, buf, strlen(buf));
450 #include "openssl/ssl.h"
451 #include "openssl/err.h"
452 #include "openssl/pem.h"
453 #include "openssl/x509.h"
455 static SSL_CTX *_ctx = NULL;
456 static SSL *_ssl_context[FD_SETSIZE];
458 SSL *SSLGetContext( int );
459 #endif /* SSL_ENABLE */
461 int SockWrite(int sock, char *buf, int len)
471 if( NULL != ( ssl = SSLGetContext( sock ) ) )
472 n = SSL_write(ssl, buf, len);
474 n = fm_write(sock, buf, len);
476 n = fm_write(sock, buf, len);
487 int SockRead(int sock, char *buf, int len)
489 char *newline, *bp = buf;
507 * The reason for these gymnastics is that we want two things:
508 * (1) to read \n-terminated lines,
509 * (2) to return the true length of data read, even if the
510 * data coming in has embedded NULS.
513 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
515 /* OK... SSL_peek works a little different from MSG_PEEK
516 Problem is that SSL_peek can return 0 if there
517 is no data currently available. If, on the other
518 hand, we loose the socket, we also get a zero, but
519 the SSL_read then SEGFAULTS! To deal with this,
520 we'll check the error code any time we get a return
521 of zero from SSL_peek. If we have an error, we bail.
522 If we don't, we read one character in SSL_read and
523 loop. This should continue to work even if they
524 later change the behavior of SSL_peek
525 to "fix" this problem... :-( */
526 if ((n = SSL_peek(ssl, bp, len)) < 0) {
530 /* SSL_peek says no data... Does he mean no data
531 or did the connection blow up? If we got an error
533 if( 0 != ( n = ERR_get_error() ) ) {
536 /* We didn't get an error so read at least one
537 character at this point and loop */
539 /* Make sure newline start out NULL!
540 * We don't have a string to pass through
541 * the strchr at this point yet */
543 } else if ((newline = memchr(bp, '\n', n)) != NULL)
544 n = newline - bp + 1;
545 if ((n = SSL_read(ssl, bp, n)) == -1) {
548 /* Check for case where our single character turned out to
549 * be a newline... (It wasn't going to get caught by
550 * the strchr above if it came from the hack... ). */
551 if( NULL == newline && 1 == n && '\n' == *bp ) {
552 /* Got our newline - this will break
553 out of the loop now */
557 if ((n = fm_peek(sock, bp, len)) <= 0)
559 if ((newline = memchr(bp, '\n', n)) != NULL)
560 n = newline - bp + 1;
561 if ((n = fm_read(sock, bp, n)) == -1)
567 if ((n = fm_read(sock, bp, 1)) <= 0)
569 if ((n = fm_peek(sock, bp, len)) <= 0)
572 if ((newline = memchr(bp, '\n', n)) != NULL)
573 n = newline - bp + 1;
575 if ((n = fm_read(sock, bp, n)) == -1)
577 #endif /* __BEOS__ */
587 int SockPeek(int sock)
588 /* peek at the next socket character without actually reading it */
597 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
598 n = SSL_peek(ssl, &ch, 1);
600 /* This code really needs to implement a "hold back"
601 * to simulate a functioning SSL_peek()... sigh...
602 * Has to be coordinated with the read code above.
603 * Next on the list todo... */
605 /* SSL_peek says no data... Does he mean no data
606 or did the connection blow up? If we got an error
608 if( 0 != ( n = ERR_get_error() ) ) {
612 /* Haven't seen this case actually occur, but...
613 if the problem in SockRead can occur, this should
614 be possible... Just not sure what to do here.
615 This should be a safe "punt" the "peek" but don't
616 "punt" the "session"... */
618 return 0; /* Give him a '\0' character */
621 n = fm_peek(sock, &ch, 1);
625 n = fm_peek(sock, &ch, 1);
627 #endif /* SSL_ENABLE */
639 static char *_ssl_server_cname = NULL;
641 SSL *SSLGetContext( int sock )
643 /* If SSLOpen has never initialized - just return NULL */
647 if( sock < 0 || sock > FD_SETSIZE )
649 return _ssl_context[sock];
653 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
662 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
663 err = X509_STORE_CTX_get_error(ctx);
664 depth = X509_STORE_CTX_get_error_depth(ctx);
666 X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
667 X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
669 /* Just to be sure those buffers are terminated... I think the
670 X509 libraries do, but... */
671 buf[256] = ibuf[256] = '\0';
674 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
676 strcpy( cbuf, str_ptr );
677 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
680 if (outlevel == O_VERBOSE)
681 report(stdout, _("Issuer Organization: %s\n"), cbuf );
683 if (outlevel == O_VERBOSE)
684 report(stdout, _("Unknown Organization\n"), cbuf );
686 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
688 strcpy( cbuf, str_ptr );
689 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
692 if (outlevel == O_VERBOSE)
693 report(stdout, _("Issuer CommonName: %s\n"), cbuf );
695 if (outlevel == O_VERBOSE)
696 report(stdout, _("Unknown Issuer CommonName\n"), cbuf );
698 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
700 strcpy( cbuf, str_ptr );
701 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
704 if (outlevel == O_VERBOSE)
705 report(stdout, _("Server CommonName: %s\n"), cbuf);
707 if (_ssl_server_cname != NULL)
710 char *p2 = _ssl_server_cname;
716 n = strlen(p2) - strlen(p1);
720 if ( 0 != strcasecmp( p1, p2 ) )
722 "Server CommonName mismatch: %s != %s\n",
723 cbuf, _ssl_server_cname );
726 if (outlevel == O_VERBOSE)
727 report(stdout, _("Unknown Server CommonName\n"), cbuf );
731 switch (ctx->error) {
732 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
733 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
734 report(stdout, _("unknown issuer= %s"), buf);
736 case X509_V_ERR_CERT_NOT_YET_VALID:
737 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
738 report(stderr, _("Server Certificate not yet valid"));
740 case X509_V_ERR_CERT_HAS_EXPIRED:
741 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
742 report(stderr, _("Server Certificate expired"));
745 /* We are not requiring or validating server or issuer id's as yet */
746 /* Always return OK from here */
752 /* performs initial SSL handshake over the connected socket
753 * uses SSL *ssl global variable, which is currently defined
756 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
758 SSL_load_error_strings();
759 SSLeay_add_ssl_algorithms();
761 if( sock < 0 || sock > FD_SETSIZE ) {
762 report(stderr, _("File descriptor out of range for SSL") );
767 /* Be picky and make sure the memory is cleared */
768 memset( _ssl_context, 0, sizeof( _ssl_context ) );
769 _ctx = SSL_CTX_new(SSLv23_client_method());
771 ERR_print_errors_fp(stderr);
776 _ssl_context[sock] = SSL_new(_ctx);
778 if(_ssl_context[sock] == NULL) {
779 ERR_print_errors_fp(stderr);
783 /* This static is for the verify callback */
784 _ssl_server_cname = servercname;
786 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
788 if( mycert || mykey ) {
790 /* Ok... He has a certificate file defined, so lets declare it. If
791 * he does NOT have a separate certificate and private key file then
792 * assume that it's a combined key and certificate file.
798 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
799 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
802 SSL_set_fd(_ssl_context[sock], sock);
804 if(SSL_connect(_ssl_context[sock]) == -1) {
805 ERR_print_errors_fp(stderr);
813 int SockClose(int sock)
814 /* close a socket gracefully */
819 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
820 /* Clean up the SSL stack */
821 SSL_free( _ssl_context[sock] );
822 _ssl_context[sock] = NULL;
828 * This hangs in RedHat 6.2 after fetchmail runs for a while a
829 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
830 * the recv system call. (Reported from jtnews
831 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
833 * Half-close the connection first so the other end gets notified.
835 * This stops sends but allows receives (effectively, it sends a
837 if (shutdown(sock, 1) == 0) {
839 /* If there is any data still waiting in the queue, discard it.
840 * Call recv() until either it returns 0 (meaning we received a FIN)
841 * or any error occurs. This makes sure all data sent by the other
842 * side is acknowledged at the TCP level.
844 if (fm_peek(sock, &ch, 1) > 0)
845 while (fm_read(sock, &ch, 1) > 0)
848 #endif /* __UNUSED__ */
850 /* if there's an error closing at this point, not much we can do */
851 return(fm_close(sock)); /* this is guarded */
856 * Use the chargen service to test input buffering directly.
857 * You may have to uncomment the `chargen' service description in your
858 * inetd.conf (and then SIGHUP inetd) for this to work. */
861 int sock = SockOpen("localhost", 19, NULL);
864 while (SockRead(sock, buf, sizeof(buf)-1))
865 SockWrite(1, buf, strlen(buf));
870 /* socket.c ends here */