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 const char **parse_plugin(const char *plugin, const char *host, const char *service)
75 { const char **argvec;
76 char *c, *p, *plugin_copy;
77 unsigned int s = 2 * sizeof(char*), i;
79 plugin_copy = strdup(plugin);
82 report(stderr, _("fetchmail: malloc failed\n"));
85 for (c = p = plugin_copy; *c; c++)
86 { if (isspace(*c) && !isspace(*p))
93 report(stderr, _("fetchmail: malloc failed\n"));
97 for (c = p = plugin_copy, i = 0; *c; c++)
98 { if ((!isspace(*c)) && (c == p ? 1 : isspace(*p))) {
104 for (c = plugin_copy; *c; c++)
108 for (i = 0; argvec[i]; i++)
109 { if (strcmp(argvec[i], "%h") == 0)
111 if (strcmp(argvec[i], "%p") == 0)
117 static int handle_plugin(const char *host,
118 const char *service, const char *plugin)
119 /* get a socket mediated through a given external command */
125 * The author of this code, Felix von Leitner <felix@convergence.de>, says:
126 * he chose socketpair() instead of pipe() because socketpair creates
127 * bidirectional sockets while allegedly some pipe() implementations don't.
129 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
131 report(stderr, _("fetchmail: socketpair failed\n"));
137 report(stderr, _("fetchmail: fork failed\n"));
141 /* fds[1] is the parent's end; close it for proper EOF
143 (void) close(fds[1]);
144 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
145 report(stderr, _("dup2 failed\n"));
148 /* fds[0] is now connected to 0 and 1; close it */
149 (void) close(fds[0]);
150 if (outlevel >= O_VERBOSE)
151 report(stderr, _("running %s (host %s service %s)\n"), plugin, host, service);
152 argvec = (char *const *)parse_plugin(plugin,host,service);
153 execvp(*argvec, argvec);
154 report(stderr, _("execvp(%s) failed\n"), *argvec);
157 default: /* parent */
161 /* fds[0] is the child's end; close it for proper EOF detection */
162 (void) close(fds[0]);
165 #endif /* HAVE_SOCKETPAIR */
168 #include <sys/time.h>
170 int SockCheckOpen(int fd)
171 /* poll given socket; is it selectable? */
179 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
182 tv.tv_sec = 0; tv.tv_usec = 0;
183 rt = select(fd+1, &r, &w, &e, &tv);
184 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
190 #endif /* __UNUSED__ */
192 int UnixOpen(const char *path)
195 struct sockaddr_un ad;
196 memset(&ad, 0, sizeof(ad));
197 ad.sun_family = AF_UNIX;
198 strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
200 sock = socket( AF_UNIX, SOCK_STREAM, 0 );
206 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
209 fm_close(sock); /* don't use SockClose, no traffic yet */
218 int SockOpen(const char *host, const char *service, const char *options,
221 struct addrinfo *ai, *ai0, req;
224 void *request = NULL;
226 #endif /* NET_SECURITY */
228 #ifdef HAVE_SOCKETPAIR
230 return handle_plugin(host,service,plugin);
231 #endif /* HAVE_SOCKETPAIR */
232 memset(&req, 0, sizeof(struct addrinfo));
233 req.ai_socktype = SOCK_STREAM;
235 if (getaddrinfo(host, service, &req, &ai0)) {
236 report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
244 if (net_security_strtorequest((char *)options, &request, &requestlen))
247 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
252 #else /* NET_SECURITY */
253 #ifdef HAVE_INNER_CONNECT
254 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
259 for (ai = ai0; ai; ai = ai->ai_next) {
260 i = socket(ai->ai_family, ai->ai_socktype, 0);
263 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
271 #endif /* NET_SECURITY */
277 #else /* INET6_ENABLE */
278 #ifndef HAVE_INET_ATON
280 #ifdef INADDR_BROADCAST
281 #define INADDR_NONE INADDR_BROADCAST
283 #define INADDR_NONE -1
286 #endif /* HAVE_INET_ATON */
288 int SockOpen(const char *host, int clientPort, const char *options,
291 int sock = -1; /* pacify -Wall */
292 #ifndef HAVE_INET_ATON
293 unsigned long inaddr;
294 #endif /* HAVE_INET_ATON */
295 struct sockaddr_in ad, **pptr;
298 #ifdef HAVE_SOCKETPAIR
301 sprintf(buf,"%d",clientPort);
302 return handle_plugin(host,buf,plugin);
304 #endif /* HAVE_SOCKETPAIR */
306 memset(&ad, 0, sizeof(ad));
307 ad.sin_family = AF_INET;
309 /* we'll accept a quad address */
310 #ifndef HAVE_INET_ATON
311 inaddr = inet_addr(host);
312 if (inaddr != INADDR_NONE)
314 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
316 if (inet_aton(host, &ad.sin_addr))
318 #endif /* HAVE_INET_ATON */
319 ad.sin_port = htons(clientPort);
321 sock = socket(AF_INET, SOCK_STREAM, 0);
327 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
330 fm_close(sock); /* don't use SockClose, no traffic yet */
335 #ifndef HAVE_INET_ATON
339 #endif /* HAVE_INET_ATON */
341 hp = gethostbyname(host);
349 * Add a check to make sure the address has a valid IPv4 or IPv6
350 * length. This prevents buffer spamming by a broken DNS.
352 if(hp->h_length != 4 && hp->h_length != 8)
356 _("fetchmail: illegal address length received for host %s\n"),host);
360 * Try all addresses of a possibly multihomed host until we get
361 * a successful connect or until we run out of addresses.
363 pptr = (struct sockaddr_in **)hp->h_addr_list;
364 for(; *pptr != NULL; pptr++)
366 sock = socket(AF_INET, SOCK_STREAM, 0);
372 ad.sin_port = htons(clientPort);
373 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
374 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
376 fm_close(sock); /* don't use SockClose, no traffic yet */
377 memset(&ad, 0, sizeof(ad));
378 ad.sin_family = AF_INET;
383 fm_close(sock); /* don't use SockClose, no traffic yet */
392 #endif /* INET6_ENABLE */
395 #if defined(HAVE_STDARG_H)
396 int SockPrintf(int sock, const char* format, ...)
399 int SockPrintf(sock,format,va_alist)
408 #if defined(HAVE_STDARG_H)
409 va_start(ap, format) ;
413 #ifdef HAVE_VSNPRINTF
414 vsnprintf(buf, sizeof(buf), format, ap);
416 vsprintf(buf, format, ap);
419 return SockWrite(sock, buf, strlen(buf));
424 #include "openssl/ssl.h"
425 #include "openssl/err.h"
426 #include "openssl/pem.h"
427 #include "openssl/x509.h"
429 static SSL_CTX *_ctx = NULL;
430 static SSL *_ssl_context[FD_SETSIZE];
432 SSL *SSLGetContext( int );
433 #endif /* SSL_ENABLE */
435 int SockWrite(int sock, char *buf, int len)
445 if( NULL != ( ssl = SSLGetContext( sock ) ) )
446 n = SSL_write(ssl, buf, len);
448 n = fm_write(sock, buf, len);
450 n = fm_write(sock, buf, len);
461 int SockRead(int sock, char *buf, int len)
463 char *newline, *bp = buf;
481 * The reason for these gymnastics is that we want two things:
482 * (1) to read \n-terminated lines,
483 * (2) to return the true length of data read, even if the
484 * data coming in has embedded NULS.
487 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
489 /* OK... SSL_peek works a little different from MSG_PEEK
490 Problem is that SSL_peek can return 0 if there
491 is no data currently available. If, on the other
492 hand, we loose the socket, we also get a zero, but
493 the SSL_read then SEGFAULTS! To deal with this,
494 we'll check the error code any time we get a return
495 of zero from SSL_peek. If we have an error, we bail.
496 If we don't, we read one character in SSL_read and
497 loop. This should continue to work even if they
498 later change the behavior of SSL_peek
499 to "fix" this problem... :-( */
500 if ((n = SSL_peek(ssl, bp, len)) < 0) {
504 /* SSL_peek says no data... Does he mean no data
505 or did the connection blow up? If we got an error
507 if( 0 != ( n = ERR_get_error() ) ) {
510 /* We didn't get an error so read at least one
511 character at this point and loop */
513 /* Make sure newline start out NULL!
514 * We don't have a string to pass through
515 * the strchr at this point yet */
517 } else if ((newline = memchr(bp, '\n', n)) != NULL)
518 n = newline - bp + 1;
519 if ((n = SSL_read(ssl, bp, n)) == -1) {
522 /* Check for case where our single character turned out to
523 * be a newline... (It wasn't going to get caught by
524 * the strchr above if it came from the hack... ). */
525 if( NULL == newline && 1 == n && '\n' == *bp ) {
526 /* Got our newline - this will break
527 out of the loop now */
531 if ((n = fm_peek(sock, bp, len)) <= 0)
533 if ((newline = memchr(bp, '\n', n)) != NULL)
534 n = newline - bp + 1;
535 if ((n = fm_read(sock, bp, n)) == -1)
541 if ((n = fm_read(sock, bp, 1)) <= 0)
543 if ((n = fm_peek(sock, bp, len)) <= 0)
546 if ((newline = memchr(bp, '\n', n)) != NULL)
547 n = newline - bp + 1;
549 if ((n = fm_read(sock, bp, n)) == -1)
551 #endif /* __BEOS__ */
561 int SockPeek(int sock)
562 /* peek at the next socket character without actually reading it */
571 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
572 n = SSL_peek(ssl, &ch, 1);
574 /* This code really needs to implement a "hold back"
575 * to simulate a functioning SSL_peek()... sigh...
576 * Has to be coordinated with the read code above.
577 * Next on the list todo... */
579 /* SSL_peek says no data... Does he mean no data
580 or did the connection blow up? If we got an error
582 if( 0 != ( n = ERR_get_error() ) ) {
586 /* Haven't seen this case actually occur, but...
587 if the problem in SockRead can occur, this should
588 be possible... Just not sure what to do here.
589 This should be a safe "punt" the "peek" but don't
590 "punt" the "session"... */
592 return 0; /* Give him a '\0' character */
595 n = fm_peek(sock, &ch, 1);
599 n = fm_peek(sock, &ch, 1);
601 #endif /* SSL_ENABLE */
613 static char *_ssl_server_cname = NULL;
615 SSL *SSLGetContext( int sock )
617 /* If SSLOpen has never initialized - just return NULL */
621 if( sock < 0 || sock > FD_SETSIZE )
623 return _ssl_context[sock];
627 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
636 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
637 err = X509_STORE_CTX_get_error(ctx);
638 depth = X509_STORE_CTX_get_error_depth(ctx);
640 X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
641 X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
643 /* Just to be sure those buffers are terminated... I think the
644 X509 libraries do, but... */
645 buf[256] = ibuf[256] = '\0';
648 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
650 strcpy( cbuf, str_ptr );
651 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
654 if (outlevel == O_VERBOSE)
655 report(stdout, _("Issuer Organization: %s\n"), cbuf );
657 if (outlevel == O_VERBOSE)
658 report(stdout, _("Unknown Organization\n"), cbuf );
660 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
662 strcpy( cbuf, str_ptr );
663 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
666 if (outlevel == O_VERBOSE)
667 report(stdout, _("Issuer CommonName: %s\n"), cbuf );
669 if (outlevel == O_VERBOSE)
670 report(stdout, _("Unknown Issuer CommonName\n"), cbuf );
672 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
674 strcpy( cbuf, str_ptr );
675 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
678 if (outlevel == O_VERBOSE)
679 report(stdout, _("Server CommonName: %s\n"), cbuf);
681 if (_ssl_server_cname != NULL)
684 char *p2 = _ssl_server_cname;
690 n = strlen(p2) - strlen(p1);
694 if ( 0 != strcasecmp( p1, p2 ) )
696 "Server CommonName mismatch: %s != %s\n",
697 cbuf, _ssl_server_cname );
700 if (outlevel == O_VERBOSE)
701 report(stdout, _("Unknown Server CommonName\n"), cbuf );
705 switch (ctx->error) {
706 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
707 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
708 report(stdout, _("unknown issuer= %s"), buf);
710 case X509_V_ERR_CERT_NOT_YET_VALID:
711 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
712 report(stderr, _("Server Certificate not yet valid"));
714 case X509_V_ERR_CERT_HAS_EXPIRED:
715 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
716 report(stderr, _("Server Certificate expired"));
719 /* We are not requiring or validating server or issuer id's as yet */
720 /* Always return OK from here */
726 /* performs initial SSL handshake over the connected socket
727 * uses SSL *ssl global variable, which is currently defined
730 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
732 SSL_load_error_strings();
733 SSLeay_add_ssl_algorithms();
735 if( sock < 0 || sock > FD_SETSIZE ) {
736 report(stderr, _("File descriptor out of range for SSL") );
741 /* Be picky and make sure the memory is cleared */
742 memset( _ssl_context, 0, sizeof( _ssl_context ) );
743 _ctx = SSL_CTX_new(SSLv23_client_method());
745 ERR_print_errors_fp(stderr);
750 _ssl_context[sock] = SSL_new(_ctx);
752 if(_ssl_context[sock] == NULL) {
753 ERR_print_errors_fp(stderr);
757 /* This static is for the verify callback */
758 _ssl_server_cname = servercname;
760 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
762 if( mycert || mykey ) {
764 /* Ok... He has a certificate file defined, so lets declare it. If
765 * he does NOT have a separate certificate and private key file then
766 * assume that it's a combined key and certificate file.
772 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
773 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
776 SSL_set_fd(_ssl_context[sock], sock);
778 if(SSL_connect(_ssl_context[sock]) == -1) {
779 ERR_print_errors_fp(stderr);
787 int SockClose(int sock)
788 /* close a socket gracefully */
793 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
794 /* Clean up the SSL stack */
795 SSL_free( _ssl_context[sock] );
796 _ssl_context[sock] = NULL;
802 * This hangs in RedHat 6.2 after fetchmail runs for a while a
803 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
804 * the recv system call. (Reported from jtnews
805 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
807 * Half-close the connection first so the other end gets notified.
809 * This stops sends but allows receives (effectively, it sends a
811 if (shutdown(sock, 1) == 0) {
813 /* If there is any data still waiting in the queue, discard it.
814 * Call recv() until either it returns 0 (meaning we received a FIN)
815 * or any error occurs. This makes sure all data sent by the other
816 * side is acknowledged at the TCP level.
818 if (fm_peek(sock, &ch, 1) > 0)
819 while (fm_read(sock, &ch, 1) > 0)
822 #endif /* __UNUSED__ */
824 /* if there's an error closing at this point, not much we can do */
825 return(fm_close(sock)); /* this is guarded */
830 * Use the chargen service to test input buffering directly.
831 * You may have to uncomment the `chargen' service description in your
832 * inetd.conf (and then SIGHUP inetd) for this to work. */
835 int sock = SockOpen("localhost", 19, NULL);
838 while (SockRead(sock, buf, sizeof(buf)-1))
839 SockWrite(1, buf, strlen(buf));
844 /* socket.c ends here */