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