]> Pileus Git - ~andy/fetchmail/blob - socket.c
Fix for IPv6.
[~andy/fetchmail] / socket.c
1 /*
2  * socket.c -- socket library functions
3  *
4  * Copyright 1998 by Eric S. Raymond.
5  * For license terms, see the file COPYING in this directory.
6  */
7
8 #include "config.h"
9 #include <stdio.h>
10 #include <errno.h>
11 #include <string.h>
12 #ifdef HAVE_MEMORY_H
13 #include <memory.h>
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>
19 #include <netdb.h>
20 #if defined(STDC_HEADERS)
21 #include <stdlib.h>
22 #endif
23 #if defined(HAVE_UNISTD_H)
24 #include <unistd.h>
25 #endif
26 #if defined(HAVE_STDARG_H)
27 #include <stdarg.h>
28 #else
29 #include <varargs.h>
30 #endif
31 #include "socket.h"
32 #include "fetchmail.h"
33 #include "i18n.h"
34
35 /* We need to define h_errno only if it is not already */
36 #ifndef h_errno
37
38 #ifdef HAVE_RES_SEARCH
39 /* some versions of FreeBSD should declare this but don't */
40 extern int h_errno;
41 #else
42 /* pretend we have h_errno to avoid some #ifdef's later */
43 static int h_errno;
44 #endif
45
46 #endif /* ndef h_errno */
47
48 #if NET_SECURITY
49 #include <net/security.h>
50 #endif /* NET_SECURITY */
51
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 */
56 {
57     int fds[2];
58     if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
59     {
60         report(stderr, _("fetchmail: socketpair failed\n"));
61         return -1;
62     }
63     switch (fork()) {
64         case -1:
65                 /* error */
66                 report(stderr, _("fetchmail: fork failed\n"));
67                 return -1;
68                 break;
69         case 0: /* child */
70                 /* fds[1] is the parent's end; close it for proper EOF
71                 ** detection */
72                 (void) close(fds[1]);
73                 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
74                         report(stderr, _("dup2 failed\n"));
75                         exit(1);
76                 }
77                 /* fds[0] is now connected to 0 and 1; close it */
78                 (void) close(fds[0]);
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);
83                 exit(0);
84                 break;
85         default:        /* parent */
86                 /* NOP */
87                 break;
88     }
89     /* fds[0] is the child's end; close it for proper EOF detection */
90     (void) close(fds[0]);
91     return fds[1];
92 }
93 #endif /* HAVE_SOCKETPAIR */
94
95 #ifdef __UNUSED__
96 #include <sys/time.h>
97
98 int SockCheckOpen(int fd)
99 /* poll given socket; is it selectable? */
100 {
101     fd_set r, w, e;
102     int rt;
103     struct timeval tv;
104   
105     for (;;) 
106     {
107         FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
108         FD_SET(fd, &e);
109     
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))
113             return 0;
114         if (rt != -1)
115             return 1;
116     }
117 }
118 #endif /* __UNUSED__ */
119
120 #if INET6_ENABLE
121 int SockOpen(const char *host, const char *service, const char *options,
122              const char *plugin)
123 {
124     struct addrinfo *ai, *ai0, req;
125     int i;
126 #if NET_SECURITY
127     void *request = NULL;
128     int requestlen;
129 #endif /* NET_SECURITY */
130
131 #ifdef HAVE_SOCKETPAIR
132     if (plugin)
133         return handle_plugin(host,service,plugin);
134 #endif /* HAVE_SOCKETPAIR */
135     memset(&req, 0, sizeof(struct addrinfo));
136     req.ai_socktype = SOCK_STREAM;
137
138     if (getaddrinfo(host, service, &req, &ai0)) {
139         report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
140         return -1;
141     }
142
143 #if NET_SECURITY
144     if (!options)
145         requestlen = 0;
146     else
147         if (net_security_strtorequest((char *)options, &request, &requestlen))
148             goto ret;
149
150     i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
151     if (request)
152         free(request);
153
154  ret:
155 #else /* NET_SECURITY */
156 #ifdef HAVE_INNER_CONNECT
157     i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
158     if (i >= 0)
159         break;
160 #else
161     i = -1;
162     for (ai = ai0; ai; ai = ai->ai_next) {
163         i = socket(ai->ai_family, ai->ai_socktype, 0);
164         if (i < 0)
165             continue;
166         if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
167             close(i);
168             i = -1;
169             continue;
170         }
171         break;
172     }
173 #endif
174 #endif /* NET_SECURITY */
175
176     freeaddrinfo(ai0);
177
178     return i;
179 }
180 #else /* INET6_ENABLE */
181 #ifndef HAVE_INET_ATON
182 #ifndef  INADDR_NONE
183 #ifdef   INADDR_BROADCAST
184 #define  INADDR_NONE    INADDR_BROADCAST
185 #else
186 #define  INADDR_NONE    -1
187 #endif
188 #endif
189 #endif /* HAVE_INET_ATON */
190
191 int SockOpen(const char *host, int clientPort, const char *options,
192              const char *plugin)
193 {
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;
199     struct hostent *hp;
200
201 #ifdef HAVE_SOCKETPAIR
202     if (plugin) {
203       char buf[10];
204       sprintf(buf,"%d",clientPort);
205       return handle_plugin(host,buf,plugin);
206     }
207 #endif /* HAVE_SOCKETPAIR */
208
209     memset(&ad, 0, sizeof(ad));
210     ad.sin_family = AF_INET;
211
212     /* we'll accept a quad address */
213 #ifndef HAVE_INET_ATON
214     inaddr = inet_addr(host);
215     if (inaddr != INADDR_NONE)
216     {
217         memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
218 #else
219     if (inet_aton(host, &ad.sin_addr))
220     {
221 #endif /* HAVE_INET_ATON */
222         ad.sin_port = htons(clientPort);
223
224         sock = socket(AF_INET, SOCK_STREAM, 0);
225         if (sock < 0)
226         {
227             h_errno = 0;
228             return -1;
229         }
230         if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
231         {
232             int olderr = errno;
233             close(sock);        /* don't use SockClose, no traffic yet */
234             h_errno = 0;
235             errno = olderr;
236             return -1;
237         }
238 #ifndef HAVE_INET_ATON
239     }
240 #else
241     }
242 #endif /* HAVE_INET_ATON */
243     else {
244         hp = gethostbyname(host);
245
246         if (hp == NULL)
247         {
248             errno = 0;
249             return -1;
250         }
251         /*
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.
254          */
255         if(hp->h_length != 4 && hp->h_length != 8)
256         {
257             h_errno = errno = 0;
258             report(stderr, 
259                    _("fetchmail: illegal address length received for host %s\n"),host);
260             return -1;
261         }
262         /*
263          * Try all addresses of a possibly multihomed host until we get
264          * a successful connect or until we run out of addresses.
265          */
266         pptr = (struct sockaddr_in **)hp->h_addr_list;
267         for(; *pptr != NULL; pptr++)
268         {
269             sock = socket(AF_INET, SOCK_STREAM, 0);
270             if (sock < 0)
271             {
272                 h_errno = 0;
273                 return -1;
274             }
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)
278                 break; /* success */
279             close(sock);        /* don't use SockClose, no traffic yet */
280             memset(&ad, 0, sizeof(ad));
281             ad.sin_family = AF_INET;
282         }
283         if(*pptr == NULL)
284         {
285             int olderr = errno;
286             close(sock);        /* don't use SockClose, no traffic yet */
287             h_errno = 0;
288             errno = olderr;
289             return -1;
290         }
291     }
292     return(sock);
293 }
294 #endif /* INET6_ENABLE */
295
296
297 #if defined(HAVE_STDARG_H)
298 int SockPrintf(int sock, const char* format, ...)
299 {
300 #else
301 int SockPrintf(sock,format,va_alist)
302 int sock;
303 char *format;
304 va_dcl {
305 #endif
306
307     va_list ap;
308     char buf[8192];
309
310 #if defined(HAVE_STDARG_H)
311     va_start(ap, format) ;
312 #else
313     va_start(ap);
314 #endif
315 #ifdef HAVE_VSNPRINTF
316     vsnprintf(buf, sizeof(buf), format, ap);
317 #else
318     vsprintf(buf, format, ap);
319 #endif
320     va_end(ap);
321     return SockWrite(sock, buf, strlen(buf));
322
323 }
324
325 #ifdef SSL_ENABLE
326 #include "ssl.h"
327 #include "err.h"
328 #include "pem.h"
329 #include "x509.h"
330
331 static  SSL_CTX *_ctx = NULL;
332 static  SSL *_ssl_context[FD_SETSIZE];
333
334 SSL     *SSLGetContext( int );
335 #endif /* SSL_ENABLE */
336
337 int SockWrite(int sock, char *buf, int len)
338 {
339     int n, wrlen = 0;
340 #ifdef  SSL_ENABLE
341     SSL *ssl;
342 #endif
343
344     while (len)
345     {
346 #ifdef SSL_ENABLE
347         if( NULL != ( ssl = SSLGetContext( sock ) ) )
348                 n = SSL_write(ssl, buf, len);
349         else
350                 n = write(sock, buf, len);
351 #else
352         n = write(sock, buf, len);
353 #endif
354         if (n <= 0)
355             return -1;
356         len -= n;
357         wrlen += n;
358         buf += n;
359     }
360     return wrlen;
361 }
362
363 int SockRead(int sock, char *buf, int len)
364 {
365     char *newline, *bp = buf;
366     int n;
367 #ifdef  SSL_ENABLE
368     SSL *ssl;
369 #endif
370
371     if (--len < 1)
372         return(-1);
373     do {
374         /* 
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.
379          */
380 #ifdef  SSL_ENABLE
381         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
382                 /* Hack alert! */
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) {
395                         return(-1);
396                 }
397                 if( 0 == n ) {
398                         /* SSL_peek says no data...  Does he mean no data
399                         or did the connection blow up?  If we got an error
400                         then bail! */
401                         if( 0 != ( n = ERR_get_error() ) ) {
402                                 return -1;
403                         }
404                         /* We didn't get an error so read at least one
405                                 character at this point and loop */
406                         n = 1;
407                         /* Make sure newline start out NULL!
408                          * We don't have a string to pass through
409                          * the strchr at this point yet */
410                         newline = NULL;
411                 } else if ((newline = memchr(bp, '\n', n)) != NULL)
412                         n = newline - bp + 1;
413                 if ((n = SSL_read(ssl, bp, n)) == -1) {
414                         return(-1);
415                 }
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 */
422                         newline = bp;
423                 }
424         } else {
425                 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
426                         return(-1);
427                 if ((newline = memchr(bp, '\n', n)) != NULL)
428                         n = newline - bp + 1;
429                 if ((n = read(sock, bp, n)) == -1)
430                         return(-1);
431         }
432 #else
433         if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
434             return(-1);
435         if ((newline = memchr(bp, '\n', n)) != NULL)
436             n = newline - bp + 1;
437         if ((n = read(sock, bp, n)) == -1)
438             return(-1);
439 #endif
440         bp += n;
441         len -= n;
442     } while 
443             (!newline && len);
444     *bp = '\0';
445     return bp - buf;
446 }
447
448 int SockPeek(int sock)
449 /* peek at the next socket character without actually reading it */
450 {
451     int n;
452     char ch;
453 #ifdef  SSL_ENABLE
454     SSL *ssl;
455 #endif
456
457 #ifdef  SSL_ENABLE
458         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
459                 n = SSL_peek(ssl, &ch, 1);
460                 if( 0 == n ) {
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...     */
465
466                         /* SSL_peek says no data...  Does he mean no data
467                         or did the connection blow up?  If we got an error
468                         then bail! */
469                         if( 0 != ( n = ERR_get_error() ) ) {
470                                 return -1;
471                         }
472
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"... */
478
479                         return 0;       /* Give him a '\0' character */
480                 }
481         } else {
482                 n = recv(sock, &ch, 1, MSG_PEEK);
483         }
484 #else
485         n = recv(sock, &ch, 1, MSG_PEEK);
486 #endif
487         if (n == -1)
488                 return -1;
489         else
490                 return(ch);
491 }
492
493 #ifdef SSL_ENABLE
494
495 static  char *_ssl_server_cname = NULL;
496
497 SSL *SSLGetContext( int sock )
498 {
499         /* If SSLOpen has never initialized - just return NULL */
500         if( NULL == _ctx )
501                 return NULL;
502
503         if( sock < 0 || sock > FD_SETSIZE )
504                 return NULL;
505         return _ssl_context[sock];
506 }
507
508
509 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
510 {
511         char buf[260];
512         char cbuf[260];
513         char ibuf[260];
514         char *str_ptr;
515         X509 *x509_cert;
516         int err, depth;
517
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);
521
522         X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
523         X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
524
525         /* Just to be sure those buffers are terminated...  I think the
526                 X509 libraries do, but... */
527         buf[256] = ibuf[256] = '\0';
528
529         if (depth == 0) {
530                 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
531                         str_ptr += 3;
532                         strcpy( cbuf, str_ptr );
533                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
534                                 *str_ptr = '\0';
535                         }
536                         if (outlevel == O_VERBOSE)
537                                 report(stdout, "Issuer Organization: %s\n", cbuf );
538                 } else {
539                         if (outlevel == O_VERBOSE)
540                                 report(stdout, "Unknown Organization\n", cbuf );
541                 }
542                 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
543                         str_ptr += 4;
544                         strcpy( cbuf, str_ptr );
545                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
546                                 *str_ptr = '\0';
547                         }
548                         if (outlevel == O_VERBOSE)
549                                 report(stdout, "Issuer CommonName: %s\n", cbuf );
550                 } else {
551                         if (outlevel == O_VERBOSE)
552                                 report(stdout, "Unknown Issuer CommonName\n", cbuf );
553                 }
554                 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
555                         str_ptr += 4;
556                         strcpy( cbuf, str_ptr );
557                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
558                                 *str_ptr = '\0';
559                         }
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 ) ) {
565                                 report(stdout,
566                                        "Server CommonName mismatch: %s != %s\n",
567                                        cbuf, _ssl_server_cname );
568                         }
569                 } else {
570                         if (outlevel == O_VERBOSE)
571                                 report(stdout, "Unknown Server CommonName\n", cbuf );
572                 }
573         }
574
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);
579                 break;
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");
583                 break;
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");
587                 break;
588         }
589         /* We are not requiring or validating server or issuer id's as yet */
590         /* Always return OK from here */
591         ok_return = 1;
592         return( ok_return );
593 }
594
595
596 /* performs initial SSL handshake over the connected socket
597  * uses SSL *ssl global variable, which is currently defined
598  * in this file
599  */
600 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
601 {
602         SSL_load_error_strings();
603         SSLeay_add_ssl_algorithms();
604         
605         if( sock < 0 || sock > FD_SETSIZE ) {
606                 report(stderr, "File descriptor out of range for SSL" );
607                 return( -1 );
608         }
609
610         if( ! _ctx ) {
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());
614                 if(_ctx == NULL) {
615                         ERR_print_errors_fp(stderr);
616                         return(-1);
617                 }
618         }
619         
620         _ssl_context[sock] = SSL_new(_ctx);
621         
622         if(_ssl_context[sock] == NULL) {
623                 ERR_print_errors_fp(stderr);
624                 return(-1);
625         }
626         
627         /* This static is for the verify callback */
628         _ssl_server_cname = servercname;
629
630         SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
631
632         if( mycert || mykey ) {
633
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.
637          */
638                 if( !mykey )
639                         mykey = mycert;
640                 if( !mycert )
641                         mycert = mykey;
642                 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
643                 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
644         }
645
646         SSL_set_fd(_ssl_context[sock], sock);
647         
648         if(SSL_connect(_ssl_context[sock]) == -1) {
649                 ERR_print_errors_fp(stderr);
650                 return(-1);
651         }
652         
653         return(0);
654 }
655 #endif
656
657 int SockClose(int sock)
658 /* close a socket gracefully */
659 {
660     char ch;
661 #ifdef  SSL_ENABLE
662     SSL *ssl;
663
664     if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
665         /* Clean up the SSL stack */
666         SSL_free( _ssl_context[sock] );
667         _ssl_context[sock] = NULL;
668     }
669 #endif
670
671     /* Half-close the connection first so the other end gets notified.
672      *
673      * This stops sends but allows receives (effectively, it sends a
674      * TCP <FIN>).
675      */
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.
681          */
682         if (recv(sock, &ch, 1, MSG_PEEK) > 0)
683             while (read(sock, &ch, 1) > 0)
684                 continue;
685
686     /* if there's an error closing at this point, not much we can do */
687     return(close(sock));        /* this is guarded */
688 }
689
690 #ifdef MAIN
691 /*
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.  */
695 main()
696 {
697     int         sock = SockOpen("localhost", 19, NULL);
698     char        buf[80];
699
700     while (SockRead(sock, buf, sizeof(buf)-1))
701         SockWrite(1, buf, strlen(buf));
702     SockClose(sock);
703 }
704 #endif /* MAIN */
705
706 /* socket.c ends here */