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