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