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