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