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