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