]> Pileus Git - ~andy/fetchmail/blob - socket.c
IPv6 patches.
[~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, req;
125     int i;
126 #if NET_SECURITY
127     void *request = NULL;
128     int requestlen;
129 #endif /* NET_SECURITY */
130     int i;
131
132 #ifdef HAVE_SOCKETPAIR
133     if (plugin)
134         return handle_plugin(host,service,plugin);
135 #endif /* HAVE_SOCKETPAIR */
136     memset(&req, 0, sizeof(struct addrinfo));
137     req.ai_socktype = SOCK_STREAM;
138
139     if (getaddrinfo(host, service, &req, &ai)) {
140         report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
141         return -1;
142     };
143
144 #if NET_SECURITY
145     if (!options)
146         requestlen = 0;
147     else
148         if (net_security_strtorequest((char *)options, &request, &requestlen))
149             goto ret;
150
151     i = inner_connect(ai, request, requestlen, NULL, NULL, "fetchmail", NULL);
152     if (request)
153         free(request);
154
155  ret:
156 #else /* NET_SECURITY */
157     i = inner_connect(ai, NULL, 0, NULL, NULL, "fetchmail", NULL);
158 #endif /* NET_SECURITY */
159
160     freeaddrinfo(ai);
161
162     return i;
163 };
164 #else /* INET6_ENABLE */
165 #ifndef HAVE_INET_ATON
166 #ifndef  INADDR_NONE
167 #ifdef   INADDR_BROADCAST
168 #define  INADDR_NONE    INADDR_BROADCAST
169 #else
170 #define  INADDR_NONE    -1
171 #endif
172 #endif
173 #endif /* HAVE_INET_ATON */
174
175 int SockOpen(const char *host, int clientPort, const char *options,
176              const char *plugin)
177 {
178     int sock = -1;      /* pacify -Wall */
179 #ifndef HAVE_INET_ATON
180     unsigned long inaddr;
181 #endif /* HAVE_INET_ATON */
182     struct sockaddr_in ad, **pptr;
183     struct hostent *hp;
184
185 #ifdef HAVE_SOCKETPAIR
186     if (plugin) {
187       char buf[10];
188       sprintf(buf,"%d",clientPort);
189       return handle_plugin(host,buf,plugin);
190     }
191 #endif /* HAVE_SOCKETPAIR */
192
193     memset(&ad, 0, sizeof(ad));
194     ad.sin_family = AF_INET;
195
196     /* we'll accept a quad address */
197 #ifndef HAVE_INET_ATON
198     inaddr = inet_addr(host);
199     if (inaddr != INADDR_NONE)
200     {
201         memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
202 #else
203     if (inet_aton(host, &ad.sin_addr))
204     {
205 #endif /* HAVE_INET_ATON */
206         ad.sin_port = htons(clientPort);
207
208         sock = socket(AF_INET, SOCK_STREAM, 0);
209         if (sock < 0)
210         {
211             h_errno = 0;
212             return -1;
213         }
214         if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
215         {
216             int olderr = errno;
217             close(sock);
218             h_errno = 0;
219             errno = olderr;
220             return -1;
221         }
222 #ifndef HAVE_INET_ATON
223     }
224 #else
225     }
226 #endif /* HAVE_INET_ATON */
227     else {
228         hp = gethostbyname(host);
229
230         if (hp == NULL)
231         {
232             errno = 0;
233             return -1;
234         }
235         /*
236          * Add a check to make sure the address has a valid IPv4 or IPv6
237          * length.  This prevents buffer spamming by a broken DNS.
238          */
239         if(hp->h_length != 4 && hp->h_length != 8)
240         {
241             h_errno = errno = 0;
242             report(stderr, 
243                    _("fetchmail: illegal address length received for host %s\n"),host);
244             return -1;
245         }
246         /*
247          * Try all addresses of a possibly multihomed host until we get
248          * a successful connect or until we run out of addresses.
249          */
250         pptr = (struct sockaddr_in **)hp->h_addr_list;
251         for(; *pptr != NULL; pptr++)
252         {
253             sock = socket(AF_INET, SOCK_STREAM, 0);
254             if (sock < 0)
255             {
256                 h_errno = 0;
257                 return -1;
258             }
259             ad.sin_port = htons(clientPort);
260             memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
261             if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
262                 break; /* success */
263             close(sock);
264             memset(&ad, 0, sizeof(ad));
265             ad.sin_family = AF_INET;
266         }
267         if(*pptr == NULL)
268         {
269             int olderr = errno;
270             close(sock);
271             h_errno = 0;
272             errno = olderr;
273             return -1;
274         }
275     }
276     return(sock);
277 }
278 #endif /* INET6_ENABLE */
279
280
281 #if defined(HAVE_STDARG_H)
282 int SockPrintf(int sock, const char* format, ...)
283 {
284 #else
285 int SockPrintf(sock,format,va_alist)
286 int sock;
287 char *format;
288 va_dcl {
289 #endif
290
291     va_list ap;
292     char buf[8192];
293
294 #if defined(HAVE_STDARG_H)
295     va_start(ap, format) ;
296 #else
297     va_start(ap);
298 #endif
299 #ifdef HAVE_VSNPRINTF
300     vsnprintf(buf, sizeof(buf), format, ap);
301 #else
302     vsprintf(buf, format, ap);
303 #endif
304     va_end(ap);
305     return SockWrite(sock, buf, strlen(buf));
306
307 }
308
309 #ifdef SSL_ENABLE
310 #include "ssl.h"
311 #include "err.h"
312 #include "pem.h"
313 #include "x509.h"
314
315 static  SSL_CTX *_ctx = NULL;
316 static  SSL *_ssl_context[FD_SETSIZE];
317
318 SSL     *SSLGetContext( int );
319 #endif /* SSL_ENABLE */
320
321 int SockWrite(int sock, char *buf, int len)
322 {
323     int n, wrlen = 0;
324 #ifdef  SSL_ENABLE
325     SSL *ssl;
326 #endif
327
328     while (len)
329     {
330 #ifdef SSL_ENABLE
331         if( NULL != ( ssl = SSLGetContext( sock ) ) )
332                 n = SSL_write(ssl, buf, len);
333         else
334                 n = write(sock, buf, len);
335 #else
336         n = write(sock, buf, len);
337 #endif
338         if (n <= 0)
339             return -1;
340         len -= n;
341         wrlen += n;
342         buf += n;
343     }
344     return wrlen;
345 }
346
347 int SockRead(int sock, char *buf, int len)
348 {
349     char *newline, *bp = buf;
350     int n;
351 #ifdef  SSL_ENABLE
352     SSL *ssl;
353 #endif
354
355     if (--len < 1)
356         return(-1);
357     do {
358         /* 
359          * The reason for these gymnastics is that we want two things:
360          * (1) to read \n-terminated lines,
361          * (2) to return the true length of data read, even if the
362          *     data coming in has embedded NULS.
363          */
364 #ifdef  SSL_ENABLE
365         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
366                 /* Hack alert! */
367                 /* OK...  SSL_peek works a little different from MSG_PEEK
368                         Problem is that SSL_peek can return 0 if there
369                         is no data currently available.  If, on the other
370                         hand, we loose the socket, we also get a zero, but
371                         the SSL_read then SEGFAULTS!  To deal with this,
372                         we'll check the error code any time we get a return
373                         of zero from SSL_peek.  If we have an error, we bail.
374                         If we don't, we read one character in SSL_read and
375                         loop.  This should continue to work even if they
376                         later change the behavior of SSL_peek
377                         to "fix" this problem...  :-(   */
378                 if ((n = SSL_peek(ssl, bp, len)) < 0) {
379                         return(-1);
380                 }
381                 if( 0 == n ) {
382                         /* SSL_peek says no data...  Does he mean no data
383                         or did the connection blow up?  If we got an error
384                         then bail! */
385                         if( 0 != ( n = ERR_get_error() ) ) {
386                                 return -1;
387                         }
388                         /* We didn't get an error so read at least one
389                                 character at this point and loop */
390                         n = 1;
391                         /* Make sure newline start out NULL!
392                          * We don't have a string to pass through
393                          * the strchr at this point yet */
394                         newline = NULL;
395                 } else if ((newline = memchr(bp, '\n', n)) != NULL)
396                         n = newline - bp + 1;
397                 if ((n = SSL_read(ssl, bp, n)) == -1) {
398                         return(-1);
399                 }
400                 /* Check for case where our single character turned out to
401                  * be a newline...  (It wasn't going to get caught by
402                  * the strchr above if it came from the hack...  ). */
403                 if( NULL == newline && 1 == n && '\n' == *bp ) {
404                         /* Got our newline - this will break
405                                 out of the loop now */
406                         newline = bp;
407                 }
408         } else {
409                 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
410                         return(-1);
411                 if ((newline = memchr(bp, '\n', n)) != NULL)
412                         n = newline - bp + 1;
413                 if ((n = read(sock, bp, n)) == -1)
414                         return(-1);
415         }
416 #else
417         if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
418             return(-1);
419         if ((newline = memchr(bp, '\n', n)) != NULL)
420             n = newline - bp + 1;
421         if ((n = read(sock, bp, n)) == -1)
422             return(-1);
423 #endif
424         bp += n;
425         len -= n;
426     } while 
427             (!newline && len);
428     *bp = '\0';
429     return bp - buf;
430 }
431
432 int SockPeek(int sock)
433 /* peek at the next socket character without actually reading it */
434 {
435     int n;
436     char ch;
437 #ifdef  SSL_ENABLE
438     SSL *ssl;
439 #endif
440
441 #ifdef  SSL_ENABLE
442         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
443                 n = SSL_peek(ssl, &ch, 1);
444                 if( 0 == n ) {
445                         /* This code really needs to implement a "hold back"
446                          * to simulate a functioning SSL_peek()...  sigh...
447                          * Has to be coordinated with the read code above.
448                          * Next on the list todo...     */
449
450                         /* SSL_peek says no data...  Does he mean no data
451                         or did the connection blow up?  If we got an error
452                         then bail! */
453                         if( 0 != ( n = ERR_get_error() ) ) {
454                                 return -1;
455                         }
456
457                         /* Haven't seen this case actually occur, but...
458                            if the problem in SockRead can occur, this should
459                            be possible...  Just not sure what to do here.
460                            This should be a safe "punt" the "peek" but don't
461                            "punt" the "session"... */
462
463                         return 0;       /* Give him a '\0' character */
464                 }
465         } else {
466                 n = recv(sock, &ch, 1, MSG_PEEK);
467         }
468 #else
469         n = recv(sock, &ch, 1, MSG_PEEK);
470 #endif
471         if (n == -1)
472                 return -1;
473         else
474                 return(ch);
475 }
476
477 #ifdef SSL_ENABLE
478
479 static  char *_ssl_server_cname = NULL;
480
481 SSL *SSLGetContext( int sock )
482 {
483         /* If SSLOpen has never initialized - just return NULL */
484         if( NULL == _ctx )
485                 return NULL;
486
487         if( sock < 0 || sock > FD_SETSIZE )
488                 return NULL;
489         return _ssl_context[sock];
490 }
491
492
493 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
494 {
495         char buf[260];
496         char cbuf[260];
497         char ibuf[260];
498         char *str_ptr;
499         X509 *x509_cert;
500         int err, depth;
501
502         x509_cert = X509_STORE_CTX_get_current_cert(ctx);
503         err = X509_STORE_CTX_get_error(ctx);
504         depth = X509_STORE_CTX_get_error_depth(ctx);
505
506         X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
507         X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
508
509         /* Just to be sure those buffers are terminated...  I think the
510                 X509 libraries do, but... */
511         buf[256] = ibuf[256] = '\0';
512
513         if (depth == 0) {
514                 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
515                         str_ptr += 3;
516                         strcpy( cbuf, str_ptr );
517                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
518                                 *str_ptr = '\0';
519                         }
520                         if (outlevel == O_VERBOSE)
521                                 report(stdout, "Issuer Organization: %s", cbuf );
522                 } else {
523                         if (outlevel == O_VERBOSE)
524                                 report(stdout, "Unknown Organization", cbuf );
525                 }
526                 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
527                         str_ptr += 4;
528                         strcpy( cbuf, str_ptr );
529                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
530                                 *str_ptr = '\0';
531                         }
532                         if (outlevel == O_VERBOSE)
533                                 report(stdout, "Issuer CommonName: %s", cbuf );
534                 } else {
535                         if (outlevel == O_VERBOSE)
536                                 report(stdout, "Unknown Issuer CommonName", cbuf );
537                 }
538                 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
539                         str_ptr += 4;
540                         strcpy( cbuf, str_ptr );
541                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
542                                 *str_ptr = '\0';
543                         }
544                         if (outlevel == O_VERBOSE)
545                                 report(stdout, "Server CommonName: %s", cbuf );
546                         /* Should we have some wildcarding here? */
547                         if ( NULL != _ssl_server_cname && 0 != strcmp( cbuf, _ssl_server_cname ) ) {
548                                 report(stdout, "Server CommonName mismatch: %s != %s", cbuf, _ssl_server_cname );
549                         }
550                 } else {
551                         if (outlevel == O_VERBOSE)
552                                 report(stdout, "Unknown Server CommonName", cbuf );
553                 }
554         }
555
556         switch (ctx->error) {
557         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
558                 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
559                 report(stdout, "unknown issuer= %s", buf);
560                 break;
561         case X509_V_ERR_CERT_NOT_YET_VALID:
562         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
563                 report(stderr, "Server Certificate not yet valid");
564                 break;
565         case X509_V_ERR_CERT_HAS_EXPIRED:
566         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
567                 report(stderr, "Server Certificate expired");
568                 break;
569         }
570         /* We are not requiring or validating server or issuer id's as yet */
571         /* Always return OK from here */
572         ok_return = 1;
573         return( ok_return );
574 }
575
576
577 /* performs initial SSL handshake over the connected socket
578  * uses SSL *ssl global variable, which is currently defined
579  * in this file
580  */
581 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
582 {
583         SSL_load_error_strings();
584         SSLeay_add_ssl_algorithms();
585         
586         if( sock < 0 || sock > FD_SETSIZE ) {
587                 report(stderr, "File descriptor out of range for SSL" );
588                 return( -1 );
589         }
590
591         if( ! _ctx ) {
592                 /* Be picky and make sure the memory is cleared */
593                 memset( _ssl_context, 0, sizeof( _ssl_context ) );
594                 _ctx = SSL_CTX_new(SSLv23_client_method());
595                 if(_ctx == NULL) {
596                         ERR_print_errors_fp(stderr);
597                         return(-1);
598                 }
599         }
600         
601         _ssl_context[sock] = SSL_new(_ctx);
602         
603         if(_ssl_context[sock] == NULL) {
604                 ERR_print_errors_fp(stderr);
605                 return(-1);
606         }
607         
608         /* This static is for the verify callback */
609         _ssl_server_cname = servercname;
610
611         SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
612
613         if( mycert || mykey ) {
614
615         /* Ok...  He has a certificate file defined, so lets declare it.  If
616          * he does NOT have a separate certificate and private key file then
617          * assume that it's a combined key and certificate file.
618          */
619                 if( !mykey )
620                         mykey = mycert;
621                 if( !mycert )
622                         mycert = mykey;
623                 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
624                 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
625         }
626
627         SSL_set_fd(_ssl_context[sock], sock);
628         
629         if(SSL_connect(_ssl_context[sock]) == -1) {
630                 ERR_print_errors_fp(stderr);
631                 return(-1);
632         }
633         
634         return(0);
635 }
636 #endif
637
638 int SockClose(int sock)
639 /* close a socket (someday we may do other cleanup here) */
640 {
641 #ifdef  SSL_ENABLE
642     SSL *ssl;
643
644     if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
645         /* Clean up the SSL stack */
646         SSL_free( _ssl_context[sock] );
647         _ssl_context[sock] = NULL;
648     }
649 #endif
650     return(close(sock));
651 }
652
653 #ifdef MAIN
654 /*
655  * Use the chargen service to test input buffering directly.
656  * You may have to uncomment the `chargen' service description in your
657  * inetd.conf (and then SIGHUP inetd) for this to work. 
658  */
659 main()
660 {
661     int         sock = SockOpen("localhost", 19, NULL);
662     char        buf[80];
663
664     while (SockRead(sock, buf, sizeof(buf)-1))
665         SockWrite(1, buf, strlen(buf));
666     SockClose(sock);
667 }
668 #endif /* MAIN */
669
670 /* socket.c ends here */