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