]> Pileus Git - ~andy/fetchmail/blob - socket.c
Ready to ship.
[~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, _("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, _("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, _("fetchmail: socketpair failed\n"));
159         return -1;
160     }
161     switch (fork()) {
162         case -1:
163                 /* error */
164                 report(stderr, _("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, _("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, _("running %s (host %s service %s)\n"), plugin, host, service);
179                 argvec = parse_plugin(plugin,host,service);
180                 execvp(*argvec, argvec);
181                 report(stderr, _("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, _("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       sprintf(buf,"%d",clientPort);
329       return handle_plugin(host,buf,plugin);
330     }
331 #endif /* HAVE_SOCKETPAIR */
332
333     memset(&ad, 0, sizeof(ad));
334     ad.sin_family = AF_INET;
335
336     /* we'll accept a quad address */
337 #ifndef HAVE_INET_ATON
338     inaddr = inet_addr(host);
339     if (inaddr != INADDR_NONE)
340     {
341         memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
342 #else
343     if (inet_aton(host, &ad.sin_addr))
344     {
345 #endif /* HAVE_INET_ATON */
346         ad.sin_port = htons(clientPort);
347
348         sock = socket(AF_INET, SOCK_STREAM, 0);
349         if (sock < 0)
350         {
351             h_errno = 0;
352             return -1;
353         }
354         if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
355         {
356             int olderr = errno;
357             fm_close(sock);     /* don't use SockClose, no traffic yet */
358             h_errno = 0;
359             errno = olderr;
360             return -1;
361         }
362 #ifndef HAVE_INET_ATON
363     }
364 #else
365     }
366 #endif /* HAVE_INET_ATON */
367     else {
368         hp = gethostbyname(host);
369
370         if (hp == NULL)
371         {
372             errno = 0;
373             return -1;
374         }
375         /*
376          * Add a check to make sure the address has a valid IPv4 or IPv6
377          * length.  This prevents buffer spamming by a broken DNS.
378          */
379         if(hp->h_length != 4 && hp->h_length != 8)
380         {
381             h_errno = errno = 0;
382             report(stderr, 
383                    _("fetchmail: illegal address length received for host %s\n"),host);
384             return -1;
385         }
386         /*
387          * Try all addresses of a possibly multihomed host until we get
388          * a successful connect or until we run out of addresses.
389          */
390         pptr = (struct sockaddr_in **)hp->h_addr_list;
391         for(; *pptr != NULL; pptr++)
392         {
393             sock = socket(AF_INET, SOCK_STREAM, 0);
394             if (sock < 0)
395             {
396                 h_errno = 0;
397                 return -1;
398             }
399             ad.sin_port = htons(clientPort);
400             memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
401             if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
402                 break; /* success */
403             fm_close(sock);     /* don't use SockClose, no traffic yet */
404             memset(&ad, 0, sizeof(ad));
405             ad.sin_family = AF_INET;
406         }
407         if(*pptr == NULL)
408         {
409             int olderr = errno;
410             fm_close(sock);     /* don't use SockClose, no traffic yet */
411             h_errno = 0;
412             errno = olderr;
413             return -1;
414         }
415     }
416
417     return(sock);
418 }
419 #endif /* INET6_ENABLE */
420
421
422 #if defined(HAVE_STDARG_H)
423 int SockPrintf(int sock, const char* format, ...)
424 {
425 #else
426 int SockPrintf(sock,format,va_alist)
427 int sock;
428 char *format;
429 va_dcl {
430 #endif
431
432     va_list ap;
433     char buf[8192];
434
435 #if defined(HAVE_STDARG_H)
436     va_start(ap, format) ;
437 #else
438     va_start(ap);
439 #endif
440 #ifdef HAVE_VSNPRINTF
441     vsnprintf(buf, sizeof(buf), format, ap);
442 #else
443     vsprintf(buf, format, ap);
444 #endif
445     va_end(ap);
446     return SockWrite(sock, buf, strlen(buf));
447
448 }
449
450 #ifdef SSL_ENABLE
451 #include "openssl/ssl.h"
452 #include "openssl/err.h"
453 #include "openssl/pem.h"
454 #include "openssl/x509.h"
455
456 static  SSL_CTX *_ctx = NULL;
457 static  SSL *_ssl_context[FD_SETSIZE];
458
459 SSL     *SSLGetContext( int );
460 #endif /* SSL_ENABLE */
461
462 int SockWrite(int sock, char *buf, int len)
463 {
464     int n, wrlen = 0;
465 #ifdef  SSL_ENABLE
466     SSL *ssl;
467 #endif
468
469     while (len)
470     {
471 #ifdef SSL_ENABLE
472         if( NULL != ( ssl = SSLGetContext( sock ) ) )
473                 n = SSL_write(ssl, buf, len);
474         else
475         n = fm_write(sock, buf, len);
476 #else
477         n = fm_write(sock, buf, len);
478 #endif
479         if (n <= 0)
480             return -1;
481         len -= n;
482         wrlen += n;
483         buf += n;
484     }
485     return wrlen;
486 }
487
488 int SockRead(int sock, char *buf, int len)
489 {
490     char *newline, *bp = buf;
491     int n;
492 #ifdef  SSL_ENABLE
493     SSL *ssl;
494 #endif
495
496     if (--len < 1)
497         return(-1);
498 #ifdef __BEOS__
499     if (peeked != 0){
500         (*bp) = peeked;
501         bp++;
502         len--;
503         peeked = 0;
504     }
505 #endif        
506     do {
507         /* 
508          * The reason for these gymnastics is that we want two things:
509          * (1) to read \n-terminated lines,
510          * (2) to return the true length of data read, even if the
511          *     data coming in has embedded NULS.
512          */
513 #ifdef  SSL_ENABLE
514         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
515                 /* Hack alert! */
516                 /* OK...  SSL_peek works a little different from MSG_PEEK
517                         Problem is that SSL_peek can return 0 if there
518                         is no data currently available.  If, on the other
519                         hand, we loose the socket, we also get a zero, but
520                         the SSL_read then SEGFAULTS!  To deal with this,
521                         we'll check the error code any time we get a return
522                         of zero from SSL_peek.  If we have an error, we bail.
523                         If we don't, we read one character in SSL_read and
524                         loop.  This should continue to work even if they
525                         later change the behavior of SSL_peek
526                         to "fix" this problem...  :-(   */
527                 if ((n = SSL_peek(ssl, bp, len)) < 0) {
528                         return(-1);
529                 }
530                 if( 0 == n ) {
531                         /* SSL_peek says no data...  Does he mean no data
532                         or did the connection blow up?  If we got an error
533                         then bail! */
534                         if( 0 != ( n = ERR_get_error() ) ) {
535                                 return -1;
536                         }
537                         /* We didn't get an error so read at least one
538                                 character at this point and loop */
539                         n = 1;
540                         /* Make sure newline start out NULL!
541                          * We don't have a string to pass through
542                          * the strchr at this point yet */
543                         newline = NULL;
544                 } else if ((newline = memchr(bp, '\n', n)) != NULL)
545                         n = newline - bp + 1;
546                 if ((n = SSL_read(ssl, bp, n)) == -1) {
547                         return(-1);
548                 }
549                 /* Check for case where our single character turned out to
550                  * be a newline...  (It wasn't going to get caught by
551                  * the strchr above if it came from the hack...  ). */
552                 if( NULL == newline && 1 == n && '\n' == *bp ) {
553                         /* Got our newline - this will break
554                                 out of the loop now */
555                         newline = bp;
556                 }
557         } else {
558                 if ((n = fm_peek(sock, bp, len)) <= 0)
559                         return(-1);
560                 if ((newline = memchr(bp, '\n', n)) != NULL)
561                         n = newline - bp + 1;
562                 if ((n = fm_read(sock, bp, n)) == -1)
563                         return(-1);
564         }
565 #else
566
567 #ifdef __BEOS__
568     if ((n = fm_read(sock, bp, 1)) <= 0)
569 #else
570     if ((n = fm_peek(sock, bp, len)) <= 0)
571 #endif
572         return (-1);
573         if ((newline = memchr(bp, '\n', n)) != NULL)
574             n = newline - bp + 1;
575 #ifndef __BEOS__
576         if ((n = fm_read(sock, bp, n)) == -1)
577             return(-1);
578 #endif /* __BEOS__ */
579 #endif
580         bp += n;
581         len -= n;
582     } while 
583             (!newline && len);
584     *bp = '\0';
585     return bp - buf;
586 }
587
588 int SockPeek(int sock)
589 /* peek at the next socket character without actually reading it */
590 {
591     int n;
592     char ch;
593 #ifdef  SSL_ENABLE
594     SSL *ssl;
595 #endif
596
597 #ifdef  SSL_ENABLE
598         if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
599                 n = SSL_peek(ssl, &ch, 1);
600                 if( 0 == n ) {
601                         /* This code really needs to implement a "hold back"
602                          * to simulate a functioning SSL_peek()...  sigh...
603                          * Has to be coordinated with the read code above.
604                          * Next on the list todo...     */
605
606                         /* SSL_peek says no data...  Does he mean no data
607                         or did the connection blow up?  If we got an error
608                         then bail! */
609                         if( 0 != ( n = ERR_get_error() ) ) {
610                                 return -1;
611                         }
612
613                         /* Haven't seen this case actually occur, but...
614                            if the problem in SockRead can occur, this should
615                            be possible...  Just not sure what to do here.
616                            This should be a safe "punt" the "peek" but don't
617                            "punt" the "session"... */
618
619                         return 0;       /* Give him a '\0' character */
620                 }
621         } else {
622                 n = fm_peek(sock, &ch, 1);
623         }
624 #else
625
626         n = fm_peek(sock, &ch, 1);
627
628 #endif /* SSL_ENABLE */
629         if (n == -1)
630                 return -1;
631
632 #ifdef __BEOS__
633     peeked = ch;
634 #endif
635     return(ch);
636 }
637
638 #ifdef SSL_ENABLE
639
640 static  char *_ssl_server_cname = NULL;
641 static  int _check_fp;
642 static  char *_check_digest;
643 static  char *_server_label;
644 static  int _depth0ck;
645
646 SSL *SSLGetContext( int sock )
647 {
648         /* If SSLOpen has never initialized - just return NULL */
649         if( NULL == _ctx )
650                 return NULL;
651
652         if( sock < 0 || sock > FD_SETSIZE )
653                 return NULL;
654         return _ssl_context[sock];
655 }
656
657
658 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
659 {
660         char buf[257];
661         X509 *x509_cert;
662         int err, depth;
663         unsigned char digest[EVP_MAX_MD_SIZE];
664         char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
665         EVP_MD *digest_tp;
666         unsigned int dsz, i, esz;
667         X509_NAME *subj, *issuer;
668
669         x509_cert = X509_STORE_CTX_get_current_cert(ctx);
670         err = X509_STORE_CTX_get_error(ctx);
671         depth = X509_STORE_CTX_get_error_depth(ctx);
672
673         subj = X509_get_subject_name(x509_cert);
674         issuer = X509_get_issuer_name(x509_cert);
675
676         if (depth == 0) {
677                 _depth0ck = 1;
678                 
679                 if (outlevel == O_VERBOSE) {
680                         if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
681                                 report(stdout, _("Issuer Organization: %s\n"), buf);
682                                 if (i >= sizeof(buf) - 1)
683                                         report(stdout, _("Warning: Issuer Organization Name too long (possibly truncated).\n"));
684                         } else
685                                 report(stdout, _("Unknown Organization\n"));
686                         if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
687                                 report(stdout, _("Issuer CommonName: %s\n"), buf);
688                                 if (i >= sizeof(buf) - 1)
689                                         report(stdout, _("Warning: Issuer CommonName too long (possibly truncated).\n"));
690                         } else
691                                 report(stdout, _("Unknown Issuer CommonName\n"));
692                 }
693                 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
694                         if (outlevel == O_VERBOSE)
695                                 report(stdout, _("Server CommonName: %s\n"), buf);
696                         if (i >= sizeof(buf) - 1) {
697                                 /* Possible truncation. In this case, this is a DNS name, so this
698                                  * is really bad. We do not tolerate this even in the non-strict case. */
699                                 report(stderr, _("Bad certificate: Subject CommonName too long!\n"));
700                                 return (0);
701                         }
702                         if (_ssl_server_cname != NULL) {
703                                 char *p1 = buf;
704                                 char *p2 = _ssl_server_cname;
705                                 int n;
706                                 
707                                 if (*p1 == '*') {
708                                         ++p1;
709                                         n = strlen(p2) - strlen(p1);
710                                         if (n >= 0)
711                                                 p2 += n;
712                                 }       
713                                 if (0 != strcasecmp(p1, p2)) {
714                                         report(stderr,
715                                             _("Server CommonName mismatch: %s != %s\n"),
716                                             buf, _ssl_server_cname );
717                                         if (ok_return && strict)
718                                                 return (0);
719                                 }
720                         } else if (ok_return && strict) {
721                                 report(stderr, _("Server name not set, could not verify certificate!\n"));
722                                 return (0);
723                         }
724                 } else {
725                         if (outlevel == O_VERBOSE)
726                                 report(stdout, _("Unknown Server CommonName\n"));
727                         if (ok_return && strict) {
728                                 report(stderr, _("Server name not specified in certificate!\n"));
729                                 return (0);
730                         }
731                 }
732                 /* Print the finger print. Note that on errors, we might print it more than once
733                  * normally; we kluge around that by using a global variable. */
734                 if (_check_fp) {
735                         _check_fp = 0;
736                         digest_tp = EVP_md5();
737                         if (digest_tp == NULL) {
738                                 report(stderr, _("EVP_md5() failed!\n"));
739                                 return (0);
740                         }
741                         if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
742                                 report(stderr, _("Out of memory!\n"));
743                                 return (0);
744                         }
745                         tp = text;
746                         te = text + sizeof(text);
747                         for (i = 0; i < dsz; i++) {
748                                 esz = snprintf(tp, te - tp, i > 0 ? ":%02X" : "%02X", digest[i]);
749                                 if (esz >= te - tp) {
750                                         report(stderr, _("Digest text buffer too small!\n"));
751                                         return (0);
752                                 }
753                                 tp += esz;
754                         }
755                         report(stdout, _("%s key fingerprint: %s\n"), _server_label, text);
756                         if (_check_digest != NULL) {
757                                 if (strcmp(text, _check_digest) == 0)
758                                         report(stdout, _("%s fingerprints match.\n"), _server_label);
759                                 else {
760                                         report(stderr, _("%s fingerprints do not match!\n"), _server_label);
761                                         return (0);
762                                 }
763                         }
764                 }
765         }
766
767         if (err != X509_V_OK && (strict || outlevel == O_VERBOSE)) {
768                 report(strict ? stderr : stdout, _("Warning: server certificate verification: %s\n"), X509_verify_cert_error_string(err));
769                 /* We gave the error code, but maybe we can add some more details for debugging */
770                 switch (err) {
771                 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
772                         X509_NAME_oneline(issuer, buf, sizeof(buf));
773                         buf[sizeof(buf) - 1] = '\0';
774                         report(stdout, _("unknown issuer (first %d characters): %s\n"), sizeof(buf), buf);
775                         break;
776                 }
777         }
778         if (!strict)
779                 ok_return = 1;
780         return (ok_return);
781 }
782
783 int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
784 {
785         return SSL_verify_callback(ok_return, ctx, 0);
786 }
787
788 int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
789 {
790         return SSL_verify_callback(ok_return, ctx, 1);
791 }
792
793 /* performs initial SSL handshake over the connected socket
794  * uses SSL *ssl global variable, which is currently defined
795  * in this file
796  */
797 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, int certck, char *certpath,
798     char *fingerprint, char *servercname, char *label)
799 {
800         SSL *ssl;
801         
802         SSL_load_error_strings();
803         SSLeay_add_ssl_algorithms();
804         
805         if( sock < 0 || sock > FD_SETSIZE ) {
806                 report(stderr, _("File descriptor out of range for SSL") );
807                 return( -1 );
808         }
809
810         if( ! _ctx ) {
811                 /* Be picky and make sure the memory is cleared */
812                 memset( _ssl_context, 0, sizeof( _ssl_context ) );
813                 if(myproto) {
814                         if(!strcmp("ssl2",myproto)) {
815                                 _ctx = SSL_CTX_new(SSLv2_client_method());
816                         } else if(!strcmp("ssl3",myproto)) {
817                                 _ctx = SSL_CTX_new(SSLv3_client_method());
818                         } else if(!strcmp("tls1",myproto)) {
819                                 _ctx = SSL_CTX_new(TLSv1_client_method());
820                         } else {
821                                 fprintf(stderr,_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
822                                 myproto = NULL;
823                         }
824                 }
825                 if(!myproto) {
826                         _ctx = SSL_CTX_new(SSLv23_client_method());
827                 }
828                 if(_ctx == NULL) {
829                         ERR_print_errors_fp(stderr);
830                         return(-1);
831                 }
832         }
833
834         if (certck) {
835                 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_ck_verify_callback);
836                 if (certpath)
837                         SSL_CTX_load_verify_locations(_ctx, NULL, certpath);
838         } else {
839                 /* In this case, we do not fail if verification fails. However,
840                  *  we provide the callback for output and possible fingerprint checks. */
841                 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_nock_verify_callback);
842         }
843         
844         _ssl_context[sock] = SSL_new(_ctx);
845         
846         if(_ssl_context[sock] == NULL) {
847                 ERR_print_errors_fp(stderr);
848                 return(-1);
849         }
850         
851         /* This static is for the verify callback */
852         _ssl_server_cname = servercname;
853         _server_label = label;
854         _check_fp = 1;
855         _check_digest = fingerprint;
856         _depth0ck = 0;
857
858         if( mycert || mykey ) {
859
860         /* Ok...  He has a certificate file defined, so lets declare it.  If
861          * he does NOT have a separate certificate and private key file then
862          * assume that it's a combined key and certificate file.
863          */
864                 if( !mykey )
865                         mykey = mycert;
866                 if( !mycert )
867                         mycert = mykey;
868                 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
869                 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
870         }
871
872         SSL_set_fd(_ssl_context[sock], sock);
873         
874         if(SSL_connect(_ssl_context[sock]) == -1) {
875                 ERR_print_errors_fp(stderr);
876                 return(-1);
877         }
878
879         /* Paranoia: was the callback not called as we expected? */
880         if ((fingerprint != NULL || certck) && !_depth0ck) {
881                 report(stderr, _("Certificate/fingerprint verification was somehow skipped!\n"));
882                 
883                 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
884                         /* Clean up the SSL stack */
885                         SSL_free( _ssl_context[sock] );
886                         _ssl_context[sock] = NULL;
887                 }
888                 return(-1);
889         }
890
891         return(0);
892 }
893 #endif
894
895 int SockClose(int sock)
896 /* close a socket gracefully */
897 {
898 #ifdef  SSL_ENABLE
899     SSL *ssl;
900
901     if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
902         /* Clean up the SSL stack */
903         SSL_free( _ssl_context[sock] );
904         _ssl_context[sock] = NULL;
905     }
906 #endif
907
908 #ifdef __UNUSED__
909     /* 
910      * This hangs in RedHat 6.2 after fetchmail runs for a while a
911      * FIN_WAIT2 comes up in netstat and fetchmail never returns from
912      * the recv system call. (Reported from jtnews
913      * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
914      *
915      * Half-close the connection first so the other end gets notified.
916      *
917      * This stops sends but allows receives (effectively, it sends a
918      * TCP <FIN>).  */
919     if (shutdown(sock, 1) == 0) {
920         char ch;
921         /* If there is any data still waiting in the queue, discard it.
922          * Call recv() until either it returns 0 (meaning we received a FIN)
923          * or any error occurs.  This makes sure all data sent by the other
924          * side is acknowledged at the TCP level.
925          */
926         if (fm_peek(sock, &ch, 1) > 0)
927             while (fm_read(sock, &ch, 1) > 0)
928                 continue;
929     }
930 #endif /* __UNUSED__ */
931
932     /* if there's an error closing at this point, not much we can do */
933     return(fm_close(sock));     /* this is guarded */
934 }
935
936 #ifdef MAIN
937 /*
938  * Use the chargen service to test input buffering directly.
939  * You may have to uncomment the `chargen' service description in your
940  * inetd.conf (and then SIGHUP inetd) for this to work.  */
941 main()
942 {
943     int         sock = SockOpen("localhost", 19, NULL);
944     char        buf[80];
945
946     while (SockRead(sock, buf, sizeof(buf)-1))
947         SockWrite(1, buf, strlen(buf));
948     SockClose(sock);
949 }
950 #endif /* MAIN */
951
952 /* socket.c ends here */