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