]> Pileus Git - ~andy/fetchmail/blob - socket.c
Clean up the horrible HAVE_[V]SNPRINTF mess, use Trio on systems that lack
[~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 #include <ctype.h> /* isspace() */
13 #ifdef HAVE_MEMORY_H
14 #include <memory.h>
15 #endif /* HAVE_MEMORY_H */
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #ifndef HAVE_NET_SOCKET_H
19 #include <sys/socket.h>
20 #else
21 #include <net/socket.h>
22 #endif
23 #include <sys/un.h>
24 #include <netinet/in.h>
25 #ifdef HAVE_ARPA_INET_H
26 #include <arpa/inet.h>
27 #endif
28 #include <netdb.h>
29 #if defined(STDC_HEADERS)
30 #include <stdlib.h>
31 #endif
32 #if defined(HAVE_UNISTD_H)
33 #include <unistd.h>
34 #endif
35 #if defined(HAVE_STDARG_H)
36 #include <stdarg.h>
37 #else
38 #include <varargs.h>
39 #endif
40 #include "socket.h"
41 #include "fetchmail.h"
42 #include "i18n.h"
43
44 /* Defines to allow BeOS and Cygwin to play nice... */
45 #ifdef __BEOS__
46 static char peeked;
47 #define fm_close(a)  closesocket(a)
48 #define fm_write(a,b,c)  send(a,b,c,0)
49 #define fm_peek(a,b,c)   recv(a,b,c,0)
50 #define fm_read(a,b,c)   recv(a,b,c,0)
51 #else
52 #define fm_close(a)  close(a)
53 #define fm_write(a,b,c)  write(a,b,c)
54 #define fm_peek(a,b,c)   recv(a,b,c, MSG_PEEK)
55 #ifdef __CYGWIN__
56 #define fm_read(a,b,c)   cygwin_read(a,b,c)
57 static ssize_t cygwin_read(int sock, void *buf, size_t count);
58 #else /* ! __CYGWIN__ */
59 #define fm_read(a,b,c)   read(a,b,c)
60 #endif /* __CYGWIN__ */
61 #endif
62
63 /* We need to define h_errno only if it is not already */
64 #ifndef h_errno
65
66 #ifdef HAVE_RES_SEARCH
67 /* some versions of FreeBSD should declare this but don't */
68 extern int h_errno;
69 #else
70 /* pretend we have h_errno to avoid some #ifdef's later */
71 static int h_errno;
72 #endif
73
74 #endif /* ndef h_errno */
75
76 #ifdef NET_SECURITY
77 #include <net/security.h>
78 #endif /* NET_SECURITY */
79
80 #ifdef HAVE_SOCKETPAIR
81 static char *const *parse_plugin(const char *plugin, const char *host, const char *service)
82 {       const char **argvec;
83         const char *c, *p;
84         char *cp, *plugin_copy;
85         unsigned int plugin_copy_len;
86         unsigned int plugin_offset = 0, plugin_copy_offset = 0;
87         unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
88         unsigned int plugin_len = strlen(plugin);
89         unsigned int host_len = strlen(host);
90         unsigned int service_len = strlen(service);
91
92         for (c = p = plugin; *c; c++)
93         {       if (isspace((unsigned char)*c) && !isspace((unsigned char)*p))
94                         s += sizeof(char*);
95                 if (*p == '%' && *c == 'h')
96                         host_count++;
97                 if (*p == '%' && *c == 'p')
98                         service_count++;
99                 p = c;
100         }
101
102         plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
103         plugin_copy = malloc(plugin_copy_len + 1);
104         if (!plugin_copy)
105         {
106                 report(stderr, GT_("fetchmail: malloc failed\n"));
107                 return NULL;
108         }
109
110         while (plugin_copy_offset < plugin_copy_len)
111         {       if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
112                 {       strcpy(plugin_copy + plugin_copy_offset, host);
113                         plugin_offset += 2;
114                         plugin_copy_offset += host_len;
115                 }
116                 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
117                 {       strcpy(plugin_copy + plugin_copy_offset, service);
118                         plugin_offset += 2;
119                         plugin_copy_offset += service_len;
120                 }
121                 else
122                 {       plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
123                         plugin_offset++;
124                         plugin_copy_offset++;
125                 }
126         }
127         plugin_copy[plugin_copy_len] = 0;
128
129         argvec = malloc(s);
130         if (!argvec)
131         {
132                 report(stderr, GT_("fetchmail: malloc failed\n"));
133                 return NULL;
134         }
135         memset(argvec, 0, s);
136         for (c = p = plugin_copy, i = 0; *c; c++)
137         {       if ((!isspace((unsigned char)*c)) && (c == p ? 1 : isspace((unsigned char)*p))) {
138                         argvec[i] = c;
139                         i++;
140                 }
141                 p = c;
142         }
143         for (cp = plugin_copy; *cp; cp++)
144         {       if (isspace((unsigned char)*cp))
145                         *cp = 0;
146         }
147         return (char *const*)argvec;
148 }
149
150 static int handle_plugin(const char *host,
151                          const char *service, const char *plugin)
152 /* get a socket mediated through a given external command */
153 {
154     int fds[2];
155     char *const *argvec;
156
157     /*
158      * The author of this code, Felix von Leitner <felix@convergence.de>, says:
159      * he chose socketpair() instead of pipe() because socketpair creates 
160      * bidirectional sockets while allegedly some pipe() implementations don't.
161      */
162     if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
163     {
164         report(stderr, GT_("fetchmail: socketpair failed\n"));
165         return -1;
166     }
167     switch (fork()) {
168         case -1:
169                 /* error */
170                 report(stderr, GT_("fetchmail: fork failed\n"));
171                 return -1;
172         case 0: /* child */
173                 /* fds[1] is the parent's end; close it for proper EOF
174                 ** detection */
175                 (void) close(fds[1]);
176                 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
177                         report(stderr, GT_("dup2 failed\n"));
178                         exit(1);
179                 }
180                 /* fds[0] is now connected to 0 and 1; close it */
181                 (void) close(fds[0]);
182                 if (outlevel >= O_VERBOSE)
183                     report(stderr, GT_("running %s (host %s service %s)\n"), plugin, host, service);
184                 argvec = parse_plugin(plugin,host,service);
185                 execvp(*argvec, argvec);
186                 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
187                 exit(0);
188                 break;
189         default:        /* parent */
190                 /* NOP */
191                 break;
192     }
193     /* fds[0] is the child's end; close it for proper EOF detection */
194     (void) close(fds[0]);
195     return fds[1];
196 }
197 #endif /* HAVE_SOCKETPAIR */
198
199 #ifdef __UNUSED__
200
201 int SockCheckOpen(int fd)
202 /* poll given socket; is it selectable? */
203 {
204     fd_set r, w, e;
205     int rt;
206     struct timeval tv;
207   
208     for (;;) 
209     {
210         FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
211         FD_SET(fd, &e);
212     
213         tv.tv_sec = 0; tv.tv_usec = 0;
214         rt = select(fd+1, &r, &w, &e, &tv);
215         if (rt == -1 && (errno != EAGAIN && errno != EINTR))
216             return 0;
217         if (rt != -1)
218             return 1;
219     }
220 }
221 #endif /* __UNUSED__ */
222
223 int UnixOpen(const char *path)
224 {
225     int sock = -1;
226     struct sockaddr_un ad;
227     memset(&ad, 0, sizeof(ad));
228     ad.sun_family = AF_UNIX;
229     strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
230
231     sock = socket( AF_UNIX, SOCK_STREAM, 0 );
232     if (sock < 0)
233     {
234         h_errno = 0;
235         return -1;
236     }
237
238         /* Socket opened saved. Usefull if connect timeout 
239          * because it can be closed.
240          */
241         mailserver_socket_temp = sock;
242     
243         if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
244     {
245         int olderr = errno;
246         fm_close(sock); /* don't use SockClose, no traffic yet */
247         h_errno = 0;
248         errno = olderr;
249         sock = -1;
250     }
251         
252         /* No connect timeout, then no need to set mailserver_socket_temp */
253         mailserver_socket_temp = -1;
254
255     return sock;
256 }
257
258 #ifdef INET6_ENABLE
259 int SockOpen(const char *host, const char *service, const char *options,
260              const char *plugin)
261 {
262     struct addrinfo *ai, *ai0, req;
263     int i;
264 #ifdef NET_SECURITY
265     void *request = NULL;
266     int requestlen;
267 #endif /* NET_SECURITY */
268
269 #ifdef HAVE_SOCKETPAIR
270     if (plugin)
271         return handle_plugin(host,service,plugin);
272 #endif /* HAVE_SOCKETPAIR */
273     memset(&req, 0, sizeof(struct addrinfo));
274     req.ai_socktype = SOCK_STREAM;
275
276     if (getaddrinfo(host, service, &req, &ai0)) {
277         report(stderr, GT_("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
278         return -1;
279     }
280
281 #if NET_SECURITY
282     if (!options)
283         requestlen = 0;
284     else
285         if (net_security_strtorequest((char *)options, &request, &requestlen))
286             goto ret;
287
288     i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
289     if (request)
290         free(request);
291
292  ret:
293 #else /* NET_SECURITY */
294 #ifdef HAVE_INNER_CONNECT
295     i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
296     if (i >= 0)
297         break;
298 #else
299
300     i = -1;
301     for (ai = ai0; ai; ai = ai->ai_next) {
302         i = socket(ai->ai_family, ai->ai_socktype, 0);
303         if (i < 0)
304             continue;
305
306         /* Socket opened saved. Usefull if connect timeout 
307          * because it can be closed.
308          */
309         mailserver_socket_temp = i;
310
311         if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
312             fm_close(i);
313             i = -1;
314             continue;
315         }
316         
317         /* No connect timeout, then no need to set mailserver_socket_temp */
318         mailserver_socket_temp = -1;
319         
320         break;
321     }
322
323 #endif
324 #endif /* NET_SECURITY */
325
326     freeaddrinfo(ai0);
327
328     return i;
329 }
330 #else /* INET6_ENABLE */
331 #ifndef HAVE_INET_ATON
332 #ifndef  INADDR_NONE
333 #ifdef   INADDR_BROADCAST
334 #define  INADDR_NONE    INADDR_BROADCAST
335 #else
336 #define  INADDR_NONE    -1
337 #endif
338 #endif
339 #endif /* HAVE_INET_ATON */
340
341 int SockOpen(const char *host, int clientPort, const char *options,
342              const char *plugin)
343 {
344     int sock = -1;      /* pacify -Wall */
345 #ifndef HAVE_INET_ATON
346     unsigned long inaddr;
347 #endif /* HAVE_INET_ATON */
348     struct sockaddr_in ad, **pptr;
349     struct hostent *hp;
350
351 #ifdef HAVE_SOCKETPAIR
352     if (plugin) {
353       char buf[10];
354       snprintf(buf, sizeof(buf), "%d", clientPort);
355       return handle_plugin(host,buf,plugin);
356     }
357 #endif /* HAVE_SOCKETPAIR */
358
359     memset(&ad, 0, sizeof(ad));
360     ad.sin_family = AF_INET;
361
362     /* we'll accept a quad address */
363 #ifndef HAVE_INET_ATON
364     inaddr = inet_addr((char*)host);
365     if (inaddr != INADDR_NONE)
366     {
367         memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
368 #else
369     if (inet_aton(host, &ad.sin_addr))
370     {
371 #endif /* HAVE_INET_ATON */
372         ad.sin_port = htons(clientPort);
373
374         sock = socket(AF_INET, SOCK_STREAM, 0);
375         if (sock < 0)
376         {
377             h_errno = 0;
378             return -1;
379         }
380
381                 /* Socket opened saved. Usefull if connect timeout because
382                  * it can be closed
383                  */
384                 mailserver_socket_temp = sock;
385                 
386         if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
387         {
388             int olderr = errno;
389             fm_close(sock);     /* don't use SockClose, no traffic yet */
390             h_errno = 0;
391             errno = olderr;
392             return -1;
393         }
394
395                 /* No connect timeout, then no need to set mailserver_socket_temp */
396                 mailserver_socket_temp = -1;
397                 
398 #ifndef HAVE_INET_ATON
399     }
400 #else
401     }
402 #endif /* HAVE_INET_ATON */
403     else {
404         hp = gethostbyname((char*)host);
405
406         if (hp == NULL)
407         {
408             errno = 0;
409             return -1;
410         }
411         /*
412          * Add a check to make sure the address has a valid IPv4 or IPv6
413          * length.  This prevents buffer spamming by a broken DNS.
414          */
415         if(hp->h_length != 4 && hp->h_length != 8)
416         {
417             h_errno = errno = 0;
418             report(stderr, 
419                    GT_("fetchmail: illegal address length received for host %s\n"),host);
420             return -1;
421         }
422         /*
423          * Try all addresses of a possibly multihomed host until we get
424          * a successful connect or until we run out of addresses.
425          */
426         pptr = (struct sockaddr_in **)hp->h_addr_list;
427         for(; *pptr != NULL; pptr++)
428         {
429             sock = socket(AF_INET, SOCK_STREAM, 0);
430             if (sock < 0)
431             {
432                 h_errno = 0;
433                 return -1;
434             }
435
436                 /* Socket opened saved. Usefull if connect timeout because
437                  * it can be closed
438                  */
439                 mailserver_socket_temp = sock;
440                 
441             ad.sin_port = htons(clientPort);
442             memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
443             if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0) {
444                         /* No connect timeout, then no need to set mailserver_socket_temp */
445                         mailserver_socket_temp = -1;
446                         break; /* success */
447                 }       
448             fm_close(sock);     /* don't use SockClose, no traffic yet */
449             memset(&ad, 0, sizeof(ad));
450             ad.sin_family = AF_INET;
451         }
452         if(*pptr == NULL)
453         {
454             int olderr = errno;
455             fm_close(sock);     /* don't use SockClose, no traffic yet */
456             h_errno = 0;
457             errno = olderr;
458             return -1;
459         }
460     }
461
462     return(sock);
463 }
464 #endif /* INET6_ENABLE */
465
466
467 #if defined(HAVE_STDARG_H)
468 int SockPrintf(int sock, const char* format, ...)
469 {
470 #else
471 int SockPrintf(sock,format,va_alist)
472 int sock;
473 char *format;
474 va_dcl {
475 #endif
476
477     va_list ap;
478     char buf[8192];
479
480 #if defined(HAVE_STDARG_H)
481     va_start(ap, format) ;
482 #else
483     va_start(ap);
484 #endif
485     vsnprintf(buf, sizeof(buf), format, ap);
486     va_end(ap);
487     return SockWrite(sock, buf, strlen(buf));
488
489 }
490
491 #ifdef SSL_ENABLE
492 #include <openssl/ssl.h>
493 #include <openssl/err.h>
494 #include <openssl/pem.h>
495 #include <openssl/x509.h>
496 #include <openssl/rand.h>
497
498 static  SSL_CTX *_ctx = NULL;
499 static  SSL *_ssl_context[FD_SETSIZE];
500
501 static SSL      *SSLGetContext( int );
502 #endif /* SSL_ENABLE */
503
504 int SockWrite(int sock, char *buf, int len)
505 {
506     int n, wrlen = 0;
507 #ifdef  SSL_ENABLE
508     SSL *ssl;
509 #endif
510
511     while (len)
512     {
513 #ifdef SSL_ENABLE
514         if( NULL != ( ssl = SSLGetContext( sock ) ) )
515                 n = SSL_write(ssl, buf, len);
516         else
517 #endif /* SSL_ENABLE */
518             n = fm_write(sock, buf, len);
519         if (n <= 0)
520             return -1;
521         len -= n;
522         wrlen += n;
523         buf += n;
524     }
525     return wrlen;
526 }
527
528 int SockRead(int sock, char *buf, int len)
529 {
530     char *newline, *bp = buf;
531     int n;
532 #ifdef  FORCE_STUFFING
533     int maxavailable = 0;
534 #endif
535 #ifdef  SSL_ENABLE
536     SSL *ssl;
537 #endif
538
539     if (--len < 1)
540         return(-1);
541 #ifdef __BEOS__
542     if (peeked != 0){
543         (*bp) = peeked;
544         bp++;
545         len--;
546         peeked = 0;
547     }
548 #endif        
549     do {
550         /* 
551          * The reason for these gymnastics is that we want two things:
552          * (1) to read \n-terminated lines,
553          * (2) to return the true length of data read, even if the
554          *     data coming in has embedded NULS.
555          */
556 #ifdef  SSL_ENABLE
557         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
558                 /* Hack alert! */
559                 /* OK...  SSL_peek works a little different from MSG_PEEK
560                         Problem is that SSL_peek can return 0 if there
561                         is no data currently available.  If, on the other
562                         hand, we loose the socket, we also get a zero, but
563                         the SSL_read then SEGFAULTS!  To deal with this,
564                         we'll check the error code any time we get a return
565                         of zero from SSL_peek.  If we have an error, we bail.
566                         If we don't, we read one character in SSL_read and
567                         loop.  This should continue to work even if they
568                         later change the behavior of SSL_peek
569                         to "fix" this problem...  :-(   */
570                 if ((n = SSL_peek(ssl, bp, len)) < 0) {
571                         (void)SSL_get_error(ssl, n);
572                         return(-1);
573                 }
574 #ifdef FORCE_STUFFING
575                 maxavailable = n;
576 #endif
577                 if( 0 == n ) {
578                         /* SSL_peek says no data...  Does he mean no data
579                         or did the connection blow up?  If we got an error
580                         then bail! */
581                         if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
582                                 return -1;
583                         }
584                         /* We didn't get an error so read at least one
585                                 character at this point and loop */
586                         n = 1;
587                         /* Make sure newline start out NULL!
588                          * We don't have a string to pass through
589                          * the strchr at this point yet */
590                         newline = NULL;
591                 } else if ((newline = memchr(bp, '\n', n)) != NULL)
592                         n = newline - bp + 1;
593                 /* Matthias Andree: SSL_read can return 0, in that case
594                  * we must cal SSL_get_error to figure if there was
595                  * an error or just a "no data" condition */
596                 if ((n = SSL_read(ssl, bp, n)) <= 0) {
597                         if ((n = SSL_get_error(ssl, n))) {
598                                 return(-1);
599                         }
600                 }
601                 /* Check for case where our single character turned out to
602                  * be a newline...  (It wasn't going to get caught by
603                  * the strchr above if it came from the hack...  ). */
604                 if( NULL == newline && 1 == n && '\n' == *bp ) {
605                         /* Got our newline - this will break
606                                 out of the loop now */
607                         newline = bp;
608                 }
609         }
610         else
611 #endif /* SSL_ENABLE */
612         {
613
614 #ifdef __BEOS__
615             if ((n = fm_read(sock, bp, 1)) <= 0)
616 #else
617             if ((n = fm_peek(sock, bp, len)) <= 0)
618 #endif
619                 return (-1);
620 #ifdef FORCE_STUFFING
621             maxavailable = n;
622 #endif
623             if ((newline = memchr(bp, '\n', n)) != NULL)
624                 n = newline - bp + 1;
625 #ifndef __BEOS__
626             if ((n = fm_read(sock, bp, n)) == -1)
627                 return(-1);
628 #endif /* __BEOS__ */
629         }
630         bp += n;
631         len -= n;
632     } while 
633             (!newline && len);
634     *bp = '\0';
635
636 #ifdef FORCE_STUFFING           /* too ugly to live -- besides, there's IMAP */
637     /* OK, very weird hack coming up here:
638      * When POP3 servers send us a message, they're supposed to
639      * terminate the message with a line containing only a dot. To protect
640      * against lines in the real message that might contain only a dot,
641      * they're supposed to preface any line that starts with a dot with
642      * an additional dot, which will be removed on the client side. That
643      * process, called byte-stuffing (and unstuffing) is really not the
644      * concern of this low-level routine, ordinarily, but there are some
645      * POP servers (and maybe IMAP servers too, who knows) that fail to
646      * do the byte-stuffing, and this routine is the best place to try to
647      * identify and fix that fault.
648      *
649      * Since the DOT line is supposed to come only at the end of a
650      * message, the implication is that right after we see it, the server
651      * is supposed to go back to waiting for the next command. There
652      * isn't supposed to be any more data to read after we see the dot.
653      * THEREFORE, if we see more data to be read after something that
654      * looks like the dot line, then probably the server is failing to
655      * do byte-stuffing. In that case, we'll byte-pack it for them so
656      * that the higher-level routines see things as hunky-dorey.
657      * This is not a perfect test or fix by any means (it has an
658      * obvious race condition, for one thing), but it should at least
659      * reduce the nastiness that ensues when people don't know how
660      * to write POP servers.
661      */
662     if ((maxavailable > (bp-buf)) &&
663             ((((bp-buf) == 3) &&
664               (buf[0] == '.') &&
665               (buf[1] == '\r') &&
666               (buf[2] == '\n')) ||
667              (((bp-buf) == 2) &&
668               (buf[0] == '.') &&
669               (buf[1] == '\n')))) {
670
671         memmove(buf+1, buf, (bp-buf)+1);
672         buf[0] = '.';
673         bp++;
674     }
675 #endif /* FORCE_STUFFING */
676     return bp - buf;
677 }
678
679 int SockPeek(int sock)
680 /* peek at the next socket character without actually reading it */
681 {
682     int n;
683     char ch;
684 #ifdef  SSL_ENABLE
685     SSL *ssl;
686 #endif
687
688 #ifdef  SSL_ENABLE
689         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
690                 n = SSL_peek(ssl, &ch, 1);
691                 if (n < 0) {
692                         (void)SSL_get_error(ssl, n);
693                         return -1;
694                 }
695                 if( 0 == n ) {
696                         /* This code really needs to implement a "hold back"
697                          * to simulate a functioning SSL_peek()...  sigh...
698                          * Has to be coordinated with the read code above.
699                          * Next on the list todo...     */
700
701                         /* SSL_peek says 0...  Does that mean no data
702                         or did the connection blow up?  If we got an error
703                         then bail! */
704                         if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
705                                 return -1;
706                         }
707
708                         /* Haven't seen this case actually occur, but...
709                            if the problem in SockRead can occur, this should
710                            be possible...  Just not sure what to do here.
711                            This should be a safe "punt" the "peek" but don't
712                            "punt" the "session"... */
713
714                         return 0;       /* Give him a '\0' character */
715                 }
716         }
717         else
718 #endif /* SSL_ENABLE */
719             n = fm_peek(sock, &ch, 1);
720         if (n == -1)
721                 return -1;
722
723 #ifdef __BEOS__
724     peeked = ch;
725 #endif
726     return(ch);
727 }
728
729 #ifdef SSL_ENABLE
730
731 static  char *_ssl_server_cname = NULL;
732 static  int _check_fp;
733 static  char *_check_digest;
734 static  char *_server_label;
735 static  int _depth0ck;
736 static  int _prev_err;
737
738 SSL *SSLGetContext( int sock )
739 {
740         /* If SSLOpen has never initialized - just return NULL */
741         if( NULL == _ctx )
742                 return NULL;
743
744         if( sock < 0 || sock > FD_SETSIZE )
745                 return NULL;
746         return _ssl_context[sock];
747 }
748
749
750 /* ok_return (preverify_ok) is 1 if this stage of certificate verification
751    passed, or 0 if it failed. This callback lets us display informative
752    errors, and perform additional validation (e.g. CN matches) */
753 static int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
754 {
755         char buf[257];
756         X509 *x509_cert;
757         int err, depth;
758         unsigned char digest[EVP_MAX_MD_SIZE];
759         char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
760         const EVP_MD *digest_tp;
761         unsigned int dsz, i, esz;
762         X509_NAME *subj, *issuer;
763
764         x509_cert = X509_STORE_CTX_get_current_cert(ctx);
765         err = X509_STORE_CTX_get_error(ctx);
766         depth = X509_STORE_CTX_get_error_depth(ctx);
767
768         subj = X509_get_subject_name(x509_cert);
769         issuer = X509_get_issuer_name(x509_cert);
770
771         if (depth == 0 && !_depth0ck) {
772                 _depth0ck = 1;
773                 
774                 if (outlevel == O_VERBOSE) {
775                         if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
776                                 report(stdout, GT_("Issuer Organization: %s\n"), buf);
777                                 if (i >= sizeof(buf) - 1)
778                                         report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
779                         } else
780                                 report(stdout, GT_("Unknown Organization\n"));
781                         if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
782                                 report(stdout, GT_("Issuer CommonName: %s\n"), buf);
783                                 if (i >= sizeof(buf) - 1)
784                                         report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
785                         } else
786                                 report(stdout, GT_("Unknown Issuer CommonName\n"));
787                 }
788                 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
789                         if (outlevel == O_VERBOSE)
790                                 report(stdout, GT_("Server CommonName: %s\n"), buf);
791                         if (i >= sizeof(buf) - 1) {
792                                 /* Possible truncation. In this case, this is a DNS name, so this
793                                  * is really bad. We do not tolerate this even in the non-strict case. */
794                                 report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
795                                 return (0);
796                         }
797                         if (_ssl_server_cname != NULL) {
798                                 char *p1 = buf;
799                                 char *p2 = _ssl_server_cname;
800                                 int n;
801                                 
802                                 if (*p1 == '*') {
803                                         ++p1;
804                                         n = strlen(p2) - strlen(p1);
805                                         if (n >= 0)
806                                                 p2 += n;
807                                 }       
808                                 if (0 != strcasecmp(p1, p2)) {
809                                         report(stderr,
810                                             GT_("Server CommonName mismatch: %s != %s\n"),
811                                             buf, _ssl_server_cname );
812                                         if (ok_return && strict)
813                                                 return (0);
814                                 }
815                         } else if (ok_return) {
816                                 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
817                                 if (strict) return (0);
818                         }
819                 } else {
820                         if (outlevel == O_VERBOSE)
821                                 report(stdout, GT_("Unknown Server CommonName\n"));
822                         if (ok_return && strict) {
823                                 report(stderr, GT_("Server name not specified in certificate!\n"));
824                                 return (0);
825                         }
826                 }
827                 /* Print the finger print. Note that on errors, we might print it more than once
828                  * normally; we kluge around that by using a global variable. */
829                 if (_check_fp) {
830                         _check_fp = 0;
831                         digest_tp = EVP_md5();
832                         if (digest_tp == NULL) {
833                                 report(stderr, GT_("EVP_md5() failed!\n"));
834                                 return (0);
835                         }
836                         if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
837                                 report(stderr, GT_("Out of memory!\n"));
838                                 return (0);
839                         }
840                         tp = text;
841                         te = text + sizeof(text);
842                         for (i = 0; i < dsz; i++) {
843                                 esz = snprintf(tp, te - tp, i > 0 ? ":%02X" : "%02X", digest[i]);
844                                 if (esz >= te - tp) {
845                                         report(stderr, GT_("Digest text buffer too small!\n"));
846                                         return (0);
847                                 }
848                                 tp += esz;
849                         }
850                         if (outlevel > O_NORMAL)
851                             report(stdout, GT_("%s key fingerprint: %s\n"), _server_label, text);
852                         if (_check_digest != NULL) {
853                                 if (strcmp(text, _check_digest) == 0) {
854                                     if (outlevel > O_NORMAL)
855                                         report(stdout, GT_("%s fingerprints match.\n"), _server_label);
856                                 } else {
857                                     if (outlevel > O_SILENT)
858                                         report(stderr, GT_("%s fingerprints do not match!\n"), _server_label);
859                                     return (0);
860                                 }
861                         }
862                 }
863         }
864
865         if (err != X509_V_OK && err != _prev_err) {
866                 _prev_err = err;
867                 report(stderr, GT_("Server certificate verification error: %s\n"), X509_verify_cert_error_string(err));
868                 /* We gave the error code, but maybe we can add some more details for debugging */
869                 switch (err) {
870                 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
871                         X509_NAME_oneline(issuer, buf, sizeof(buf));
872                         buf[sizeof(buf) - 1] = '\0';
873                         report(stderr, GT_("unknown issuer (first %d characters): %s\n"), sizeof(buf)-1, buf);
874                         break;
875                 }
876         }
877         if (!strict)
878                 ok_return = 1;
879         return (ok_return);
880 }
881
882 static int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
883 {
884         return SSL_verify_callback(ok_return, ctx, 0);
885 }
886
887 static int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
888 {
889         return SSL_verify_callback(ok_return, ctx, 1);
890 }
891
892 /* performs initial SSL handshake over the connected socket
893  * uses SSL *ssl global variable, which is currently defined
894  * in this file
895  */
896 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, int certck, char *certpath,
897     char *fingerprint, char *servercname, char *label)
898 {
899         struct stat randstat;
900         int i;
901
902         SSL_load_error_strings();
903         SSLeay_add_ssl_algorithms();
904         
905 #ifdef SSL_ENABLE
906         if (stat("/dev/random", &randstat)  &&
907             stat("/dev/urandom", &randstat)) {
908           /* Neither /dev/random nor /dev/urandom are present, so add
909              entropy to the SSL PRNG a hard way. */
910           for (i = 0; i < 10000  &&  ! RAND_status (); ++i) {
911             char buf[4];
912             struct timeval tv;
913             gettimeofday (&tv, 0);
914             buf[0] = tv.tv_usec & 0xF;
915             buf[2] = (tv.tv_usec & 0xF0) >> 4;
916             buf[3] = (tv.tv_usec & 0xF00) >> 8;
917             buf[1] = (tv.tv_usec & 0xF000) >> 12;
918             RAND_add (buf, sizeof buf, 0.1);
919           }
920         }
921 #endif /* SSL_ENABLE */
922
923
924         if( sock < 0 || sock > FD_SETSIZE ) {
925                 report(stderr, GT_("File descriptor out of range for SSL") );
926                 return( -1 );
927         }
928
929         if( ! _ctx ) {
930                 /* Be picky and make sure the memory is cleared */
931                 memset( _ssl_context, 0, sizeof( _ssl_context ) );
932                 if(myproto) {
933                         if(!strcmp("ssl2",myproto)) {
934                                 _ctx = SSL_CTX_new(SSLv2_client_method());
935                         } else if(!strcmp("ssl3",myproto)) {
936                                 _ctx = SSL_CTX_new(SSLv3_client_method());
937                         } else if(!strcmp("tls1",myproto)) {
938                                 _ctx = SSL_CTX_new(TLSv1_client_method());
939                         } else if (!strcmp("ssl23",myproto)) {
940                                 myproto = NULL;
941                         } else {
942                                 fprintf(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
943                                 myproto = NULL;
944                         }
945                 }
946                 if(!myproto) {
947                         _ctx = SSL_CTX_new(SSLv23_client_method());
948                 }
949                 if(_ctx == NULL) {
950                         ERR_print_errors_fp(stderr);
951                         return(-1);
952                 }
953         }
954
955         if (certck) {
956                 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_ck_verify_callback);
957         } else {
958                 /* In this case, we do not fail if verification fails. However,
959                  *  we provide the callback for output and possible fingerprint checks. */
960                 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_nock_verify_callback);
961         }
962         if (certpath)
963                 SSL_CTX_load_verify_locations(_ctx, NULL, certpath);
964         
965         _ssl_context[sock] = SSL_new(_ctx);
966         
967         if(_ssl_context[sock] == NULL) {
968                 ERR_print_errors_fp(stderr);
969                 return(-1);
970         }
971         
972         /* This static is for the verify callback */
973         _ssl_server_cname = servercname;
974         _server_label = label;
975         _check_fp = 1;
976         _check_digest = fingerprint;
977         _depth0ck = 0;
978         _prev_err = -1;
979
980         if( mycert || mykey ) {
981
982         /* Ok...  He has a certificate file defined, so lets declare it.  If
983          * he does NOT have a separate certificate and private key file then
984          * assume that it's a combined key and certificate file.
985          */
986                 if( !mykey )
987                         mykey = mycert;
988                 if( !mycert )
989                         mycert = mykey;
990                 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
991                 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
992         }
993
994         SSL_set_fd(_ssl_context[sock], sock);
995         
996         if(SSL_connect(_ssl_context[sock]) < 1) {
997                 ERR_print_errors_fp(stderr);
998                 return(-1);
999         }
1000
1001         /* Paranoia: was the callback not called as we expected? */
1002         if (!_depth0ck) {
1003                 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
1004
1005                 if (fingerprint != NULL || certck) {
1006                         if( NULL != SSLGetContext( sock ) ) {
1007                                 /* Clean up the SSL stack */
1008                                 SSL_free( _ssl_context[sock] );
1009                                 _ssl_context[sock] = NULL;
1010                         }
1011                         return(-1);
1012                 }
1013         }
1014
1015         return(0);
1016 }
1017 #endif
1018
1019 int SockClose(int sock)
1020 /* close a socket gracefully */
1021 {
1022 #ifdef  SSL_ENABLE
1023     if( NULL != SSLGetContext( sock ) ) {
1024         /* Clean up the SSL stack */
1025         SSL_free( _ssl_context[sock] );
1026         _ssl_context[sock] = NULL;
1027     }
1028 #endif
1029
1030 #ifdef __UNUSED__
1031     /* 
1032      * This hangs in RedHat 6.2 after fetchmail runs for a while a
1033      * FIN_WAIT2 comes up in netstat and fetchmail never returns from
1034      * the recv system call. (Reported from jtnews
1035      * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
1036      *
1037      * Half-close the connection first so the other end gets notified.
1038      *
1039      * This stops sends but allows receives (effectively, it sends a
1040      * TCP <FIN>).  */
1041     if (shutdown(sock, 1) == 0) {
1042         char ch;
1043         /* If there is any data still waiting in the queue, discard it.
1044          * Call recv() until either it returns 0 (meaning we received a FIN)
1045          * or any error occurs.  This makes sure all data sent by the other
1046          * side is acknowledged at the TCP level.
1047          */
1048         if (fm_peek(sock, &ch, 1) > 0)
1049             while (fm_read(sock, &ch, 1) > 0)
1050                 continue;
1051     }
1052 #endif /* __UNUSED__ */
1053
1054     /* if there's an error closing at this point, not much we can do */
1055     return(fm_close(sock));     /* this is guarded */
1056 }
1057
1058 #ifdef __CYGWIN__
1059 /*
1060  * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1061  * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1062  * for more details.
1063  */
1064 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1065 {
1066     char *bp = buf;
1067     int n = 0;
1068
1069     if ((n = read(sock, bp, count)) == -1)
1070         return(-1);
1071
1072     if (n != count) {
1073         int n2 = 0;
1074         if (outlevel >= O_VERBOSE)
1075             report(stdout, GT_("Cygwin socket read retry\n"));
1076         n2 = read(sock, bp + n, count - n);
1077         if (n2 == -1 || n + n2 != count) {
1078             report(stderr, GT_("Cygwin socket read retry failed!\n"));
1079             return(-1);
1080         }
1081     }
1082
1083     return count;
1084 }
1085 #endif /* __CYGWIN__ */
1086
1087 #ifdef MAIN
1088 /*
1089  * Use the chargen service to test input buffering directly.
1090  * You may have to uncomment the `chargen' service description in your
1091  * inetd.conf (and then SIGHUP inetd) for this to work.  */
1092 main()
1093 {
1094     int         sock = SockOpen("localhost", 19, NULL);
1095     char        buf[80];
1096
1097     while (SockRead(sock, buf, sizeof(buf)-1))
1098         SockWrite(1, buf, strlen(buf));
1099     SockClose(sock);
1100 }
1101 #endif /* MAIN */
1102
1103 /* socket.c ends here */