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, *ai0, 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, &ai0)) {
139 report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
147 if (net_security_strtorequest((char *)options, &request, &requestlen))
150 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
155 #else /* NET_SECURITY */
156 #ifdef HAVE_INNER_CONNECT
157 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
162 for (ai = ai0; ai; ai = ai->ai_next) {
163 i = socket(ai->ai_family, ai->ai_socktype, 0);
166 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
174 #endif /* NET_SECURITY */
180 #else /* INET6_ENABLE */
181 #ifndef HAVE_INET_ATON
183 #ifdef INADDR_BROADCAST
184 #define INADDR_NONE INADDR_BROADCAST
186 #define INADDR_NONE -1
189 #endif /* HAVE_INET_ATON */
191 int SockOpen(const char *host, int clientPort, const char *options,
194 int sock = -1; /* pacify -Wall */
195 #ifndef HAVE_INET_ATON
196 unsigned long inaddr;
197 #endif /* HAVE_INET_ATON */
198 struct sockaddr_in ad, **pptr;
201 #ifdef HAVE_SOCKETPAIR
204 sprintf(buf,"%d",clientPort);
205 return handle_plugin(host,buf,plugin);
207 #endif /* HAVE_SOCKETPAIR */
209 memset(&ad, 0, sizeof(ad));
210 ad.sin_family = AF_INET;
212 /* we'll accept a quad address */
213 #ifndef HAVE_INET_ATON
214 inaddr = inet_addr(host);
215 if (inaddr != INADDR_NONE)
217 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
219 if (inet_aton(host, &ad.sin_addr))
221 #endif /* HAVE_INET_ATON */
222 ad.sin_port = htons(clientPort);
224 sock = socket(AF_INET, SOCK_STREAM, 0);
230 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
233 close(sock); /* don't use SockClose, no traffic yet */
238 #ifndef HAVE_INET_ATON
242 #endif /* HAVE_INET_ATON */
244 hp = gethostbyname(host);
252 * Add a check to make sure the address has a valid IPv4 or IPv6
253 * length. This prevents buffer spamming by a broken DNS.
255 if(hp->h_length != 4 && hp->h_length != 8)
259 _("fetchmail: illegal address length received for host %s\n"),host);
263 * Try all addresses of a possibly multihomed host until we get
264 * a successful connect or until we run out of addresses.
266 pptr = (struct sockaddr_in **)hp->h_addr_list;
267 for(; *pptr != NULL; pptr++)
269 sock = socket(AF_INET, SOCK_STREAM, 0);
275 ad.sin_port = htons(clientPort);
276 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
277 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
279 close(sock); /* don't use SockClose, no traffic yet */
280 memset(&ad, 0, sizeof(ad));
281 ad.sin_family = AF_INET;
286 close(sock); /* don't use SockClose, no traffic yet */
294 #endif /* INET6_ENABLE */
297 #if defined(HAVE_STDARG_H)
298 int SockPrintf(int sock, const char* format, ...)
301 int SockPrintf(sock,format,va_alist)
310 #if defined(HAVE_STDARG_H)
311 va_start(ap, format) ;
315 #ifdef HAVE_VSNPRINTF
316 vsnprintf(buf, sizeof(buf), format, ap);
318 vsprintf(buf, format, ap);
321 return SockWrite(sock, buf, strlen(buf));
331 static SSL_CTX *_ctx = NULL;
332 static SSL *_ssl_context[FD_SETSIZE];
334 SSL *SSLGetContext( int );
335 #endif /* SSL_ENABLE */
337 int SockWrite(int sock, char *buf, int len)
347 if( NULL != ( ssl = SSLGetContext( sock ) ) )
348 n = SSL_write(ssl, buf, len);
350 n = write(sock, buf, len);
352 n = write(sock, buf, len);
363 int SockRead(int sock, char *buf, int len)
365 char *newline, *bp = buf;
375 * The reason for these gymnastics is that we want two things:
376 * (1) to read \n-terminated lines,
377 * (2) to return the true length of data read, even if the
378 * data coming in has embedded NULS.
381 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
383 /* OK... SSL_peek works a little different from MSG_PEEK
384 Problem is that SSL_peek can return 0 if there
385 is no data currently available. If, on the other
386 hand, we loose the socket, we also get a zero, but
387 the SSL_read then SEGFAULTS! To deal with this,
388 we'll check the error code any time we get a return
389 of zero from SSL_peek. If we have an error, we bail.
390 If we don't, we read one character in SSL_read and
391 loop. This should continue to work even if they
392 later change the behavior of SSL_peek
393 to "fix" this problem... :-( */
394 if ((n = SSL_peek(ssl, bp, len)) < 0) {
398 /* SSL_peek says no data... Does he mean no data
399 or did the connection blow up? If we got an error
401 if( 0 != ( n = ERR_get_error() ) ) {
404 /* We didn't get an error so read at least one
405 character at this point and loop */
407 /* Make sure newline start out NULL!
408 * We don't have a string to pass through
409 * the strchr at this point yet */
411 } else if ((newline = memchr(bp, '\n', n)) != NULL)
412 n = newline - bp + 1;
413 if ((n = SSL_read(ssl, bp, n)) == -1) {
416 /* Check for case where our single character turned out to
417 * be a newline... (It wasn't going to get caught by
418 * the strchr above if it came from the hack... ). */
419 if( NULL == newline && 1 == n && '\n' == *bp ) {
420 /* Got our newline - this will break
421 out of the loop now */
425 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
427 if ((newline = memchr(bp, '\n', n)) != NULL)
428 n = newline - bp + 1;
429 if ((n = read(sock, bp, n)) == -1)
433 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
435 if ((newline = memchr(bp, '\n', n)) != NULL)
436 n = newline - bp + 1;
437 if ((n = read(sock, bp, n)) == -1)
448 int SockPeek(int sock)
449 /* peek at the next socket character without actually reading it */
458 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
459 n = SSL_peek(ssl, &ch, 1);
461 /* This code really needs to implement a "hold back"
462 * to simulate a functioning SSL_peek()... sigh...
463 * Has to be coordinated with the read code above.
464 * Next on the list todo... */
466 /* SSL_peek says no data... Does he mean no data
467 or did the connection blow up? If we got an error
469 if( 0 != ( n = ERR_get_error() ) ) {
473 /* Haven't seen this case actually occur, but...
474 if the problem in SockRead can occur, this should
475 be possible... Just not sure what to do here.
476 This should be a safe "punt" the "peek" but don't
477 "punt" the "session"... */
479 return 0; /* Give him a '\0' character */
482 n = recv(sock, &ch, 1, MSG_PEEK);
485 n = recv(sock, &ch, 1, MSG_PEEK);
495 static char *_ssl_server_cname = NULL;
497 SSL *SSLGetContext( int sock )
499 /* If SSLOpen has never initialized - just return NULL */
503 if( sock < 0 || sock > FD_SETSIZE )
505 return _ssl_context[sock];
509 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
518 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
519 err = X509_STORE_CTX_get_error(ctx);
520 depth = X509_STORE_CTX_get_error_depth(ctx);
522 X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
523 X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
525 /* Just to be sure those buffers are terminated... I think the
526 X509 libraries do, but... */
527 buf[256] = ibuf[256] = '\0';
530 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
532 strcpy( cbuf, str_ptr );
533 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
536 if (outlevel == O_VERBOSE)
537 report(stdout, "Issuer Organization: %s\n", cbuf );
539 if (outlevel == O_VERBOSE)
540 report(stdout, "Unknown Organization\n", cbuf );
542 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
544 strcpy( cbuf, str_ptr );
545 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
548 if (outlevel == O_VERBOSE)
549 report(stdout, "Issuer CommonName: %s\n", cbuf );
551 if (outlevel == O_VERBOSE)
552 report(stdout, "Unknown Issuer CommonName\n", cbuf );
554 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
556 strcpy( cbuf, str_ptr );
557 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
560 if (outlevel == O_VERBOSE)
561 report(stdout, "Server CommonName: %s\n", cbuf );
562 /* Should we have some wildcarding here? */
563 if ( NULL != _ssl_server_cname
564 && 0 != strcmp( cbuf, _ssl_server_cname ) ) {
566 "Server CommonName mismatch: %s != %s\n",
567 cbuf, _ssl_server_cname );
570 if (outlevel == O_VERBOSE)
571 report(stdout, "Unknown Server CommonName\n", cbuf );
575 switch (ctx->error) {
576 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
577 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
578 report(stdout, "unknown issuer= %s", buf);
580 case X509_V_ERR_CERT_NOT_YET_VALID:
581 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
582 report(stderr, "Server Certificate not yet valid");
584 case X509_V_ERR_CERT_HAS_EXPIRED:
585 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
586 report(stderr, "Server Certificate expired");
589 /* We are not requiring or validating server or issuer id's as yet */
590 /* Always return OK from here */
596 /* performs initial SSL handshake over the connected socket
597 * uses SSL *ssl global variable, which is currently defined
600 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
602 SSL_load_error_strings();
603 SSLeay_add_ssl_algorithms();
605 if( sock < 0 || sock > FD_SETSIZE ) {
606 report(stderr, "File descriptor out of range for SSL" );
611 /* Be picky and make sure the memory is cleared */
612 memset( _ssl_context, 0, sizeof( _ssl_context ) );
613 _ctx = SSL_CTX_new(SSLv23_client_method());
615 ERR_print_errors_fp(stderr);
620 _ssl_context[sock] = SSL_new(_ctx);
622 if(_ssl_context[sock] == NULL) {
623 ERR_print_errors_fp(stderr);
627 /* This static is for the verify callback */
628 _ssl_server_cname = servercname;
630 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
632 if( mycert || mykey ) {
634 /* Ok... He has a certificate file defined, so lets declare it. If
635 * he does NOT have a separate certificate and private key file then
636 * assume that it's a combined key and certificate file.
642 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
643 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
646 SSL_set_fd(_ssl_context[sock], sock);
648 if(SSL_connect(_ssl_context[sock]) == -1) {
649 ERR_print_errors_fp(stderr);
657 int SockClose(int sock)
658 /* close a socket gracefully */
664 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
665 /* Clean up the SSL stack */
666 SSL_free( _ssl_context[sock] );
667 _ssl_context[sock] = NULL;
671 /* Half-close the connection first so the other end gets notified.
673 * This stops sends but allows receives (effectively, it sends a
676 if (shutdown(sock, 1) == 0)
677 /* If there is any data still waiting in the queue, discard it.
678 * Call recv() until either it returns 0 (meaning we received a FIN)
679 * or any error occurs. This makes sure all data sent by the other
680 * side is acknowledged at the TCP level.
682 if (recv(sock, &ch, 1, MSG_PEEK) > 0)
683 while (read(sock, &ch, 1) > 0)
686 /* if there's an error closing at this point, not much we can do */
687 return(close(sock)); /* this is guarded */
692 * Use the chargen service to test input buffering directly.
693 * You may have to uncomment the `chargen' service description in your
694 * inetd.conf (and then SIGHUP inetd) for this to work. */
697 int sock = SockOpen("localhost", 19, NULL);
700 while (SockRead(sock, buf, sizeof(buf)-1))
701 SockWrite(1, buf, strlen(buf));
706 /* socket.c ends here */