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>
21 #include <netinet/in.h>
22 #ifdef HAVE_ARPA_INET_H
23 #include <arpa/inet.h>
26 #if defined(STDC_HEADERS)
29 #if defined(HAVE_UNISTD_H)
32 #if defined(HAVE_STDARG_H)
38 #include "fetchmail.h"
41 /* Defines to allow BeOS to play nice... */
44 #define fm_close(a) closesocket(a)
45 #define fm_write(a,b,c) send(a,b,c,0)
46 #define fm_peek(a,b,c) recv(a,b,c,0)
47 #define fm_read(a,b,c) recv(a,b,c,0)
49 #define fm_close(a) close(a)
50 #define fm_write(a,b,c) write(a,b,c)
51 #define fm_peek(a,b,c) recv(a,b,c, MSG_PEEK)
52 #define fm_read(a,b,c) read(a,b,c)
55 /* We need to define h_errno only if it is not already */
58 #ifdef HAVE_RES_SEARCH
59 /* some versions of FreeBSD should declare this but don't */
62 /* pretend we have h_errno to avoid some #ifdef's later */
66 #endif /* ndef h_errno */
69 #include <net/security.h>
70 #endif /* NET_SECURITY */
72 #ifdef HAVE_SOCKETPAIR
73 const char **parse_plugin(const char *plugin, const char *host, const char *service)
74 { const char **argvec;
75 char *c, *p, *plugin_copy;
76 unsigned int s = 2 * sizeof(char*), i;
78 plugin_copy = strdup(plugin);
81 report(stderr, _("fetchmail: malloc failed\n"));
84 for (c = p = plugin_copy; *c; c++)
85 { if (isspace(*c) && !isspace(*p))
92 report(stderr, _("fetchmail: malloc failed\n"));
96 for (c = p = plugin_copy, i = 0; *c; c++)
97 { if ((!isspace(*c)) && (c == p ? 1 : isspace(*p))) {
103 for (c = plugin_copy; *c; c++)
107 for (i = 0; argvec[i]; i++)
108 { if (strcmp(argvec[i], "%h") == 0)
110 if (strcmp(argvec[i], "%p") == 0)
116 static int handle_plugin(const char *host,
117 const char *service, const char *plugin)
118 /* get a socket mediated through a given external command */
122 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
124 report(stderr, _("fetchmail: socketpair failed\n"));
130 report(stderr, _("fetchmail: fork failed\n"));
134 /* fds[1] is the parent's end; close it for proper EOF
136 (void) close(fds[1]);
137 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
138 report(stderr, _("dup2 failed\n"));
141 /* fds[0] is now connected to 0 and 1; close it */
142 (void) close(fds[0]);
143 if (outlevel >= O_VERBOSE)
144 report(stderr, _("running %s %s %s\n"), plugin, host, service);
145 argvec = parse_plugin(plugin,host,service);
146 execvp(*argvec, argvec);
147 report(stderr, _("execvp(%s) failed\n"), *argvec);
150 default: /* parent */
154 /* fds[0] is the child's end; close it for proper EOF detection */
155 (void) close(fds[0]);
158 #endif /* HAVE_SOCKETPAIR */
161 #include <sys/time.h>
163 int SockCheckOpen(int fd)
164 /* poll given socket; is it selectable? */
172 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
175 tv.tv_sec = 0; tv.tv_usec = 0;
176 rt = select(fd+1, &r, &w, &e, &tv);
177 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
183 #endif /* __UNUSED__ */
186 int SockOpen(const char *host, const char *service, const char *options,
189 struct addrinfo *ai, *ai0, req;
192 void *request = NULL;
194 #endif /* NET_SECURITY */
196 #ifdef HAVE_SOCKETPAIR
198 return handle_plugin(host,service,plugin);
199 #endif /* HAVE_SOCKETPAIR */
200 memset(&req, 0, sizeof(struct addrinfo));
201 req.ai_socktype = SOCK_STREAM;
203 if (getaddrinfo(host, service, &req, &ai0)) {
204 report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
212 if (net_security_strtorequest((char *)options, &request, &requestlen))
215 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
220 #else /* NET_SECURITY */
221 #ifdef HAVE_INNER_CONNECT
222 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
227 for (ai = ai0; ai; ai = ai->ai_next) {
228 i = socket(ai->ai_family, ai->ai_socktype, 0);
231 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
239 #endif /* NET_SECURITY */
245 #else /* INET6_ENABLE */
246 #ifndef HAVE_INET_ATON
248 #ifdef INADDR_BROADCAST
249 #define INADDR_NONE INADDR_BROADCAST
251 #define INADDR_NONE -1
254 #endif /* HAVE_INET_ATON */
256 int SockOpen(const char *host, int clientPort, const char *options,
259 int sock = -1; /* pacify -Wall */
260 #ifndef HAVE_INET_ATON
261 unsigned long inaddr;
262 #endif /* HAVE_INET_ATON */
263 struct sockaddr_in ad, **pptr;
266 #ifdef HAVE_SOCKETPAIR
269 sprintf(buf,"%d",clientPort);
270 return handle_plugin(host,buf,plugin);
272 #endif /* HAVE_SOCKETPAIR */
274 memset(&ad, 0, sizeof(ad));
275 ad.sin_family = AF_INET;
277 /* we'll accept a quad address */
278 #ifndef HAVE_INET_ATON
279 inaddr = inet_addr(host);
280 if (inaddr != INADDR_NONE)
282 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
284 if (inet_aton(host, &ad.sin_addr))
286 #endif /* HAVE_INET_ATON */
287 ad.sin_port = htons(clientPort);
289 sock = socket(AF_INET, SOCK_STREAM, 0);
295 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
298 fm_close(sock); /* don't use SockClose, no traffic yet */
303 #ifndef HAVE_INET_ATON
307 #endif /* HAVE_INET_ATON */
309 hp = gethostbyname(host);
317 * Add a check to make sure the address has a valid IPv4 or IPv6
318 * length. This prevents buffer spamming by a broken DNS.
320 if(hp->h_length != 4 && hp->h_length != 8)
324 _("fetchmail: illegal address length received for host %s\n"),host);
328 * Try all addresses of a possibly multihomed host until we get
329 * a successful connect or until we run out of addresses.
331 pptr = (struct sockaddr_in **)hp->h_addr_list;
332 for(; *pptr != NULL; pptr++)
334 sock = socket(AF_INET, SOCK_STREAM, 0);
340 ad.sin_port = htons(clientPort);
341 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
342 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
344 fm_close(sock); /* don't use SockClose, no traffic yet */
345 memset(&ad, 0, sizeof(ad));
346 ad.sin_family = AF_INET;
351 fm_close(sock); /* don't use SockClose, no traffic yet */
360 #endif /* INET6_ENABLE */
363 #if defined(HAVE_STDARG_H)
364 int SockPrintf(int sock, const char* format, ...)
367 int SockPrintf(sock,format,va_alist)
376 #if defined(HAVE_STDARG_H)
377 va_start(ap, format) ;
381 #ifdef HAVE_VSNPRINTF
382 vsnprintf(buf, sizeof(buf), format, ap);
384 vsprintf(buf, format, ap);
387 return SockWrite(sock, buf, strlen(buf));
392 #include "openssl/ssl.h"
393 #include "openssl/err.h"
394 #include "openssl/pem.h"
395 #include "openssl/x509.h"
397 static SSL_CTX *_ctx = NULL;
398 static SSL *_ssl_context[FD_SETSIZE];
400 SSL *SSLGetContext( int );
401 #endif /* SSL_ENABLE */
403 int SockWrite(int sock, char *buf, int len)
413 if( NULL != ( ssl = SSLGetContext( sock ) ) )
414 n = SSL_write(ssl, buf, len);
416 n = fm_write(sock, buf, len);
418 n = fm_write(sock, buf, len);
429 int SockRead(int sock, char *buf, int len)
431 char *newline, *bp = buf;
449 * The reason for these gymnastics is that we want two things:
450 * (1) to read \n-terminated lines,
451 * (2) to return the true length of data read, even if the
452 * data coming in has embedded NULS.
455 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
457 /* OK... SSL_peek works a little different from MSG_PEEK
458 Problem is that SSL_peek can return 0 if there
459 is no data currently available. If, on the other
460 hand, we loose the socket, we also get a zero, but
461 the SSL_read then SEGFAULTS! To deal with this,
462 we'll check the error code any time we get a return
463 of zero from SSL_peek. If we have an error, we bail.
464 If we don't, we read one character in SSL_read and
465 loop. This should continue to work even if they
466 later change the behavior of SSL_peek
467 to "fix" this problem... :-( */
468 if ((n = SSL_peek(ssl, bp, len)) < 0) {
472 /* SSL_peek says no data... Does he mean no data
473 or did the connection blow up? If we got an error
475 if( 0 != ( n = ERR_get_error() ) ) {
478 /* We didn't get an error so read at least one
479 character at this point and loop */
481 /* Make sure newline start out NULL!
482 * We don't have a string to pass through
483 * the strchr at this point yet */
485 } else if ((newline = memchr(bp, '\n', n)) != NULL)
486 n = newline - bp + 1;
487 if ((n = SSL_read(ssl, bp, n)) == -1) {
490 /* Check for case where our single character turned out to
491 * be a newline... (It wasn't going to get caught by
492 * the strchr above if it came from the hack... ). */
493 if( NULL == newline && 1 == n && '\n' == *bp ) {
494 /* Got our newline - this will break
495 out of the loop now */
499 if ((n = fm_peek(sock, bp, len)) <= 0)
501 if ((newline = memchr(bp, '\n', n)) != NULL)
502 n = newline - bp + 1;
503 if ((n = fm_read(sock, bp, n)) == -1)
509 if ((n = fm_read(sock, bp, 1)) <= 0)
511 if ((n = fm_peek(sock, bp, len)) <= 0)
514 if ((newline = memchr(bp, '\n', n)) != NULL)
515 n = newline - bp + 1;
517 if ((n = fm_read(sock, bp, n)) == -1)
519 #endif /* __BEOS__ */
529 int SockPeek(int sock)
530 /* peek at the next socket character without actually reading it */
539 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
540 n = SSL_peek(ssl, &ch, 1);
542 /* This code really needs to implement a "hold back"
543 * to simulate a functioning SSL_peek()... sigh...
544 * Has to be coordinated with the read code above.
545 * Next on the list todo... */
547 /* SSL_peek says no data... Does he mean no data
548 or did the connection blow up? If we got an error
550 if( 0 != ( n = ERR_get_error() ) ) {
554 /* Haven't seen this case actually occur, but...
555 if the problem in SockRead can occur, this should
556 be possible... Just not sure what to do here.
557 This should be a safe "punt" the "peek" but don't
558 "punt" the "session"... */
560 return 0; /* Give him a '\0' character */
563 n = fm_peek(sock, &ch, 1);
567 n = fm_peek(sock, &ch, 1);
569 #endif /* SSL_ENABLE */
581 static char *_ssl_server_cname = NULL;
583 SSL *SSLGetContext( int sock )
585 /* If SSLOpen has never initialized - just return NULL */
589 if( sock < 0 || sock > FD_SETSIZE )
591 return _ssl_context[sock];
595 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
604 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
605 err = X509_STORE_CTX_get_error(ctx);
606 depth = X509_STORE_CTX_get_error_depth(ctx);
608 X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
609 X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
611 /* Just to be sure those buffers are terminated... I think the
612 X509 libraries do, but... */
613 buf[256] = ibuf[256] = '\0';
616 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
618 strcpy( cbuf, str_ptr );
619 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
622 if (outlevel == O_VERBOSE)
623 report(stdout, "Issuer Organization: %s\n", cbuf );
625 if (outlevel == O_VERBOSE)
626 report(stdout, "Unknown Organization\n", cbuf );
628 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
630 strcpy( cbuf, str_ptr );
631 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
634 if (outlevel == O_VERBOSE)
635 report(stdout, "Issuer CommonName: %s\n", cbuf );
637 if (outlevel == O_VERBOSE)
638 report(stdout, "Unknown Issuer CommonName\n", cbuf );
640 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
642 strcpy( cbuf, str_ptr );
643 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
646 if (outlevel == O_VERBOSE)
647 report(stdout, "Server CommonName: %s\n", cbuf );
648 /* Should we have some wildcarding here? */
649 if ( NULL != _ssl_server_cname
650 && 0 != strcasecmp( cbuf, _ssl_server_cname ) ) {
652 "Server CommonName mismatch: %s != %s\n",
653 cbuf, _ssl_server_cname );
656 if (outlevel == O_VERBOSE)
657 report(stdout, "Unknown Server CommonName\n", cbuf );
661 switch (ctx->error) {
662 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
663 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
664 report(stdout, "unknown issuer= %s", buf);
666 case X509_V_ERR_CERT_NOT_YET_VALID:
667 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
668 report(stderr, "Server Certificate not yet valid");
670 case X509_V_ERR_CERT_HAS_EXPIRED:
671 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
672 report(stderr, "Server Certificate expired");
675 /* We are not requiring or validating server or issuer id's as yet */
676 /* Always return OK from here */
682 /* performs initial SSL handshake over the connected socket
683 * uses SSL *ssl global variable, which is currently defined
686 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
688 SSL_load_error_strings();
689 SSLeay_add_ssl_algorithms();
691 if( sock < 0 || sock > FD_SETSIZE ) {
692 report(stderr, "File descriptor out of range for SSL" );
697 /* Be picky and make sure the memory is cleared */
698 memset( _ssl_context, 0, sizeof( _ssl_context ) );
699 _ctx = SSL_CTX_new(SSLv23_client_method());
701 ERR_print_errors_fp(stderr);
706 _ssl_context[sock] = SSL_new(_ctx);
708 if(_ssl_context[sock] == NULL) {
709 ERR_print_errors_fp(stderr);
713 /* This static is for the verify callback */
714 _ssl_server_cname = servercname;
716 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
718 if( mycert || mykey ) {
720 /* Ok... He has a certificate file defined, so lets declare it. If
721 * he does NOT have a separate certificate and private key file then
722 * assume that it's a combined key and certificate file.
728 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
729 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
732 SSL_set_fd(_ssl_context[sock], sock);
734 if(SSL_connect(_ssl_context[sock]) == -1) {
735 ERR_print_errors_fp(stderr);
743 int SockClose(int sock)
744 /* close a socket gracefully */
749 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
750 /* Clean up the SSL stack */
751 SSL_free( _ssl_context[sock] );
752 _ssl_context[sock] = NULL;
758 * This hangs in RedHat 6.2 after fetchmail runs for a while a
759 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
760 * the recv system call. (Reported from jtnews
761 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
763 * Half-close the connection first so the other end gets notified.
765 * This stops sends but allows receives (effectively, it sends a
767 if (shutdown(sock, 1) == 0) {
769 /* If there is any data still waiting in the queue, discard it.
770 * Call recv() until either it returns 0 (meaning we received a FIN)
771 * or any error occurs. This makes sure all data sent by the other
772 * side is acknowledged at the TCP level.
774 if (fm_peek(sock, &ch, 1) > 0)
775 while (fm_read(sock, &ch, 1) > 0)
778 #endif /* __UNUSED__ */
780 /* if there's an error closing at this point, not much we can do */
781 return(fm_close(sock)); /* this is guarded */
786 * Use the chargen service to test input buffering directly.
787 * You may have to uncomment the `chargen' service description in your
788 * inetd.conf (and then SIGHUP inetd) for this to work. */
791 int sock = SockOpen("localhost", 19, NULL);
794 while (SockRead(sock, buf, sizeof(buf)-1))
795 SockWrite(1, buf, strlen(buf));
800 /* socket.c ends here */