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