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 static int handle_plugin(const char *host,
74 const char *service, const char *plugin)
75 /* get a socket mediated through a given external command */
78 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
80 report(stderr, _("fetchmail: socketpair failed\n"));
86 report(stderr, _("fetchmail: fork failed\n"));
90 /* fds[1] is the parent's end; close it for proper EOF
93 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
94 report(stderr, _("dup2 failed\n"));
97 /* fds[0] is now connected to 0 and 1; close it */
99 if (outlevel >= O_VERBOSE)
100 report(stderr, _("running %s %s %s\n"), plugin, host, service);
101 execlp(plugin,plugin,host,service,0);
102 report(stderr, _("execl(%s) failed\n"), plugin);
105 default: /* parent */
109 /* fds[0] is the child's end; close it for proper EOF detection */
110 (void) close(fds[0]);
113 #endif /* HAVE_SOCKETPAIR */
116 #include <sys/time.h>
118 int SockCheckOpen(int fd)
119 /* poll given socket; is it selectable? */
127 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
130 tv.tv_sec = 0; tv.tv_usec = 0;
131 rt = select(fd+1, &r, &w, &e, &tv);
132 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
138 #endif /* __UNUSED__ */
141 int SockOpen(const char *host, const char *service, const char *options,
144 struct addrinfo *ai, *ai0, req;
147 void *request = NULL;
149 #endif /* NET_SECURITY */
151 #ifdef HAVE_SOCKETPAIR
153 return handle_plugin(host,service,plugin);
154 #endif /* HAVE_SOCKETPAIR */
155 memset(&req, 0, sizeof(struct addrinfo));
156 req.ai_socktype = SOCK_STREAM;
158 if (getaddrinfo(host, service, &req, &ai0)) {
159 report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
167 if (net_security_strtorequest((char *)options, &request, &requestlen))
170 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
175 #else /* NET_SECURITY */
176 #ifdef HAVE_INNER_CONNECT
177 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
182 for (ai = ai0; ai; ai = ai->ai_next) {
183 i = socket(ai->ai_family, ai->ai_socktype, 0);
186 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
194 #endif /* NET_SECURITY */
200 #else /* INET6_ENABLE */
201 #ifndef HAVE_INET_ATON
203 #ifdef INADDR_BROADCAST
204 #define INADDR_NONE INADDR_BROADCAST
206 #define INADDR_NONE -1
209 #endif /* HAVE_INET_ATON */
211 int SockOpen(const char *host, int clientPort, const char *options,
214 int sock = -1; /* pacify -Wall */
215 #ifndef HAVE_INET_ATON
216 unsigned long inaddr;
217 #endif /* HAVE_INET_ATON */
218 struct sockaddr_in ad, **pptr;
221 #ifdef HAVE_SOCKETPAIR
224 sprintf(buf,"%d",clientPort);
225 return handle_plugin(host,buf,plugin);
227 #endif /* HAVE_SOCKETPAIR */
229 memset(&ad, 0, sizeof(ad));
230 ad.sin_family = AF_INET;
232 /* we'll accept a quad address */
233 #ifndef HAVE_INET_ATON
234 inaddr = inet_addr(host);
235 if (inaddr != INADDR_NONE)
237 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
239 if (inet_aton(host, &ad.sin_addr))
241 #endif /* HAVE_INET_ATON */
242 ad.sin_port = htons(clientPort);
244 sock = socket(AF_INET, SOCK_STREAM, 0);
250 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
253 fm_close(sock); /* don't use SockClose, no traffic yet */
258 #ifndef HAVE_INET_ATON
262 #endif /* HAVE_INET_ATON */
264 hp = gethostbyname(host);
272 * Add a check to make sure the address has a valid IPv4 or IPv6
273 * length. This prevents buffer spamming by a broken DNS.
275 if(hp->h_length != 4 && hp->h_length != 8)
279 _("fetchmail: illegal address length received for host %s\n"),host);
283 * Try all addresses of a possibly multihomed host until we get
284 * a successful connect or until we run out of addresses.
286 pptr = (struct sockaddr_in **)hp->h_addr_list;
287 for(; *pptr != NULL; pptr++)
289 sock = socket(AF_INET, SOCK_STREAM, 0);
295 ad.sin_port = htons(clientPort);
296 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
297 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
299 fm_close(sock); /* don't use SockClose, no traffic yet */
300 memset(&ad, 0, sizeof(ad));
301 ad.sin_family = AF_INET;
306 fm_close(sock); /* don't use SockClose, no traffic yet */
315 #endif /* INET6_ENABLE */
318 #if defined(HAVE_STDARG_H)
319 int SockPrintf(int sock, const char* format, ...)
322 int SockPrintf(sock,format,va_alist)
331 #if defined(HAVE_STDARG_H)
332 va_start(ap, format) ;
336 #ifdef HAVE_VSNPRINTF
337 vsnprintf(buf, sizeof(buf), format, ap);
339 vsprintf(buf, format, ap);
342 return SockWrite(sock, buf, strlen(buf));
352 static SSL_CTX *_ctx = NULL;
353 static SSL *_ssl_context[FD_SETSIZE];
355 SSL *SSLGetContext( int );
356 #endif /* SSL_ENABLE */
358 int SockWrite(int sock, char *buf, int len)
368 if( NULL != ( ssl = SSLGetContext( sock ) ) )
369 n = SSL_write(ssl, buf, len);
371 n = fm_write(sock, buf, len);
373 n = fm_write(sock, buf, len);
384 int SockRead(int sock, char *buf, int len)
386 char *newline, *bp = buf;
404 * The reason for these gymnastics is that we want two things:
405 * (1) to read \n-terminated lines,
406 * (2) to return the true length of data read, even if the
407 * data coming in has embedded NULS.
410 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
412 /* OK... SSL_peek works a little different from MSG_PEEK
413 Problem is that SSL_peek can return 0 if there
414 is no data currently available. If, on the other
415 hand, we loose the socket, we also get a zero, but
416 the SSL_read then SEGFAULTS! To deal with this,
417 we'll check the error code any time we get a return
418 of zero from SSL_peek. If we have an error, we bail.
419 If we don't, we read one character in SSL_read and
420 loop. This should continue to work even if they
421 later change the behavior of SSL_peek
422 to "fix" this problem... :-( */
423 if ((n = SSL_peek(ssl, bp, len)) < 0) {
427 /* SSL_peek says no data... Does he mean no data
428 or did the connection blow up? If we got an error
430 if( 0 != ( n = ERR_get_error() ) ) {
433 /* We didn't get an error so read at least one
434 character at this point and loop */
436 /* Make sure newline start out NULL!
437 * We don't have a string to pass through
438 * the strchr at this point yet */
440 } else if ((newline = memchr(bp, '\n', n)) != NULL)
441 n = newline - bp + 1;
442 if ((n = SSL_read(ssl, bp, n)) == -1) {
445 /* Check for case where our single character turned out to
446 * be a newline... (It wasn't going to get caught by
447 * the strchr above if it came from the hack... ). */
448 if( NULL == newline && 1 == n && '\n' == *bp ) {
449 /* Got our newline - this will break
450 out of the loop now */
454 if ((n = fm_peek(sock, bp, len)) <= 0)
456 if ((newline = memchr(bp, '\n', n)) != NULL)
457 n = newline - bp + 1;
458 if ((n = fm_read(sock, bp, n)) == -1)
464 if ((n = fm_read(sock, bp, 1)) <= 0)
466 if ((n = fm_peek(sock, bp, len)) <= 0)
469 if ((newline = memchr(bp, '\n', n)) != NULL)
470 n = newline - bp + 1;
472 if ((n = fm_read(sock, bp, n)) == -1)
474 #endif /* __BEOS__ */
484 int SockPeek(int sock)
485 /* peek at the next socket character without actually reading it */
494 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
495 n = SSL_peek(ssl, &ch, 1);
497 /* This code really needs to implement a "hold back"
498 * to simulate a functioning SSL_peek()... sigh...
499 * Has to be coordinated with the read code above.
500 * Next on the list todo... */
502 /* SSL_peek says no data... Does he mean no data
503 or did the connection blow up? If we got an error
505 if( 0 != ( n = ERR_get_error() ) ) {
509 /* Haven't seen this case actually occur, but...
510 if the problem in SockRead can occur, this should
511 be possible... Just not sure what to do here.
512 This should be a safe "punt" the "peek" but don't
513 "punt" the "session"... */
515 return 0; /* Give him a '\0' character */
518 n = fm_peek(sock, &ch, 1);
522 n = fm_peek(sock, &ch, 1);
524 #endif /* SSL_ENABLE */
536 static char *_ssl_server_cname = NULL;
538 SSL *SSLGetContext( int sock )
540 /* If SSLOpen has never initialized - just return NULL */
544 if( sock < 0 || sock > FD_SETSIZE )
546 return _ssl_context[sock];
550 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
559 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
560 err = X509_STORE_CTX_get_error(ctx);
561 depth = X509_STORE_CTX_get_error_depth(ctx);
563 X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
564 X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
566 /* Just to be sure those buffers are terminated... I think the
567 X509 libraries do, but... */
568 buf[256] = ibuf[256] = '\0';
571 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
573 strcpy( cbuf, str_ptr );
574 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
577 if (outlevel == O_VERBOSE)
578 report(stdout, "Issuer Organization: %s\n", cbuf );
580 if (outlevel == O_VERBOSE)
581 report(stdout, "Unknown Organization\n", cbuf );
583 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
585 strcpy( cbuf, str_ptr );
586 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
589 if (outlevel == O_VERBOSE)
590 report(stdout, "Issuer CommonName: %s\n", cbuf );
592 if (outlevel == O_VERBOSE)
593 report(stdout, "Unknown Issuer CommonName\n", cbuf );
595 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
597 strcpy( cbuf, str_ptr );
598 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
601 if (outlevel == O_VERBOSE)
602 report(stdout, "Server CommonName: %s\n", cbuf );
603 /* Should we have some wildcarding here? */
604 if ( NULL != _ssl_server_cname
605 && 0 != strcasemp( cbuf, _ssl_server_cname ) ) {
607 "Server CommonName mismatch: %s != %s\n",
608 cbuf, _ssl_server_cname );
611 if (outlevel == O_VERBOSE)
612 report(stdout, "Unknown Server CommonName\n", cbuf );
616 switch (ctx->error) {
617 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
618 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
619 report(stdout, "unknown issuer= %s", buf);
621 case X509_V_ERR_CERT_NOT_YET_VALID:
622 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
623 report(stderr, "Server Certificate not yet valid");
625 case X509_V_ERR_CERT_HAS_EXPIRED:
626 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
627 report(stderr, "Server Certificate expired");
630 /* We are not requiring or validating server or issuer id's as yet */
631 /* Always return OK from here */
637 /* performs initial SSL handshake over the connected socket
638 * uses SSL *ssl global variable, which is currently defined
641 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
643 SSL_load_error_strings();
644 SSLeay_add_ssl_algorithms();
646 if( sock < 0 || sock > FD_SETSIZE ) {
647 report(stderr, "File descriptor out of range for SSL" );
652 /* Be picky and make sure the memory is cleared */
653 memset( _ssl_context, 0, sizeof( _ssl_context ) );
654 _ctx = SSL_CTX_new(SSLv23_client_method());
656 ERR_print_errors_fp(stderr);
661 _ssl_context[sock] = SSL_new(_ctx);
663 if(_ssl_context[sock] == NULL) {
664 ERR_print_errors_fp(stderr);
668 /* This static is for the verify callback */
669 _ssl_server_cname = servercname;
671 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
673 if( mycert || mykey ) {
675 /* Ok... He has a certificate file defined, so lets declare it. If
676 * he does NOT have a separate certificate and private key file then
677 * assume that it's a combined key and certificate file.
683 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
684 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
687 SSL_set_fd(_ssl_context[sock], sock);
689 if(SSL_connect(_ssl_context[sock]) == -1) {
690 ERR_print_errors_fp(stderr);
698 int SockClose(int sock)
699 /* close a socket gracefully */
704 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
705 /* Clean up the SSL stack */
706 SSL_free( _ssl_context[sock] );
707 _ssl_context[sock] = NULL;
713 * This hangs in RedHat 6.2 after fetchmail runs for a while a
714 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
715 * the recv system call. (Reported from jtnews
716 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
718 * Half-close the connection first so the other end gets notified.
720 * This stops sends but allows receives (effectively, it sends a
722 if (shutdown(sock, 1) == 0) {
724 /* If there is any data still waiting in the queue, discard it.
725 * Call recv() until either it returns 0 (meaning we received a FIN)
726 * or any error occurs. This makes sure all data sent by the other
727 * side is acknowledged at the TCP level.
729 if (fm_peek(sock, &ch, 1) > 0)
730 while (fm_read(sock, &ch, 1) > 0)
733 #endif /* __UNUSED__ */
735 /* if there's an error closing at this point, not much we can do */
736 return(fm_close(sock)); /* this is guarded */
741 * Use the chargen service to test input buffering directly.
742 * You may have to uncomment the `chargen' service description in your
743 * inetd.conf (and then SIGHUP inetd) for this to work. */
746 int sock = SockOpen("localhost", 19, NULL);
749 while (SockRead(sock, buf, sizeof(buf)-1))
750 SockWrite(1, buf, strlen(buf));
755 /* socket.c ends here */