]> Pileus Git - ~andy/fetchmail/blob - socket.c
d96743c8e3ac2bc2ad59af092cba4093a5ba4730
[~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
642 SSL *SSLGetContext( int sock )
643 {
644         /* If SSLOpen has never initialized - just return NULL */
645         if( NULL == _ctx )
646                 return NULL;
647
648         if( sock < 0 || sock > FD_SETSIZE )
649                 return NULL;
650         return _ssl_context[sock];
651 }
652
653
654 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
655 {
656         char buf[260];
657         char cbuf[260];
658         char ibuf[260];
659         char *str_ptr;
660         X509 *x509_cert;
661         int err, depth;
662
663         x509_cert = X509_STORE_CTX_get_current_cert(ctx);
664         err = X509_STORE_CTX_get_error(ctx);
665         depth = X509_STORE_CTX_get_error_depth(ctx);
666
667         X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
668         X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
669
670         /* Just to be sure those buffers are terminated...  I think the
671                 X509 libraries do, but... */
672         buf[256] = ibuf[256] = '\0';
673
674         if (depth == 0) {
675                 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
676                         str_ptr += 3;
677                         strcpy( cbuf, str_ptr );
678                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
679                                 *str_ptr = '\0';
680                         }
681                         if (outlevel == O_VERBOSE)
682                                 report(stdout, _("Issuer Organization: %s\n"), cbuf );
683                 } else {
684                         if (outlevel == O_VERBOSE)
685                                 report(stdout, _("Unknown Organization\n"));
686                 }
687                 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
688                         str_ptr += 4;
689                         strcpy( cbuf, str_ptr );
690                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
691                                 *str_ptr = '\0';
692                         }
693                         if (outlevel == O_VERBOSE)
694                                 report(stdout, _("Issuer CommonName: %s\n"), cbuf );
695                 } else {
696                         if (outlevel == O_VERBOSE)
697                                 report(stdout, _("Unknown Issuer CommonName\n"));
698                 }
699                 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
700                         str_ptr += 4;
701                         strcpy( cbuf, str_ptr );
702                         if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
703                                 *str_ptr = '\0';
704                         }
705                         if (outlevel == O_VERBOSE)
706                                 report(stdout, _("Server CommonName: %s\n"), cbuf);
707
708                        if (_ssl_server_cname != NULL) 
709                        {
710                                char *p1 = cbuf;
711                                char *p2 = _ssl_server_cname;
712                                int n;
713
714                                if (*p1 == '*') 
715                                {
716                                        ++p1;
717                                        n = strlen(p2) - strlen(p1);
718                                        if (n >= 0)
719                                                p2 += n;
720                                }
721                                if ( 0 != strcasecmp( p1, p2 ) )
722                                        report(stdout,
723                                               "Server CommonName mismatch: %s != %s\n",
724                                               cbuf, _ssl_server_cname );
725                        }
726                 } else {
727                         if (outlevel == O_VERBOSE)
728                                 report(stdout, _("Unknown Server CommonName\n"));
729                 }
730         }
731
732         switch (ctx->error) {
733         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
734                 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
735                 report(stdout, _("unknown issuer= %s"), buf);
736                 break;
737         case X509_V_ERR_CERT_NOT_YET_VALID:
738         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
739                 report(stderr, _("Server Certificate not yet valid"));
740                 break;
741         case X509_V_ERR_CERT_HAS_EXPIRED:
742         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
743                 report(stderr, _("Server Certificate expired"));
744                 break;
745         }
746         /* We are not requiring or validating server or issuer id's as yet */
747         /* Always return OK from here */
748         ok_return = 1;
749         return( ok_return );
750 }
751
752
753 /* performs initial SSL handshake over the connected socket
754  * uses SSL *ssl global variable, which is currently defined
755  * in this file
756  */
757 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, char *servercname )
758 {
759         SSL_load_error_strings();
760         SSLeay_add_ssl_algorithms();
761         
762         if( sock < 0 || sock > FD_SETSIZE ) {
763                 report(stderr, _("File descriptor out of range for SSL") );
764                 return( -1 );
765         }
766
767         if( ! _ctx ) {
768                 /* Be picky and make sure the memory is cleared */
769                 memset( _ssl_context, 0, sizeof( _ssl_context ) );
770                 if(myproto) {
771                         if(!strcmp("ssl2",myproto)) {
772                                 _ctx = SSL_CTX_new(SSLv2_client_method());
773                         } else if(!strcmp("ssl3",myproto)) {
774                                 _ctx = SSL_CTX_new(SSLv3_client_method());
775                         } else if(!strcmp("tls1",myproto)) {
776                                 _ctx = SSL_CTX_new(TLSv1_client_method());
777                         } else {
778                                 fprintf(stderr,_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
779                                 myproto = NULL;
780                         }
781                 }
782                 if(!myproto) {
783                         _ctx = SSL_CTX_new(SSLv23_client_method());
784                 }
785                 if(_ctx == NULL) {
786                         ERR_print_errors_fp(stderr);
787                         return(-1);
788                 }
789         }
790         
791         _ssl_context[sock] = SSL_new(_ctx);
792         
793         if(_ssl_context[sock] == NULL) {
794                 ERR_print_errors_fp(stderr);
795                 return(-1);
796         }
797         
798         /* This static is for the verify callback */
799         _ssl_server_cname = servercname;
800
801         SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
802
803         if( mycert || mykey ) {
804
805         /* Ok...  He has a certificate file defined, so lets declare it.  If
806          * he does NOT have a separate certificate and private key file then
807          * assume that it's a combined key and certificate file.
808          */
809                 if( !mykey )
810                         mykey = mycert;
811                 if( !mycert )
812                         mycert = mykey;
813                 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
814                 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
815         }
816
817         SSL_set_fd(_ssl_context[sock], sock);
818         
819         if(SSL_connect(_ssl_context[sock]) == -1) {
820                 ERR_print_errors_fp(stderr);
821                 return(-1);
822         }
823         
824         return(0);
825 }
826 #endif
827
828 int SockClose(int sock)
829 /* close a socket gracefully */
830 {
831 #ifdef  SSL_ENABLE
832     SSL *ssl;
833
834     if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
835         /* Clean up the SSL stack */
836         SSL_free( _ssl_context[sock] );
837         _ssl_context[sock] = NULL;
838     }
839 #endif
840
841 #ifdef __UNUSED__
842     /* 
843      * This hangs in RedHat 6.2 after fetchmail runs for a while a
844      * FIN_WAIT2 comes up in netstat and fetchmail never returns from
845      * the recv system call. (Reported from jtnews
846      * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
847      *
848      * Half-close the connection first so the other end gets notified.
849      *
850      * This stops sends but allows receives (effectively, it sends a
851      * TCP <FIN>).  */
852     if (shutdown(sock, 1) == 0) {
853         char ch;
854         /* If there is any data still waiting in the queue, discard it.
855          * Call recv() until either it returns 0 (meaning we received a FIN)
856          * or any error occurs.  This makes sure all data sent by the other
857          * side is acknowledged at the TCP level.
858          */
859         if (fm_peek(sock, &ch, 1) > 0)
860             while (fm_read(sock, &ch, 1) > 0)
861                 continue;
862     }
863 #endif /* __UNUSED__ */
864
865     /* if there's an error closing at this point, not much we can do */
866     return(fm_close(sock));     /* this is guarded */
867 }
868
869 #ifdef MAIN
870 /*
871  * Use the chargen service to test input buffering directly.
872  * You may have to uncomment the `chargen' service description in your
873  * inetd.conf (and then SIGHUP inetd) for this to work.  */
874 main()
875 {
876     int         sock = SockOpen("localhost", 19, NULL);
877     char        buf[80];
878
879     while (SockRead(sock, buf, sizeof(buf)-1))
880         SockWrite(1, buf, strlen(buf));
881     SockClose(sock);
882 }
883 #endif /* MAIN */
884
885 /* socket.c ends here */