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, _("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, _("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, _("fetchmail: socketpair failed\n"));
164 report(stderr, _("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, _("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, _("running %s (host %s service %s)\n"), plugin, host, service);
179 argvec = parse_plugin(plugin,host,service);
180 execvp(*argvec, argvec);
181 report(stderr, _("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, _("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
328 sprintf(buf,"%d",clientPort);
329 return handle_plugin(host,buf,plugin);
331 #endif /* HAVE_SOCKETPAIR */
333 memset(&ad, 0, sizeof(ad));
334 ad.sin_family = AF_INET;
336 /* we'll accept a quad address */
337 #ifndef HAVE_INET_ATON
338 inaddr = inet_addr(host);
339 if (inaddr != INADDR_NONE)
341 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
343 if (inet_aton(host, &ad.sin_addr))
345 #endif /* HAVE_INET_ATON */
346 ad.sin_port = htons(clientPort);
348 sock = socket(AF_INET, SOCK_STREAM, 0);
354 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
357 fm_close(sock); /* don't use SockClose, no traffic yet */
362 #ifndef HAVE_INET_ATON
366 #endif /* HAVE_INET_ATON */
368 hp = gethostbyname(host);
376 * Add a check to make sure the address has a valid IPv4 or IPv6
377 * length. This prevents buffer spamming by a broken DNS.
379 if(hp->h_length != 4 && hp->h_length != 8)
383 _("fetchmail: illegal address length received for host %s\n"),host);
387 * Try all addresses of a possibly multihomed host until we get
388 * a successful connect or until we run out of addresses.
390 pptr = (struct sockaddr_in **)hp->h_addr_list;
391 for(; *pptr != NULL; pptr++)
393 sock = socket(AF_INET, SOCK_STREAM, 0);
399 ad.sin_port = htons(clientPort);
400 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
401 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
403 fm_close(sock); /* don't use SockClose, no traffic yet */
404 memset(&ad, 0, sizeof(ad));
405 ad.sin_family = AF_INET;
410 fm_close(sock); /* don't use SockClose, no traffic yet */
419 #endif /* INET6_ENABLE */
422 #if defined(HAVE_STDARG_H)
423 int SockPrintf(int sock, const char* format, ...)
426 int SockPrintf(sock,format,va_alist)
435 #if defined(HAVE_STDARG_H)
436 va_start(ap, format) ;
440 #ifdef HAVE_VSNPRINTF
441 vsnprintf(buf, sizeof(buf), format, ap);
443 vsprintf(buf, format, ap);
446 return SockWrite(sock, buf, strlen(buf));
451 #include "openssl/ssl.h"
452 #include "openssl/err.h"
453 #include "openssl/pem.h"
454 #include "openssl/x509.h"
456 static SSL_CTX *_ctx = NULL;
457 static SSL *_ssl_context[FD_SETSIZE];
459 SSL *SSLGetContext( int );
460 #endif /* SSL_ENABLE */
462 int SockWrite(int sock, char *buf, int len)
472 if( NULL != ( ssl = SSLGetContext( sock ) ) )
473 n = SSL_write(ssl, buf, len);
475 n = fm_write(sock, buf, len);
477 n = fm_write(sock, buf, len);
488 int SockRead(int sock, char *buf, int len)
490 char *newline, *bp = buf;
508 * The reason for these gymnastics is that we want two things:
509 * (1) to read \n-terminated lines,
510 * (2) to return the true length of data read, even if the
511 * data coming in has embedded NULS.
514 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
516 /* OK... SSL_peek works a little different from MSG_PEEK
517 Problem is that SSL_peek can return 0 if there
518 is no data currently available. If, on the other
519 hand, we loose the socket, we also get a zero, but
520 the SSL_read then SEGFAULTS! To deal with this,
521 we'll check the error code any time we get a return
522 of zero from SSL_peek. If we have an error, we bail.
523 If we don't, we read one character in SSL_read and
524 loop. This should continue to work even if they
525 later change the behavior of SSL_peek
526 to "fix" this problem... :-( */
527 if ((n = SSL_peek(ssl, bp, len)) < 0) {
531 /* SSL_peek says no data... Does he mean no data
532 or did the connection blow up? If we got an error
534 if( 0 != ( n = ERR_get_error() ) ) {
537 /* We didn't get an error so read at least one
538 character at this point and loop */
540 /* Make sure newline start out NULL!
541 * We don't have a string to pass through
542 * the strchr at this point yet */
544 } else if ((newline = memchr(bp, '\n', n)) != NULL)
545 n = newline - bp + 1;
546 if ((n = SSL_read(ssl, bp, n)) == -1) {
549 /* Check for case where our single character turned out to
550 * be a newline... (It wasn't going to get caught by
551 * the strchr above if it came from the hack... ). */
552 if( NULL == newline && 1 == n && '\n' == *bp ) {
553 /* Got our newline - this will break
554 out of the loop now */
558 if ((n = fm_peek(sock, bp, len)) <= 0)
560 if ((newline = memchr(bp, '\n', n)) != NULL)
561 n = newline - bp + 1;
562 if ((n = fm_read(sock, bp, n)) == -1)
568 if ((n = fm_read(sock, bp, 1)) <= 0)
570 if ((n = fm_peek(sock, bp, len)) <= 0)
573 if ((newline = memchr(bp, '\n', n)) != NULL)
574 n = newline - bp + 1;
576 if ((n = fm_read(sock, bp, n)) == -1)
578 #endif /* __BEOS__ */
588 int SockPeek(int sock)
589 /* peek at the next socket character without actually reading it */
598 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
599 n = SSL_peek(ssl, &ch, 1);
601 /* This code really needs to implement a "hold back"
602 * to simulate a functioning SSL_peek()... sigh...
603 * Has to be coordinated with the read code above.
604 * Next on the list todo... */
606 /* SSL_peek says no data... Does he mean no data
607 or did the connection blow up? If we got an error
609 if( 0 != ( n = ERR_get_error() ) ) {
613 /* Haven't seen this case actually occur, but...
614 if the problem in SockRead can occur, this should
615 be possible... Just not sure what to do here.
616 This should be a safe "punt" the "peek" but don't
617 "punt" the "session"... */
619 return 0; /* Give him a '\0' character */
622 n = fm_peek(sock, &ch, 1);
626 n = fm_peek(sock, &ch, 1);
628 #endif /* SSL_ENABLE */
640 static char *_ssl_server_cname = NULL;
642 SSL *SSLGetContext( int sock )
644 /* If SSLOpen has never initialized - just return NULL */
648 if( sock < 0 || sock > FD_SETSIZE )
650 return _ssl_context[sock];
654 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
663 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
664 err = X509_STORE_CTX_get_error(ctx);
665 depth = X509_STORE_CTX_get_error_depth(ctx);
667 X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
668 X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
670 /* Just to be sure those buffers are terminated... I think the
671 X509 libraries do, but... */
672 buf[256] = ibuf[256] = '\0';
675 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
677 strcpy( cbuf, str_ptr );
678 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
681 if (outlevel == O_VERBOSE)
682 report(stdout, _("Issuer Organization: %s\n"), cbuf );
684 if (outlevel == O_VERBOSE)
685 report(stdout, _("Unknown Organization\n"));
687 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
689 strcpy( cbuf, str_ptr );
690 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
693 if (outlevel == O_VERBOSE)
694 report(stdout, _("Issuer CommonName: %s\n"), cbuf );
696 if (outlevel == O_VERBOSE)
697 report(stdout, _("Unknown Issuer CommonName\n"));
699 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
701 strcpy( cbuf, str_ptr );
702 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
705 if (outlevel == O_VERBOSE)
706 report(stdout, _("Server CommonName: %s\n"), cbuf);
708 if (_ssl_server_cname != NULL)
711 char *p2 = _ssl_server_cname;
717 n = strlen(p2) - strlen(p1);
721 if ( 0 != strcasecmp( p1, p2 ) )
723 "Server CommonName mismatch: %s != %s\n",
724 cbuf, _ssl_server_cname );
727 if (outlevel == O_VERBOSE)
728 report(stdout, _("Unknown Server CommonName\n"));
732 switch (ctx->error) {
733 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
734 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
735 report(stdout, _("unknown issuer= %s"), buf);
737 case X509_V_ERR_CERT_NOT_YET_VALID:
738 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
739 report(stderr, _("Server Certificate not yet valid"));
741 case X509_V_ERR_CERT_HAS_EXPIRED:
742 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
743 report(stderr, _("Server Certificate expired"));
746 /* We are not requiring or validating server or issuer id's as yet */
747 /* Always return OK from here */
753 /* performs initial SSL handshake over the connected socket
754 * uses SSL *ssl global variable, which is currently defined
757 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, char *servercname )
759 SSL_load_error_strings();
760 SSLeay_add_ssl_algorithms();
762 if( sock < 0 || sock > FD_SETSIZE ) {
763 report(stderr, _("File descriptor out of range for SSL") );
768 /* Be picky and make sure the memory is cleared */
769 memset( _ssl_context, 0, sizeof( _ssl_context ) );
771 if(!strcmp("ssl2",myproto)) {
772 _ctx = SSL_CTX_new(SSLv2_client_method());
773 } else if(!strcmp("ssl3",myproto)) {
774 _ctx = SSL_CTX_new(SSLv3_client_method());
775 } else if(!strcmp("tls1",myproto)) {
776 _ctx = SSL_CTX_new(TLSv1_client_method());
778 fprintf(stderr,_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
783 _ctx = SSL_CTX_new(SSLv23_client_method());
786 ERR_print_errors_fp(stderr);
791 _ssl_context[sock] = SSL_new(_ctx);
793 if(_ssl_context[sock] == NULL) {
794 ERR_print_errors_fp(stderr);
798 /* This static is for the verify callback */
799 _ssl_server_cname = servercname;
801 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
803 if( mycert || mykey ) {
805 /* Ok... He has a certificate file defined, so lets declare it. If
806 * he does NOT have a separate certificate and private key file then
807 * assume that it's a combined key and certificate file.
813 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
814 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
817 SSL_set_fd(_ssl_context[sock], sock);
819 if(SSL_connect(_ssl_context[sock]) == -1) {
820 ERR_print_errors_fp(stderr);
828 int SockClose(int sock)
829 /* close a socket gracefully */
834 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
835 /* Clean up the SSL stack */
836 SSL_free( _ssl_context[sock] );
837 _ssl_context[sock] = NULL;
843 * This hangs in RedHat 6.2 after fetchmail runs for a while a
844 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
845 * the recv system call. (Reported from jtnews
846 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
848 * Half-close the connection first so the other end gets notified.
850 * This stops sends but allows receives (effectively, it sends a
852 if (shutdown(sock, 1) == 0) {
854 /* If there is any data still waiting in the queue, discard it.
855 * Call recv() until either it returns 0 (meaning we received a FIN)
856 * or any error occurs. This makes sure all data sent by the other
857 * side is acknowledged at the TCP level.
859 if (fm_peek(sock, &ch, 1) > 0)
860 while (fm_read(sock, &ch, 1) > 0)
863 #endif /* __UNUSED__ */
865 /* if there's an error closing at this point, not much we can do */
866 return(fm_close(sock)); /* this is guarded */
871 * Use the chargen service to test input buffering directly.
872 * You may have to uncomment the `chargen' service description in your
873 * inetd.conf (and then SIGHUP inetd) for this to work. */
876 int sock = SockOpen("localhost", 19, NULL);
879 while (SockRead(sock, buf, sizeof(buf)-1))
880 SockWrite(1, buf, strlen(buf));
885 /* socket.c ends here */