]> Pileus Git - ~andy/fetchmail/blob - socket.c
Fix socket timeout handling.
[~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 #if TIME_WITH_SYS_TIME
41 # include <sys/time.h>
42 # include <time.h>
43 #else
44 # if HAVE_SYS_TIME_H
45 #  include <sys/time.h>
46 # else
47 #  include <time.h>
48 # endif
49 #endif
50
51 #include "socket.h"
52 #include "fetchmail.h"
53 #include "getaddrinfo.h"
54 #include "i18n.h"
55 #include "sdump.h"
56
57 /* Defines to allow BeOS and Cygwin to play nice... */
58 #ifdef __BEOS__
59 static char peeked;
60 #define fm_close(a)  closesocket(a)
61 #define fm_write(a,b,c)  send(a,b,c,0)
62 #define fm_peek(a,b,c)   recv(a,b,c,0)
63 #define fm_read(a,b,c)   recv(a,b,c,0)
64 #else
65 #define fm_close(a)  close(a)
66 #define fm_write(a,b,c)  write(a,b,c)
67 #define fm_peek(a,b,c)   recv(a,b,c, MSG_PEEK)
68 #ifdef __CYGWIN__
69 #define fm_read(a,b,c)   cygwin_read(a,b,c)
70 static ssize_t cygwin_read(int sock, void *buf, size_t count);
71 #else /* ! __CYGWIN__ */
72 #define fm_read(a,b,c)   read(a,b,c)
73 #endif /* __CYGWIN__ */
74 #endif
75
76 /* We need to define h_errno only if it is not already */
77 #ifndef h_errno
78 # if !HAVE_DECL_H_ERRNO
79 extern int h_errno;
80 # endif
81 #endif /* ndef h_errno */
82
83 #ifdef HAVE_SOCKETPAIR
84 static char *const *parse_plugin(const char *plugin, const char *host, const char *service)
85 {
86         char **argvec;
87         const char *c, *p;
88         char *cp, *plugin_copy;
89         unsigned int plugin_copy_len;
90         unsigned int plugin_offset = 0, plugin_copy_offset = 0;
91         unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
92         unsigned int plugin_len = strlen(plugin);
93         unsigned int host_len = strlen(host);
94         unsigned int service_len = strlen(service);
95
96         for (c = p = plugin; *c; c++)
97         {       if (isspace((unsigned char)*c) && !isspace((unsigned char)*p))
98                         s += sizeof(char*);
99                 if (*p == '%' && *c == 'h')
100                         host_count++;
101                 if (*p == '%' && *c == 'p')
102                         service_count++;
103                 p = c;
104         }
105
106         plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
107         plugin_copy = (char *)malloc(plugin_copy_len + 1);
108         if (!plugin_copy)
109         {
110                 report(stderr, GT_("fetchmail: malloc failed\n"));
111                 return NULL;
112         }
113
114         while (plugin_copy_offset < plugin_copy_len)
115         {       if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
116                 {       strcpy(plugin_copy + plugin_copy_offset, host);
117                         plugin_offset += 2;
118                         plugin_copy_offset += host_len;
119                 }
120                 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
121                 {       strcpy(plugin_copy + plugin_copy_offset, service);
122                         plugin_offset += 2;
123                         plugin_copy_offset += service_len;
124                 }
125                 else
126                 {       plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
127                         plugin_offset++;
128                         plugin_copy_offset++;
129                 }
130         }
131         plugin_copy[plugin_copy_len] = 0;
132
133         argvec = (char **)malloc(s);
134         if (!argvec)
135         {
136                 report(stderr, GT_("fetchmail: malloc failed\n"));
137                 return NULL;
138         }
139         memset(argvec, 0, s);
140         for (p = cp = plugin_copy, i = 0; *cp; cp++)
141         {       if ((!isspace((unsigned char)*cp)) && (cp == p ? 1 : isspace((unsigned char)*p))) {
142                         argvec[i] = cp;
143                         i++;
144                 }
145                 p = cp;
146         }
147         for (cp = plugin_copy; *cp; cp++)
148         {       if (isspace((unsigned char)*cp))
149                         *cp = 0;
150         }
151         return argvec;
152 }
153
154 static int handle_plugin(const char *host,
155                          const char *service, const char *plugin)
156 /* get a socket mediated through a given external command */
157 {
158     int fds[2];
159     char *const *argvec;
160
161     /*
162      * The author of this code, Felix von Leitner <felix@convergence.de>, says:
163      * he chose socketpair() instead of pipe() because socketpair creates 
164      * bidirectional sockets while allegedly some pipe() implementations don't.
165      */
166     if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
167     {
168         report(stderr, GT_("fetchmail: socketpair failed\n"));
169         return -1;
170     }
171     switch (fork()) {
172         case -1:
173                 /* error */
174                 report(stderr, GT_("fetchmail: fork failed\n"));
175                 return -1;
176         case 0: /* child */
177                 /* fds[1] is the parent's end; close it for proper EOF
178                 ** detection */
179                 (void) close(fds[1]);
180                 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
181                         report(stderr, GT_("dup2 failed\n"));
182                         _exit(EXIT_FAILURE);
183                 }
184                 /* fds[0] is now connected to 0 and 1; close it */
185                 (void) close(fds[0]);
186                 if (outlevel >= O_VERBOSE)
187                     report(stderr, GT_("running %s (host %s service %s)\n"), plugin, host, service);
188                 argvec = parse_plugin(plugin,host,service);
189                 execvp(*argvec, argvec);
190                 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
191                 _exit(EXIT_FAILURE);
192                 break;
193         default:        /* parent */
194                 /* NOP */
195                 break;
196     }
197     /* fds[0] is the child's end; close it for proper EOF detection */
198     (void) close(fds[0]);
199     return fds[1];
200 }
201 #endif /* HAVE_SOCKETPAIR */
202
203 static int setsocktimeout(int sock, int which, int timeout) {
204     struct timeval tv;
205     int rc;
206
207     tv.tv_sec = timeout;
208     tv.tv_usec = 0;
209     rc = setsockopt(sock, SOL_SOCKET, which, &tv, sizeof(tv));
210     if (rc) {
211         report(stderr, GT_("setsockopt(%d, SOL_SOCKET) failed: %s"), sock, strerror(errno));
212     }
213     return rc;
214 }
215
216 /** Configure socket options such as send/receive timeout at the socket
217  * level, to avoid network-induced stalls.
218  */
219 int SockTimeout(int sock, int timeout)
220 {
221     int err = 0;
222
223     if (setsocktimeout(sock, SO_RCVTIMEO, timeout)) err = 1;
224     if (setsocktimeout(sock, SO_SNDTIMEO, timeout)) err = 1;
225     return err;
226 }
227
228 /** Set socket to SO_KEEPALIVE. \return 0 for success. */
229 int SockKeepalive(int sock) {
230     int keepalive = 1;
231     return setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof keepalive);
232 }
233
234 int UnixOpen(const char *path)
235 {
236     int sock = -1;
237     struct sockaddr_un ad;
238     memset(&ad, 0, sizeof(ad));
239     ad.sun_family = AF_UNIX;
240     strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
241
242     sock = socket( AF_UNIX, SOCK_STREAM, 0 );
243     if (sock < 0)
244     {
245         h_errno = 0;
246         return -1;
247     }
248
249     /* Socket opened saved. Usefull if connect timeout 
250      * because it can be closed.
251      */
252     mailserver_socket_temp = sock;
253
254     SockTimeout(sock, mytimeout);
255     if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
256     {
257         int olderr = errno;
258         fm_close(sock); /* don't use SockClose, no traffic yet */
259         h_errno = 0;
260         errno = olderr;
261         sock = -1;
262     }
263
264     /* No connect timeout, then no need to set mailserver_socket_temp */
265     mailserver_socket_temp = -1;
266
267     return sock;
268 }
269
270 int SockOpen(const char *host, const char *service,
271              const char *plugin, struct addrinfo **ai0)
272 {
273     struct addrinfo *ai, req;
274     int i, acterr = 0;
275     int ord;
276     char errbuf[8192] = "";
277
278 #ifdef HAVE_SOCKETPAIR
279     if (plugin)
280         return handle_plugin(host,service,plugin);
281 #endif /* HAVE_SOCKETPAIR */
282
283     memset(&req, 0, sizeof(struct addrinfo));
284     req.ai_socktype = SOCK_STREAM;
285 #ifdef AI_ADDRCONFIG
286     req.ai_flags = AI_ADDRCONFIG;
287 #endif
288
289     i = fm_getaddrinfo(host, service, &req, ai0);
290     if (i) {
291         report(stderr, GT_("getaddrinfo(\"%s\",\"%s\") error: %s\n"),
292                 host, service, gai_strerror(i));
293         if (i == EAI_SERVICE)
294             report(stderr, GT_("Try adding the --service option (see also FAQ item R12).\n"));
295         return -1;
296     }
297
298     /* NOTE a Linux bug here - getaddrinfo will happily return 127.0.0.1
299      * twice if no IPv6 is configured */
300     i = -1;
301     for (ord = 0, ai = *ai0; ai; ord++, ai = ai->ai_next) {
302         char buf[256]; /* hostname */
303         char pb[256];  /* service name */
304         int gnie;      /* getnameinfo result code */
305
306         gnie = getnameinfo(ai->ai_addr, ai->ai_addrlen, buf, sizeof(buf), NULL, 0, NI_NUMERICHOST);
307         if (gnie)
308             snprintf(buf, sizeof(buf), GT_("unknown (%s)"), gai_strerror(gnie));
309         gnie = getnameinfo(ai->ai_addr, ai->ai_addrlen, NULL, 0, pb, sizeof(pb), NI_NUMERICSERV);
310         if (gnie)
311             snprintf(pb, sizeof(pb), GT_("unknown (%s)"), gai_strerror(gnie));
312
313         if (outlevel >= O_VERBOSE)
314             report_build(stdout, GT_("Trying to connect to %s/%s..."), buf, pb);
315         i = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
316         if (i < 0) {
317             int e = errno;
318             /* mask EAFNOSUPPORT errors, they confuse users for
319              * multihomed hosts */
320             if (errno != EAFNOSUPPORT)
321                 acterr = errno;
322             if (outlevel >= O_VERBOSE)
323                 report_complete(stdout, GT_("cannot create socket: %s\n"), strerror(e));
324             snprintf(errbuf+strlen(errbuf), sizeof(errbuf)-strlen(errbuf),\
325                      GT_("name %d: cannot create socket family %d type %d: %s\n"), ord, ai->ai_family, ai->ai_socktype, strerror(e));
326             continue;
327         }
328
329         SockTimeout(i, mytimeout);
330         SockKeepalive(i);
331
332         /* Save socket descriptor.
333          * Used to close the socket after connect timeout. */
334         mailserver_socket_temp = i;
335
336         if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
337             int e = errno;
338
339             /* additionally, suppress IPv4 network unreach errors */
340             if (e != EAFNOSUPPORT)
341                 acterr = errno;
342
343             if (outlevel >= O_VERBOSE)
344                 report_complete(stdout, GT_("connection failed.\n"));
345             if (outlevel >= O_VERBOSE)
346                 report(stderr, GT_("connection to %s:%s [%s/%s] failed: %s.\n"), host, service, buf, pb, strerror(e));
347             snprintf(errbuf+strlen(errbuf), sizeof(errbuf)-strlen(errbuf), GT_("name %d: connection to %s:%s [%s/%s] failed: %s.\n"), ord, host, service, buf, pb, strerror(e));
348             fm_close(i);
349             i = -1;
350             continue;
351         } else {
352             if (outlevel >= O_VERBOSE)
353                 report_complete(stdout, GT_("connected.\n"));
354         }
355
356         /* No connect timeout, then no need to set mailserver_socket_temp */
357         mailserver_socket_temp = -1;
358
359         break;
360     }
361
362     fm_freeaddrinfo(*ai0);
363     *ai0 = NULL;
364
365     if (i == -1) {
366         report(stderr, GT_("Connection errors for this poll:\n%s"), errbuf);
367         errno = acterr;
368     }
369
370     return i;
371 }
372
373
374 #if defined(HAVE_STDARG_H)
375 int SockPrintf(int sock, const char* format, ...)
376 {
377 #else
378 int SockPrintf(sock,format,va_alist)
379 int sock;
380 char *format;
381 va_dcl {
382 #endif
383
384     va_list ap;
385     char buf[8192];
386
387 #if defined(HAVE_STDARG_H)
388     va_start(ap, format) ;
389 #else
390     va_start(ap);
391 #endif
392     vsnprintf(buf, sizeof(buf), format, ap);
393     va_end(ap);
394     SockTimeout(sock, mytimeout);
395     return SockWrite(sock, buf, strlen(buf));
396 }
397
398 #ifdef SSL_ENABLE
399 #include <openssl/ssl.h>
400 #include <openssl/err.h>
401 #include <openssl/pem.h>
402 #include <openssl/x509v3.h>
403 #include <openssl/rand.h>
404
405 static  SSL_CTX *_ctx[FD_SETSIZE];
406 static  SSL *_ssl_context[FD_SETSIZE];
407
408 static SSL      *SSLGetContext( int );
409 #endif /* SSL_ENABLE */
410
411 int SockWrite(int sock, const char *buf, int len)
412 {
413     int n, wrlen = 0;
414 #ifdef  SSL_ENABLE
415     SSL *ssl;
416 #endif
417
418     while (len)
419     {
420 #ifdef SSL_ENABLE
421         if( NULL != ( ssl = SSLGetContext( sock ) ) )
422                 n = SSL_write(ssl, buf, len);
423         else
424 #endif /* SSL_ENABLE */
425             n = fm_write(sock, buf, len);
426         if (n <= 0)
427             return -1;
428         len -= n;
429         wrlen += n;
430         buf += n;
431     }
432     return wrlen;
433 }
434
435 int SockRead(int sock, char *buf, int len)
436 {
437     char *newline, *bp = buf;
438     int n;
439 #ifdef  SSL_ENABLE
440     SSL *ssl;
441 #endif
442
443     if (--len < 1)
444         return(-1);
445 #ifdef __BEOS__
446     if (peeked != 0){
447         (*bp) = peeked;
448         bp++;
449         len--;
450         peeked = 0;
451     }
452 #endif        
453     do {
454         /* 
455          * The reason for these gymnastics is that we want two things:
456          * (1) to read \n-terminated lines,
457          * (2) to return the true length of data read, even if the
458          *     data coming in has embedded NULS.
459          */
460 #ifdef  SSL_ENABLE
461         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
462                 /* Hack alert! */
463                 /* OK...  SSL_peek works a little different from MSG_PEEK
464                         Problem is that SSL_peek can return 0 if there
465                         is no data currently available.  If, on the other
466                         hand, we lose the socket, we also get a zero, but
467                         the SSL_read then SEGFAULTS!  To deal with this,
468                         we'll check the error code any time we get a return
469                         of zero from SSL_peek.  If we have an error, we bail.
470                         If we don't, we read one character in SSL_read and
471                         loop.  This should continue to work even if they
472                         later change the behavior of SSL_peek
473                         to "fix" this problem...  :-(   */
474                 if ((n = SSL_peek(ssl, bp, len)) < 0) {
475                         (void)SSL_get_error(ssl, n);
476                         return(-1);
477                 }
478                 if( 0 == n ) {
479                         /* SSL_peek says no data...  Does he mean no data
480                         or did the connection blow up?  If we got an error
481                         then bail! */
482                         if (0 != SSL_get_error(ssl, n)) {
483                                 return -1;
484                         }
485                         /* We didn't get an error so read at least one
486                                 character at this point and loop */
487                         n = 1;
488                         /* Make sure newline start out NULL!
489                          * We don't have a string to pass through
490                          * the strchr at this point yet */
491                         newline = NULL;
492                 } else if ((newline = (char *)memchr(bp, '\n', n)) != NULL)
493                         n = newline - bp + 1;
494                 /* Matthias Andree: SSL_read can return 0, in that case
495                  * we must call SSL_get_error to figure if there was
496                  * an error or just a "no data" condition */
497                 if ((n = SSL_read(ssl, bp, n)) <= 0) {
498                         if ((n = SSL_get_error(ssl, n))) {
499                                 return(-1);
500                         }
501                 }
502                 /* Check for case where our single character turned out to
503                  * be a newline...  (It wasn't going to get caught by
504                  * the strchr above if it came from the hack...  ). */
505                 if( NULL == newline && 1 == n && '\n' == *bp ) {
506                         /* Got our newline - this will break
507                                 out of the loop now */
508                         newline = bp;
509                 }
510         }
511         else
512 #endif /* SSL_ENABLE */
513         {
514
515 #ifdef __BEOS__
516             if ((n = fm_read(sock, bp, 1)) <= 0)
517 #else
518             if ((n = fm_peek(sock, bp, len)) <= 0)
519 #endif
520                 return (-1);
521             if ((newline = (char *)memchr(bp, '\n', n)) != NULL)
522                 n = newline - bp + 1;
523 #ifndef __BEOS__
524             if ((n = fm_read(sock, bp, n)) == -1)
525                 return(-1);
526 #endif /* __BEOS__ */
527         }
528         bp += n;
529         len -= n;
530     } while 
531             (!newline && len);
532     *bp = '\0';
533
534     return bp - buf;
535 }
536
537 int SockPeek(int sock)
538 /* peek at the next socket character without actually reading it */
539 {
540     int n;
541     char ch;
542 #ifdef  SSL_ENABLE
543     SSL *ssl;
544 #endif
545
546 #ifdef  SSL_ENABLE
547         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
548                 n = SSL_peek(ssl, &ch, 1);
549                 if (n < 0) {
550                         (void)SSL_get_error(ssl, n);
551                         return -1;
552                 }
553                 if( 0 == n ) {
554                         /* This code really needs to implement a "hold back"
555                          * to simulate a functioning SSL_peek()...  sigh...
556                          * Has to be coordinated with the read code above.
557                          * Next on the list todo...     */
558
559                         /* SSL_peek says 0...  Does that mean no data
560                         or did the connection blow up?  If we got an error
561                         then bail! */
562                         if(0 != SSL_get_error(ssl, n)) {
563                                 return -1;
564                         }
565
566                         /* Haven't seen this case actually occur, but...
567                            if the problem in SockRead can occur, this should
568                            be possible...  Just not sure what to do here.
569                            This should be a safe "punt" the "peek" but don't
570                            "punt" the "session"... */
571
572                         return 0;       /* Give him a '\0' character */
573                 }
574         }
575         else
576 #endif /* SSL_ENABLE */
577             n = fm_peek(sock, &ch, 1);
578         if (n == -1)
579                 return -1;
580
581 #ifdef __BEOS__
582     peeked = ch;
583 #endif
584     return(ch);
585 }
586
587 #ifdef SSL_ENABLE
588
589 static  char *_ssl_server_cname = NULL;
590 static  int _check_fp;
591 static  char *_check_digest;
592 static  char *_server_label;
593 static  int _depth0ck;
594 static  int _firstrun;
595 static  int _prev_err;
596 static  int _verify_ok;
597
598 SSL *SSLGetContext( int sock )
599 {
600         if( sock < 0 || (unsigned)sock > FD_SETSIZE )
601                 return NULL;
602         if( _ctx[sock] == NULL )
603                 return NULL;
604         return _ssl_context[sock];
605 }
606
607 /* ok_return (preverify_ok) is 1 if this stage of certificate verification
608    passed, or 0 if it failed. This callback lets us display informative
609    errors, and perform additional validation (e.g. CN matches) */
610 static int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
611 {
612 #define SSLverbose (((outlevel) >= O_DEBUG) || ((outlevel) >= O_VERBOSE && (depth) == 0)) 
613         char buf[257];
614         X509 *x509_cert;
615         int err, depth, i;
616         unsigned char digest[EVP_MAX_MD_SIZE];
617         char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
618         const EVP_MD *digest_tp;
619         unsigned int dsz, esz;
620         X509_NAME *subj, *issuer;
621         char *tt;
622
623         x509_cert = X509_STORE_CTX_get_current_cert(ctx);
624         err = X509_STORE_CTX_get_error(ctx);
625         depth = X509_STORE_CTX_get_error_depth(ctx);
626
627         subj = X509_get_subject_name(x509_cert);
628         issuer = X509_get_issuer_name(x509_cert);
629
630         if (outlevel >= O_VERBOSE) {
631                 if (depth == 0 && SSLverbose)
632                         report(stderr, GT_("Server certificate:\n"));
633                 else {
634                         if (_firstrun) {
635                                 _firstrun = 0;
636                                 if (SSLverbose)
637                                         report(stdout, GT_("Certificate chain, from root to peer, starting at depth %d:\n"), depth);
638                         } else {
639                                 if (SSLverbose)
640                                         report(stdout, GT_("Certificate at depth %d:\n"), depth);
641                         }
642                 }
643
644                 if (SSLverbose) {
645                         if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
646                                 report(stdout, GT_("Issuer Organization: %s\n"), (tt = sdump(buf, i)));
647                                 xfree(tt);
648                                 if ((size_t)i >= sizeof(buf) - 1)
649                                         report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
650                         } else
651                                 report(stdout, GT_("Unknown Organization\n"));
652                         if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
653                                 report(stdout, GT_("Issuer CommonName: %s\n"), (tt = sdump(buf, i)));
654                                 xfree(tt);
655                                 if ((size_t)i >= sizeof(buf) - 1)
656                                         report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
657                         } else
658                                 report(stdout, GT_("Unknown Issuer CommonName\n"));
659                 }
660         }
661
662         if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
663                 if (SSLverbose) {
664                         report(stdout, GT_("Subject CommonName: %s\n"), (tt = sdump(buf, i)));
665                         xfree(tt);
666                 }
667                 if ((size_t)i >= sizeof(buf) - 1) {
668                         /* Possible truncation. In this case, this is a DNS name, so this
669                          * is really bad. We do not tolerate this even in the non-strict case. */
670                         report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
671                         return (0);
672                 }
673                 if ((size_t)i > strlen(buf)) {
674                         /* Name contains embedded NUL characters, so we complain. This is likely
675                          * a certificate spoofing attack. */
676                         report(stderr, GT_("Bad certificate: Subject CommonName contains NUL, aborting!\n"));
677                         return 0;
678                 }
679         }
680
681         if (depth == 0) { /* peer certificate */
682                 if (!_depth0ck) {
683                         _depth0ck = 1;
684                 }
685
686                 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
687                         if (_ssl_server_cname != NULL) {
688                                 char *p1 = buf;
689                                 char *p2 = _ssl_server_cname;
690                                 int matched = 0;
691                                 STACK_OF(GENERAL_NAME) *gens;
692
693                                 /* RFC 2595 section 2.4: find a matching name
694                                  * first find a match among alternative names */
695                                 gens = (STACK_OF(GENERAL_NAME) *)X509_get_ext_d2i(x509_cert, NID_subject_alt_name, NULL, NULL);
696                                 if (gens) {
697                                         int j, r;
698                                         for (j = 0, r = sk_GENERAL_NAME_num(gens); j < r; ++j) {
699                                                 const GENERAL_NAME *gn = sk_GENERAL_NAME_value(gens, j);
700                                                 if (gn->type == GEN_DNS) {
701                                                         char *pp1 = (char *)gn->d.ia5->data;
702                                                         char *pp2 = _ssl_server_cname;
703                                                         if (outlevel >= O_VERBOSE) {
704                                                                 report(stdout, GT_("Subject Alternative Name: %s\n"), (tt = sdump(pp1, (size_t)gn->d.ia5->length)));
705                                                                 xfree(tt);
706                                                         }
707                                                         /* Name contains embedded NUL characters, so we complain. This
708                                                          * is likely a certificate spoofing attack. */
709                                                         if ((size_t)gn->d.ia5->length != strlen(pp1)) {
710                                                                 report(stderr, GT_("Bad certificate: Subject Alternative Name contains NUL, aborting!\n"));
711                                                                 sk_GENERAL_NAME_free(gens);
712                                                                 return 0;
713                                                         }
714                                                         if (name_match(pp1, pp2)) {
715                                                             matched = 1;
716                                                         }
717                                                 }
718                                         }
719                                         sk_GENERAL_NAME_free(gens);
720                                 }
721                                 if (name_match(p1, p2)) {
722                                         matched = 1;
723                                 }
724                                 if (!matched) {
725                                         if (strict || SSLverbose) {
726                                                 report(stderr,
727                                                                 GT_("Server CommonName mismatch: %s != %s\n"),
728                                                                 (tt = sdump(buf, i)), _ssl_server_cname );
729                                                 xfree(tt);
730                                         }
731                                         ok_return = 0;
732                                 }
733                         } else if (ok_return) {
734                                 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
735                                 if (strict) return (0);
736                         }
737                 } else {
738                         if (outlevel >= O_VERBOSE)
739                                 report(stdout, GT_("Unknown Server CommonName\n"));
740                         if (ok_return && strict) {
741                                 report(stderr, GT_("Server name not specified in certificate!\n"));
742                                 return (0);
743                         }
744                 }
745                 /* Print the finger print. Note that on errors, we might print it more than once
746                  * normally; we kluge around that by using a global variable. */
747                 if (_check_fp == 1) {
748                         unsigned dp;
749
750                         _check_fp = -1;
751                         digest_tp = EVP_md5();
752                         if (digest_tp == NULL) {
753                                 report(stderr, GT_("EVP_md5() failed!\n"));
754                                 return (0);
755                         }
756                         if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
757                                 report(stderr, GT_("Out of memory!\n"));
758                                 return (0);
759                         }
760                         tp = text;
761                         te = text + sizeof(text);
762                         for (dp = 0; dp < dsz; dp++) {
763                                 esz = snprintf(tp, te - tp, dp > 0 ? ":%02X" : "%02X", digest[dp]);
764                                 if (esz >= (size_t)(te - tp)) {
765                                         report(stderr, GT_("Digest text buffer too small!\n"));
766                                         return (0);
767                                 }
768                                 tp += esz;
769                         }
770                         if (outlevel > O_NORMAL)
771                             report(stdout, GT_("%s key fingerprint: %s\n"), _server_label, text);
772                         if (_check_digest != NULL) {
773                                 if (strcasecmp(text, _check_digest) == 0) {
774                                     if (outlevel > O_NORMAL)
775                                         report(stdout, GT_("%s fingerprints match.\n"), _server_label);
776                                 } else {
777                                     report(stderr, GT_("%s fingerprints do not match!\n"), _server_label);
778                                     return (0);
779                                 }
780                         } /* if (_check_digest != NULL) */
781                 } /* if (_check_fp) */
782         } /* if (depth == 0 && !_depth0ck) */
783
784         if (err != X509_V_OK && err != _prev_err && !(_check_fp != 0 && _check_digest && !strict)) {
785                 _prev_err = err;
786                                         
787                 report(stderr, GT_("Server certificate verification error: %s\n"), X509_verify_cert_error_string(err));
788                 /* We gave the error code, but maybe we can add some more details for debugging */
789
790                 switch (err) {
791                 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
792                         X509_NAME_oneline(issuer, buf, sizeof(buf));
793                         buf[sizeof(buf) - 1] = '\0';
794                         report(stderr, GT_("unknown issuer (first %d characters): %s\n"), (int)(sizeof(buf)-1), buf);
795                         report(stderr, GT_("This error usually happens when the server provides an incomplete certificate "
796                                                 "chain, which is nothing fetchmail could do anything about.  For details, "
797                                                 "please see the README.SSL-SERVER document that comes with fetchmail.\n"));
798                         break;
799                 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
800                 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
801                 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
802                         X509_NAME_oneline(subj, buf, sizeof(buf));
803                         buf[sizeof(buf) - 1] = '\0';
804                         report(stderr, GT_("This means that the root signing certificate (issued for %s) is not in the "
805                                                 "trusted CA certificate locations, or that c_rehash needs to be run "
806                                                 "on the certificate directory. For details, please "
807                                                 "see the documentation of --sslcertpath and --sslcertfile in the manual page.\n"), buf);
808                         break;
809                 default:
810                         break;
811                 }
812         }
813         /*
814          * If not in strict checking mode (--sslcertck), override this
815          * and pretend that verification had succeeded.
816          */
817         _verify_ok &= ok_return;
818         if (!strict)
819                 ok_return = 1;
820         return (ok_return);
821 }
822
823 static int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
824 {
825         return SSL_verify_callback(ok_return, ctx, 0);
826 }
827
828 static int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
829 {
830         return SSL_verify_callback(ok_return, ctx, 1);
831 }
832
833
834 /* get commonName from certificate set in file.
835  * commonName is stored in buffer namebuffer, limited with namebufferlen
836  */
837 static const char *SSLCertGetCN(const char *mycert,
838                                 char *namebuffer, size_t namebufferlen)
839 {
840         const char *ret       = NULL;
841         BIO        *certBio   = NULL;
842         X509       *x509_cert = NULL;
843         X509_NAME  *certname  = NULL;
844
845         if (namebuffer && namebufferlen > 0) {
846                 namebuffer[0] = 0x00;
847                 certBio = BIO_new_file(mycert,"r");
848                 if (certBio) {
849                         x509_cert = PEM_read_bio_X509(certBio,NULL,NULL,NULL);
850                         BIO_free(certBio);
851                 }
852                 if (x509_cert) {
853                         certname = X509_get_subject_name(x509_cert);
854                         if (certname &&
855                             X509_NAME_get_text_by_NID(certname, NID_commonName,
856                                                       namebuffer, namebufferlen) > 0)
857                                 ret = namebuffer;
858                         X509_free(x509_cert);
859                 }
860         }
861         return ret;
862 }
863
864 /* performs initial SSL handshake over the connected socket
865  * uses SSL *ssl global variable, which is currently defined
866  * in this file
867  */
868 int SSLOpen(int sock, char *mycert, char *mykey, const char *myproto, int certck,
869     char *cacertfile, char *certpath,
870     char *fingerprint, char *servercname, char *label, char **remotename)
871 {
872         struct stat randstat;
873         int i;
874
875         SSL_load_error_strings();
876         SSL_library_init();
877         OpenSSL_add_all_algorithms(); /* see Debian Bug#576430 and manpage */
878
879         if (stat("/dev/random", &randstat)  &&
880             stat("/dev/urandom", &randstat)) {
881           /* Neither /dev/random nor /dev/urandom are present, so add
882              entropy to the SSL PRNG a hard way. */
883           for (i = 0; i < 10000  &&  ! RAND_status (); ++i) {
884             char buf[4];
885             struct timeval tv;
886             gettimeofday (&tv, 0);
887             buf[0] = tv.tv_usec & 0xF;
888             buf[2] = (tv.tv_usec & 0xF0) >> 4;
889             buf[3] = (tv.tv_usec & 0xF00) >> 8;
890             buf[1] = (tv.tv_usec & 0xF000) >> 12;
891             RAND_add (buf, sizeof buf, 0.1);
892           }
893         }
894
895         if( sock < 0 || (unsigned)sock > FD_SETSIZE ) {
896                 report(stderr, GT_("File descriptor out of range for SSL") );
897                 return( -1 );
898         }
899
900         /* Make sure a connection referring to an older context is not left */
901         _ssl_context[sock] = NULL;
902         if(myproto) {
903                 if(!strcasecmp("ssl2",myproto)) {
904                         _ctx[sock] = SSL_CTX_new(SSLv2_client_method());
905                 } else if(!strcasecmp("ssl3",myproto)) {
906                         _ctx[sock] = SSL_CTX_new(SSLv3_client_method());
907                 } else if(!strcasecmp("tls1",myproto)) {
908                         _ctx[sock] = SSL_CTX_new(TLSv1_client_method());
909                 } else if (!strcasecmp("ssl23",myproto)) {
910                         myproto = NULL;
911                 } else {
912                         fprintf(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
913                         myproto = NULL;
914                 }
915         }
916         if(!myproto) {
917                 _ctx[sock] = SSL_CTX_new(SSLv23_client_method());
918         }
919         if(_ctx[sock] == NULL) {
920                 ERR_print_errors_fp(stderr);
921                 return(-1);
922         }
923
924         SSL_CTX_set_options(_ctx[sock], SSL_OP_ALL);
925
926         if (certck) {
927                 SSL_CTX_set_verify(_ctx[sock], SSL_VERIFY_PEER, SSL_ck_verify_callback);
928         } else {
929                 /* In this case, we do not fail if verification fails. However,
930                  * we provide the callback for output and possible fingerprint
931                  * checks. */
932                 SSL_CTX_set_verify(_ctx[sock], SSL_VERIFY_PEER, SSL_nock_verify_callback);
933         }
934
935         /* Check which trusted X.509 CA certificate store(s) to load */
936         {
937                 char *tmp;
938                 int want_default_cacerts = 0;
939
940                 /* Load user locations if any is given */
941                 if (certpath || cacertfile)
942                         SSL_CTX_load_verify_locations(_ctx[sock],
943                                                 cacertfile, certpath);
944                 else
945                         want_default_cacerts = 1;
946
947                 tmp = getenv("FETCHMAIL_INCLUDE_DEFAULT_X509_CA_CERTS");
948                 if (want_default_cacerts || (tmp && tmp[0])) {
949                         SSL_CTX_set_default_verify_paths(_ctx[sock]);
950                 }
951         }
952         
953         _ssl_context[sock] = SSL_new(_ctx[sock]);
954         
955         if(_ssl_context[sock] == NULL) {
956                 ERR_print_errors_fp(stderr);
957                 SSL_CTX_free(_ctx[sock]);
958                 _ctx[sock] = NULL;
959                 return(-1);
960         }
961         
962         /* This static is for the verify callback */
963         _ssl_server_cname = servercname;
964         _server_label = label;
965         _check_fp = 1;
966         _check_digest = fingerprint;
967         _depth0ck = 0;
968         _firstrun = 1;
969         _verify_ok = 1;
970         _prev_err = -1;
971
972         if( mycert || mykey ) {
973
974         /* Ok...  He has a certificate file defined, so lets declare it.  If
975          * he does NOT have a separate certificate and private key file then
976          * assume that it's a combined key and certificate file.
977          */
978                 char buffer[256];
979                 
980                 if( !mykey )
981                         mykey = mycert;
982                 if( !mycert )
983                         mycert = mykey;
984
985                 if ((!*remotename || !**remotename) && SSLCertGetCN(mycert, buffer, sizeof(buffer))) {
986                         free(*remotename);
987                         *remotename = xstrdup(buffer);
988                 }
989                 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
990                 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
991         }
992
993         if (SSL_set_fd(_ssl_context[sock], sock) == 0 
994             || SSL_connect(_ssl_context[sock]) < 1) {
995                 ERR_print_errors_fp(stderr);
996                 SSL_free( _ssl_context[sock] );
997                 _ssl_context[sock] = NULL;
998                 SSL_CTX_free(_ctx[sock]);
999                 _ctx[sock] = NULL;
1000                 return(-1);
1001         }
1002
1003         /* Paranoia: was the callback not called as we expected? */
1004         if (!_depth0ck) {
1005                 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
1006
1007                 if (fingerprint != NULL || certck) {
1008                         if( NULL != SSLGetContext( sock ) ) {
1009                                 /* Clean up the SSL stack */
1010                                 SSL_shutdown( _ssl_context[sock] );
1011                                 SSL_free( _ssl_context[sock] );
1012                                 _ssl_context[sock] = NULL;
1013                                 SSL_CTX_free(_ctx[sock]);
1014                                 _ctx[sock] = NULL;
1015                         }
1016                         return(-1);
1017                 }
1018         }
1019
1020         if (!certck && !fingerprint &&
1021                 (SSL_get_verify_result(_ssl_context[sock]) != X509_V_OK || !_verify_ok)) {
1022                 report(stderr, GT_("Warning: the connection is insecure, continuing anyways. (Better use --sslcertck!)\n"));
1023         }
1024
1025         return(0);
1026 }
1027 #endif
1028
1029 int SockClose(int sock)
1030 /* close a socket gracefully */
1031 {
1032 #ifdef  SSL_ENABLE
1033     if( NULL != SSLGetContext( sock ) ) {
1034         /* Clean up the SSL stack */
1035         SSL_shutdown( _ssl_context[sock] );
1036         SSL_free( _ssl_context[sock] );
1037         _ssl_context[sock] = NULL;
1038         SSL_CTX_free(_ctx[sock]);
1039         _ctx[sock] = NULL;
1040     }
1041 #endif
1042
1043     /* if there's an error closing at this point, not much we can do */
1044     return(fm_close(sock));     /* this is guarded */
1045 }
1046
1047 #ifdef __CYGWIN__
1048 /*
1049  * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1050  * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1051  * for more details.
1052  */
1053 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1054 {
1055     char *bp = (char *)buf;
1056     size_t n = 0;
1057
1058     if ((n = read(sock, bp, count)) == (size_t)-1)
1059         return(-1);
1060
1061     if (n != count) {
1062         size_t n2 = 0;
1063         if (outlevel >= O_VERBOSE)
1064             report(stdout, GT_("Cygwin socket read retry\n"));
1065         n2 = read(sock, bp + n, count - n);
1066         if (n2 == (size_t)-1 || n + n2 != count) {
1067             report(stderr, GT_("Cygwin socket read retry failed!\n"));
1068             return(-1);
1069         }
1070     }
1071
1072     return count;
1073 }
1074 #endif /* __CYGWIN__ */