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