]> Pileus Git - ~andy/fetchmail/blob - socket.c
Tweak in lexical analysis.
[~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
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, &ai)) {
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(ai, 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(ai, NULL, 0, NULL, NULL, "fetchmail", NULL);
158 #else
159     i = socket(ai->ai_family, ai->ai_socktype, 0);
160     if (i < 0) {
161         freeaddrinfo(ai);
162         return -1;
163     }
164     if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
165         freeaddrinfo(ai);
166         close(i);       /* don't use SockClose, no traffic yet */
167         return -1;
168     }
169 #endif
170 #endif /* NET_SECURITY */
171
172     freeaddrinfo(ai);
173
174     return i;
175 };
176 #else /* INET6_ENABLE */
177 #ifndef HAVE_INET_ATON
178 #ifndef  INADDR_NONE
179 #ifdef   INADDR_BROADCAST
180 #define  INADDR_NONE    INADDR_BROADCAST
181 #else
182 #define  INADDR_NONE    -1
183 #endif
184 #endif
185 #endif /* HAVE_INET_ATON */
186
187 int SockOpen(const char *host, int clientPort, const char *options,
188              const char *plugin)
189 {
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;
195     struct hostent *hp;
196
197 #ifdef HAVE_SOCKETPAIR
198     if (plugin) {
199       char buf[10];
200       sprintf(buf,"%d",clientPort);
201       return handle_plugin(host,buf,plugin);
202     }
203 #endif /* HAVE_SOCKETPAIR */
204
205     memset(&ad, 0, sizeof(ad));
206     ad.sin_family = AF_INET;
207
208     /* we'll accept a quad address */
209 #ifndef HAVE_INET_ATON
210     inaddr = inet_addr(host);
211     if (inaddr != INADDR_NONE)
212     {
213         memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
214 #else
215     if (inet_aton(host, &ad.sin_addr))
216     {
217 #endif /* HAVE_INET_ATON */
218         ad.sin_port = htons(clientPort);
219
220         sock = socket(AF_INET, SOCK_STREAM, 0);
221         if (sock < 0)
222         {
223             h_errno = 0;
224             return -1;
225         }
226         if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
227         {
228             int olderr = errno;
229             close(sock);        /* don't use SockClose, no traffic yet */
230             h_errno = 0;
231             errno = olderr;
232             return -1;
233         }
234 #ifndef HAVE_INET_ATON
235     }
236 #else
237     }
238 #endif /* HAVE_INET_ATON */
239     else {
240         hp = gethostbyname(host);
241
242         if (hp == NULL)
243         {
244             errno = 0;
245             return -1;
246         }
247         /*
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.
250          */
251         if(hp->h_length != 4 && hp->h_length != 8)
252         {
253             h_errno = errno = 0;
254             report(stderr, 
255                    _("fetchmail: illegal address length received for host %s\n"),host);
256             return -1;
257         }
258         /*
259          * Try all addresses of a possibly multihomed host until we get
260          * a successful connect or until we run out of addresses.
261          */
262         pptr = (struct sockaddr_in **)hp->h_addr_list;
263         for(; *pptr != NULL; pptr++)
264         {
265             sock = socket(AF_INET, SOCK_STREAM, 0);
266             if (sock < 0)
267             {
268                 h_errno = 0;
269                 return -1;
270             }
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)
274                 break; /* success */
275             close(sock);        /* don't use SockClose, no traffic yet */
276             memset(&ad, 0, sizeof(ad));
277             ad.sin_family = AF_INET;
278         }
279         if(*pptr == NULL)
280         {
281             int olderr = errno;
282             close(sock);        /* don't use SockClose, no traffic yet */
283             h_errno = 0;
284             errno = olderr;
285             return -1;
286         }
287     }
288     return(sock);
289 }
290 #endif /* INET6_ENABLE */
291
292
293 #if defined(HAVE_STDARG_H)
294 int SockPrintf(int sock, const char* format, ...)
295 {
296 #else
297 int SockPrintf(sock,format,va_alist)
298 int sock;
299 char *format;
300 va_dcl {
301 #endif
302
303     va_list ap;
304     char buf[8192];
305
306 #if defined(HAVE_STDARG_H)
307     va_start(ap, format) ;
308 #else
309     va_start(ap);
310 #endif
311 #ifdef HAVE_VSNPRINTF
312     vsnprintf(buf, sizeof(buf), format, ap);
313 #else
314     vsprintf(buf, format, ap);
315 #endif
316     va_end(ap);
317     return SockWrite(sock, buf, strlen(buf));
318
319 }
320
321 #ifdef SSL_ENABLE
322 #include "ssl.h"
323 #include "err.h"
324 #include "pem.h"
325 #include "x509.h"
326
327 static  SSL_CTX *_ctx = NULL;
328 static  SSL *_ssl_context[FD_SETSIZE];
329
330 SSL     *SSLGetContext( int );
331 #endif /* SSL_ENABLE */
332
333 int SockWrite(int sock, char *buf, int len)
334 {
335     int n, wrlen = 0;
336 #ifdef  SSL_ENABLE
337     SSL *ssl;
338 #endif
339
340     while (len)
341     {
342 #ifdef SSL_ENABLE
343         if( NULL != ( ssl = SSLGetContext( sock ) ) )
344                 n = SSL_write(ssl, buf, len);
345         else
346                 n = write(sock, buf, len);
347 #else
348         n = write(sock, buf, len);
349 #endif
350         if (n <= 0)
351             return -1;
352         len -= n;
353         wrlen += n;
354         buf += n;
355     }
356     return wrlen;
357 }
358
359 int SockRead(int sock, char *buf, int len)
360 {
361     char *newline, *bp = buf;
362     int n;
363 #ifdef  SSL_ENABLE
364     SSL *ssl;
365 #endif
366
367     if (--len < 1)
368         return(-1);
369     do {
370         /* 
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.
375          */
376 #ifdef  SSL_ENABLE
377         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
378                 /* Hack alert! */
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) {
391                         return(-1);
392                 }
393                 if( 0 == n ) {
394                         /* SSL_peek says no data...  Does he mean no data
395                         or did the connection blow up?  If we got an error
396                         then bail! */
397                         if( 0 != ( n = ERR_get_error() ) ) {
398                                 return -1;
399                         }
400                         /* We didn't get an error so read at least one
401                                 character at this point and loop */
402                         n = 1;
403                         /* Make sure newline start out NULL!
404                          * We don't have a string to pass through
405                          * the strchr at this point yet */
406                         newline = NULL;
407                 } else if ((newline = memchr(bp, '\n', n)) != NULL)
408                         n = newline - bp + 1;
409                 if ((n = SSL_read(ssl, bp, n)) == -1) {
410                         return(-1);
411                 }
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 */
418                         newline = bp;
419                 }
420         } else {
421                 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
422                         return(-1);
423                 if ((newline = memchr(bp, '\n', n)) != NULL)
424                         n = newline - bp + 1;
425                 if ((n = read(sock, bp, n)) == -1)
426                         return(-1);
427         }
428 #else
429         if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
430             return(-1);
431         if ((newline = memchr(bp, '\n', n)) != NULL)
432             n = newline - bp + 1;
433         if ((n = read(sock, bp, n)) == -1)
434             return(-1);
435 #endif
436         bp += n;
437         len -= n;
438     } while 
439             (!newline && len);
440     *bp = '\0';
441     return bp - buf;
442 }
443
444 int SockPeek(int sock)
445 /* peek at the next socket character without actually reading it */
446 {
447     int n;
448     char ch;
449 #ifdef  SSL_ENABLE
450     SSL *ssl;
451 #endif
452
453 #ifdef  SSL_ENABLE
454         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
455                 n = SSL_peek(ssl, &ch, 1);
456                 if( 0 == n ) {
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...     */
461
462                         /* SSL_peek says no data...  Does he mean no data
463                         or did the connection blow up?  If we got an error
464                         then bail! */
465                         if( 0 != ( n = ERR_get_error() ) ) {
466                                 return -1;
467                         }
468
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"... */
474
475                         return 0;       /* Give him a '\0' character */
476                 }
477         } else {
478                 n = recv(sock, &ch, 1, MSG_PEEK);
479         }
480 #else
481         n = recv(sock, &ch, 1, MSG_PEEK);
482 #endif
483         if (n == -1)
484                 return -1;
485         else
486                 return(ch);
487 }
488
489 #ifdef SSL_ENABLE
490
491 static  char *_ssl_server_cname = NULL;
492
493 SSL *SSLGetContext( int sock )
494 {
495         /* If SSLOpen has never initialized - just return NULL */
496         if( NULL == _ctx )
497                 return NULL;
498
499         if( sock < 0 || sock > FD_SETSIZE )
500                 return NULL;
501         return _ssl_context[sock];
502 }
503
504
505 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
506 {
507         char buf[260];
508         char cbuf[260];
509         char ibuf[260];
510         char *str_ptr;
511         X509 *x509_cert;
512         int err, depth;
513
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);
517
518         X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
519         X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
520
521         /* Just to be sure those buffers are terminated...  I think the
522                 X509 libraries do, but... */
523         buf[256] = ibuf[256] = '\0';
524
525         if (depth == 0) {
526                 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
527                         str_ptr += 3;
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 Organization: %s\n", cbuf );
534                 } else {
535                         if (outlevel == O_VERBOSE)
536                                 report(stdout, "Unknown Organization\n", cbuf );
537                 }
538                 if( ( str_ptr = strstr( ibuf, "/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, "Issuer CommonName: %s\n", cbuf );
546                 } else {
547                         if (outlevel == O_VERBOSE)
548                                 report(stdout, "Unknown Issuer CommonName\n", cbuf );
549                 }
550                 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
551                         str_ptr += 4;
552                         strcpy( cbuf, str_ptr );
553                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
554                                 *str_ptr = '\0';
555                         }
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 ) ) {
561                                 report(stdout,
562                                        "Server CommonName mismatch: %s != %s\n",
563                                        cbuf, _ssl_server_cname );
564                         }
565                 } else {
566                         if (outlevel == O_VERBOSE)
567                                 report(stdout, "Unknown Server CommonName\n", cbuf );
568                 }
569         }
570
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);
575                 break;
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");
579                 break;
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");
583                 break;
584         }
585         /* We are not requiring or validating server or issuer id's as yet */
586         /* Always return OK from here */
587         ok_return = 1;
588         return( ok_return );
589 }
590
591
592 /* performs initial SSL handshake over the connected socket
593  * uses SSL *ssl global variable, which is currently defined
594  * in this file
595  */
596 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
597 {
598         SSL_load_error_strings();
599         SSLeay_add_ssl_algorithms();
600         
601         if( sock < 0 || sock > FD_SETSIZE ) {
602                 report(stderr, "File descriptor out of range for SSL" );
603                 return( -1 );
604         }
605
606         if( ! _ctx ) {
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());
610                 if(_ctx == NULL) {
611                         ERR_print_errors_fp(stderr);
612                         return(-1);
613                 }
614         }
615         
616         _ssl_context[sock] = SSL_new(_ctx);
617         
618         if(_ssl_context[sock] == NULL) {
619                 ERR_print_errors_fp(stderr);
620                 return(-1);
621         }
622         
623         /* This static is for the verify callback */
624         _ssl_server_cname = servercname;
625
626         SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
627
628         if( mycert || mykey ) {
629
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.
633          */
634                 if( !mykey )
635                         mykey = mycert;
636                 if( !mycert )
637                         mycert = mykey;
638                 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
639                 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
640         }
641
642         SSL_set_fd(_ssl_context[sock], sock);
643         
644         if(SSL_connect(_ssl_context[sock]) == -1) {
645                 ERR_print_errors_fp(stderr);
646                 return(-1);
647         }
648         
649         return(0);
650 }
651 #endif
652
653 int SockClose(int sock)
654 /* close a socket gracefully */
655 {
656     char ch;
657 #ifdef  SSL_ENABLE
658     SSL *ssl;
659
660     if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
661         /* Clean up the SSL stack */
662         SSL_free( _ssl_context[sock] );
663         _ssl_context[sock] = NULL;
664     }
665 #endif
666
667     /* Half-close the connection first so the other end gets notified.
668      *
669      * This stops sends but allows receives (effectively, it sends a
670      * TCP <FIN>).
671      */
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.
677          */
678         if (recv(sock, &ch, 1, MSG_PEEK) > 0)
679             while (read(sock, &ch, 1) > 0)
680                 continue;
681
682     /* if there's an error closing at this point, not much we can do */
683     return(close(sock));        /* this is guarded */
684 }
685
686 #ifdef MAIN
687 /*
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.  */
691 main()
692 {
693     int         sock = SockOpen("localhost", 19, NULL);
694     char        buf[80];
695
696     while (SockRead(sock, buf, sizeof(buf)-1))
697         SockWrite(1, buf, strlen(buf));
698     SockClose(sock);
699 }
700 #endif /* MAIN */
701
702 /* socket.c ends here */