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 #include <sys/socket.h>
17 #include <netinet/in.h>
18 #include <arpa/inet.h>
20 #if defined(STDC_HEADERS)
23 #if defined(HAVE_UNISTD_H)
26 #if defined(HAVE_STDARG_H)
32 #include "fetchmail.h"
35 /* We need to define h_errno only if it is not already */
38 #ifdef HAVE_RES_SEARCH
39 /* some versions of FreeBSD should declare this but don't */
42 /* pretend we have h_errno to avoid some #ifdef's later */
46 #endif /* ndef h_errno */
49 #include <net/security.h>
50 #endif /* NET_SECURITY */
52 #ifdef HAVE_SOCKETPAIR
53 static int handle_plugin(const char *host,
54 const char *service, const char *plugin)
55 /* get a socket mediated through a given external command */
58 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
60 report(stderr, _("fetchmail: socketpair failed\n"));
66 report(stderr, _("fetchmail: fork failed\n"));
70 /* fds[1] is the parent's end; close it for proper EOF
73 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
74 report(stderr, _("dup2 failed\n"));
77 /* fds[0] is now connected to 0 and 1; close it */
79 if (outlevel >= O_VERBOSE)
80 report(stderr, _("running %s %s %s\n"), plugin, host, service);
81 execlp(plugin,plugin,host,service,0);
82 report(stderr, _("execl(%s) failed\n"), plugin);
89 /* fds[0] is the child's end; close it for proper EOF detection */
93 #endif /* HAVE_SOCKETPAIR */
98 int SockCheckOpen(int fd)
99 /* poll given socket; is it selectable? */
107 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
110 tv.tv_sec = 0; tv.tv_usec = 0;
111 rt = select(fd+1, &r, &w, &e, &tv);
112 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
118 #endif /* __UNUSED__ */
121 int SockOpen(const char *host, const char *service, const char *options,
124 struct addrinfo *ai, req;
127 void *request = NULL;
129 #endif /* NET_SECURITY */
131 #ifdef HAVE_SOCKETPAIR
133 return handle_plugin(host,service,plugin);
134 #endif /* HAVE_SOCKETPAIR */
135 memset(&req, 0, sizeof(struct addrinfo));
136 req.ai_socktype = SOCK_STREAM;
138 if (getaddrinfo(host, service, &req, &ai)) {
139 report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
147 if (net_security_strtorequest((char *)options, &request, &requestlen))
150 i = inner_connect(ai, request, requestlen, NULL, NULL, "fetchmail", NULL);
155 #else /* NET_SECURITY */
156 #ifdef HAVE_INNER_CONNECT
157 i = inner_connect(ai, NULL, 0, NULL, NULL, "fetchmail", NULL);
159 i = socket(ai->ai_family, ai->ai_socktype, 0);
164 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
166 close(i); /* don't use SockClose, no traffic yet */
170 #endif /* NET_SECURITY */
176 #else /* INET6_ENABLE */
177 #ifndef HAVE_INET_ATON
179 #ifdef INADDR_BROADCAST
180 #define INADDR_NONE INADDR_BROADCAST
182 #define INADDR_NONE -1
185 #endif /* HAVE_INET_ATON */
187 int SockOpen(const char *host, int clientPort, const char *options,
190 int sock = -1; /* pacify -Wall */
191 #ifndef HAVE_INET_ATON
192 unsigned long inaddr;
193 #endif /* HAVE_INET_ATON */
194 struct sockaddr_in ad, **pptr;
197 #ifdef HAVE_SOCKETPAIR
200 sprintf(buf,"%d",clientPort);
201 return handle_plugin(host,buf,plugin);
203 #endif /* HAVE_SOCKETPAIR */
205 memset(&ad, 0, sizeof(ad));
206 ad.sin_family = AF_INET;
208 /* we'll accept a quad address */
209 #ifndef HAVE_INET_ATON
210 inaddr = inet_addr(host);
211 if (inaddr != INADDR_NONE)
213 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
215 if (inet_aton(host, &ad.sin_addr))
217 #endif /* HAVE_INET_ATON */
218 ad.sin_port = htons(clientPort);
220 sock = socket(AF_INET, SOCK_STREAM, 0);
226 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
229 close(sock); /* don't use SockClose, no traffic yet */
234 #ifndef HAVE_INET_ATON
238 #endif /* HAVE_INET_ATON */
240 hp = gethostbyname(host);
248 * Add a check to make sure the address has a valid IPv4 or IPv6
249 * length. This prevents buffer spamming by a broken DNS.
251 if(hp->h_length != 4 && hp->h_length != 8)
255 _("fetchmail: illegal address length received for host %s\n"),host);
259 * Try all addresses of a possibly multihomed host until we get
260 * a successful connect or until we run out of addresses.
262 pptr = (struct sockaddr_in **)hp->h_addr_list;
263 for(; *pptr != NULL; pptr++)
265 sock = socket(AF_INET, SOCK_STREAM, 0);
271 ad.sin_port = htons(clientPort);
272 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
273 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
275 close(sock); /* don't use SockClose, no traffic yet */
276 memset(&ad, 0, sizeof(ad));
277 ad.sin_family = AF_INET;
282 close(sock); /* don't use SockClose, no traffic yet */
290 #endif /* INET6_ENABLE */
293 #if defined(HAVE_STDARG_H)
294 int SockPrintf(int sock, const char* format, ...)
297 int SockPrintf(sock,format,va_alist)
306 #if defined(HAVE_STDARG_H)
307 va_start(ap, format) ;
311 #ifdef HAVE_VSNPRINTF
312 vsnprintf(buf, sizeof(buf), format, ap);
314 vsprintf(buf, format, ap);
317 return SockWrite(sock, buf, strlen(buf));
327 static SSL_CTX *_ctx = NULL;
328 static SSL *_ssl_context[FD_SETSIZE];
330 SSL *SSLGetContext( int );
331 #endif /* SSL_ENABLE */
333 int SockWrite(int sock, char *buf, int len)
343 if( NULL != ( ssl = SSLGetContext( sock ) ) )
344 n = SSL_write(ssl, buf, len);
346 n = write(sock, buf, len);
348 n = write(sock, buf, len);
359 int SockRead(int sock, char *buf, int len)
361 char *newline, *bp = buf;
371 * The reason for these gymnastics is that we want two things:
372 * (1) to read \n-terminated lines,
373 * (2) to return the true length of data read, even if the
374 * data coming in has embedded NULS.
377 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
379 /* OK... SSL_peek works a little different from MSG_PEEK
380 Problem is that SSL_peek can return 0 if there
381 is no data currently available. If, on the other
382 hand, we loose the socket, we also get a zero, but
383 the SSL_read then SEGFAULTS! To deal with this,
384 we'll check the error code any time we get a return
385 of zero from SSL_peek. If we have an error, we bail.
386 If we don't, we read one character in SSL_read and
387 loop. This should continue to work even if they
388 later change the behavior of SSL_peek
389 to "fix" this problem... :-( */
390 if ((n = SSL_peek(ssl, bp, len)) < 0) {
394 /* SSL_peek says no data... Does he mean no data
395 or did the connection blow up? If we got an error
397 if( 0 != ( n = ERR_get_error() ) ) {
400 /* We didn't get an error so read at least one
401 character at this point and loop */
403 /* Make sure newline start out NULL!
404 * We don't have a string to pass through
405 * the strchr at this point yet */
407 } else if ((newline = memchr(bp, '\n', n)) != NULL)
408 n = newline - bp + 1;
409 if ((n = SSL_read(ssl, bp, n)) == -1) {
412 /* Check for case where our single character turned out to
413 * be a newline... (It wasn't going to get caught by
414 * the strchr above if it came from the hack... ). */
415 if( NULL == newline && 1 == n && '\n' == *bp ) {
416 /* Got our newline - this will break
417 out of the loop now */
421 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
423 if ((newline = memchr(bp, '\n', n)) != NULL)
424 n = newline - bp + 1;
425 if ((n = read(sock, bp, n)) == -1)
429 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
431 if ((newline = memchr(bp, '\n', n)) != NULL)
432 n = newline - bp + 1;
433 if ((n = read(sock, bp, n)) == -1)
444 int SockPeek(int sock)
445 /* peek at the next socket character without actually reading it */
454 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
455 n = SSL_peek(ssl, &ch, 1);
457 /* This code really needs to implement a "hold back"
458 * to simulate a functioning SSL_peek()... sigh...
459 * Has to be coordinated with the read code above.
460 * Next on the list todo... */
462 /* SSL_peek says no data... Does he mean no data
463 or did the connection blow up? If we got an error
465 if( 0 != ( n = ERR_get_error() ) ) {
469 /* Haven't seen this case actually occur, but...
470 if the problem in SockRead can occur, this should
471 be possible... Just not sure what to do here.
472 This should be a safe "punt" the "peek" but don't
473 "punt" the "session"... */
475 return 0; /* Give him a '\0' character */
478 n = recv(sock, &ch, 1, MSG_PEEK);
481 n = recv(sock, &ch, 1, MSG_PEEK);
491 static char *_ssl_server_cname = NULL;
493 SSL *SSLGetContext( int sock )
495 /* If SSLOpen has never initialized - just return NULL */
499 if( sock < 0 || sock > FD_SETSIZE )
501 return _ssl_context[sock];
505 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
514 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
515 err = X509_STORE_CTX_get_error(ctx);
516 depth = X509_STORE_CTX_get_error_depth(ctx);
518 X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
519 X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
521 /* Just to be sure those buffers are terminated... I think the
522 X509 libraries do, but... */
523 buf[256] = ibuf[256] = '\0';
526 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
528 strcpy( cbuf, str_ptr );
529 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
532 if (outlevel == O_VERBOSE)
533 report(stdout, "Issuer Organization: %s\n", cbuf );
535 if (outlevel == O_VERBOSE)
536 report(stdout, "Unknown Organization\n", cbuf );
538 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
540 strcpy( cbuf, str_ptr );
541 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
544 if (outlevel == O_VERBOSE)
545 report(stdout, "Issuer CommonName: %s\n", cbuf );
547 if (outlevel == O_VERBOSE)
548 report(stdout, "Unknown Issuer CommonName\n", cbuf );
550 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
552 strcpy( cbuf, str_ptr );
553 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
556 if (outlevel == O_VERBOSE)
557 report(stdout, "Server CommonName: %s\n", cbuf );
558 /* Should we have some wildcarding here? */
559 if ( NULL != _ssl_server_cname
560 && 0 != strcmp( cbuf, _ssl_server_cname ) ) {
562 "Server CommonName mismatch: %s != %s\n",
563 cbuf, _ssl_server_cname );
566 if (outlevel == O_VERBOSE)
567 report(stdout, "Unknown Server CommonName\n", cbuf );
571 switch (ctx->error) {
572 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
573 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
574 report(stdout, "unknown issuer= %s", buf);
576 case X509_V_ERR_CERT_NOT_YET_VALID:
577 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
578 report(stderr, "Server Certificate not yet valid");
580 case X509_V_ERR_CERT_HAS_EXPIRED:
581 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
582 report(stderr, "Server Certificate expired");
585 /* We are not requiring or validating server or issuer id's as yet */
586 /* Always return OK from here */
592 /* performs initial SSL handshake over the connected socket
593 * uses SSL *ssl global variable, which is currently defined
596 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
598 SSL_load_error_strings();
599 SSLeay_add_ssl_algorithms();
601 if( sock < 0 || sock > FD_SETSIZE ) {
602 report(stderr, "File descriptor out of range for SSL" );
607 /* Be picky and make sure the memory is cleared */
608 memset( _ssl_context, 0, sizeof( _ssl_context ) );
609 _ctx = SSL_CTX_new(SSLv23_client_method());
611 ERR_print_errors_fp(stderr);
616 _ssl_context[sock] = SSL_new(_ctx);
618 if(_ssl_context[sock] == NULL) {
619 ERR_print_errors_fp(stderr);
623 /* This static is for the verify callback */
624 _ssl_server_cname = servercname;
626 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
628 if( mycert || mykey ) {
630 /* Ok... He has a certificate file defined, so lets declare it. If
631 * he does NOT have a separate certificate and private key file then
632 * assume that it's a combined key and certificate file.
638 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
639 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
642 SSL_set_fd(_ssl_context[sock], sock);
644 if(SSL_connect(_ssl_context[sock]) == -1) {
645 ERR_print_errors_fp(stderr);
653 int SockClose(int sock)
654 /* close a socket gracefully */
660 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
661 /* Clean up the SSL stack */
662 SSL_free( _ssl_context[sock] );
663 _ssl_context[sock] = NULL;
667 /* Half-close the connection first so the other end gets notified.
669 * This stops sends but allows receives (effectively, it sends a
672 if (shutdown(sock, 1) == 0)
673 /* If there is any data still waiting in the queue, discard it.
674 * Call recv() until either it returns 0 (meaning we received a FIN)
675 * or any error occurs. This makes sure all data sent by the other
676 * side is acknowledged at the TCP level.
678 if (recv(sock, &ch, 1, MSG_PEEK) > 0)
679 while (read(sock, &ch, 1) > 0)
682 /* if there's an error closing at this point, not much we can do */
683 return(close(sock)); /* this is guarded */
688 * Use the chargen service to test input buffering directly.
689 * You may have to uncomment the `chargen' service description in your
690 * inetd.conf (and then SIGHUP inetd) for this to work. */
693 int sock = SockOpen("localhost", 19, NULL);
696 while (SockRead(sock, buf, sizeof(buf)-1))
697 SockWrite(1, buf, strlen(buf));
702 /* socket.c ends here */