2 * socket.c -- socket library functions
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
12 #include <ctype.h> /* isspace() */
15 #endif /* HAVE_MEMORY_H */
16 #include <sys/types.h>
17 #ifndef HAVE_NET_SOCKET_H
18 #include <sys/socket.h>
20 #include <net/socket.h>
23 #include <netinet/in.h>
24 #ifdef HAVE_ARPA_INET_H
25 #include <arpa/inet.h>
28 #if defined(STDC_HEADERS)
31 #if defined(HAVE_UNISTD_H)
34 #if defined(HAVE_STDARG_H)
40 #include "fetchmail.h"
43 /* Defines to allow BeOS and Cygwin to play nice... */
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)
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)
55 #define fm_read(a,b,c) cygwin_read(a,b,c)
56 static ssize_t cygwin_read(int sock, void *buf, size_t count);
57 #else /* ! __CYGWIN__ */
58 #define fm_read(a,b,c) read(a,b,c)
59 #endif /* __CYGWIN__ */
62 /* We need to define h_errno only if it is not already */
65 #ifdef HAVE_RES_SEARCH
66 /* some versions of FreeBSD should declare this but don't */
69 /* pretend we have h_errno to avoid some #ifdef's later */
73 #endif /* ndef h_errno */
75 extern int mailserver_socket_temp; /* Socket to close if connect timeout */
78 #include <net/security.h>
79 #endif /* NET_SECURITY */
81 #ifdef HAVE_SOCKETPAIR
82 char *const *parse_plugin(const char *plugin, const char *host, const char *service)
83 { const char **argvec;
85 char *cp, *plugin_copy;
86 unsigned int plugin_copy_len;
87 unsigned int plugin_offset = 0, plugin_copy_offset = 0;
88 unsigned int i, s = 2 * sizeof(char*), host_count = 0, service_count = 0;
89 unsigned int plugin_len = strlen(plugin);
90 unsigned int host_len = strlen(host);
91 unsigned int service_len = strlen(service);
93 for (c = p = plugin; *c; c++)
94 { if (isspace(*c) && !isspace(*p))
96 if (*p == '%' && *c == 'h')
98 if (*p == '%' && *c == 'p')
103 plugin_copy_len = plugin_len + host_len * host_count + service_len * service_count;
104 plugin_copy = malloc(plugin_copy_len + 1);
107 report(stderr, GT_("fetchmail: malloc failed\n"));
111 while (plugin_copy_offset < plugin_copy_len)
112 { if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'h'))
113 { strcpy(plugin_copy + plugin_copy_offset, host);
115 plugin_copy_offset += host_len;
117 else if ((plugin[plugin_offset] == '%') && (plugin[plugin_offset + 1] == 'p'))
118 { strcpy(plugin_copy + plugin_copy_offset, service);
120 plugin_copy_offset += service_len;
123 { plugin_copy[plugin_copy_offset] = plugin[plugin_offset];
125 plugin_copy_offset++;
128 plugin_copy[plugin_copy_len] = 0;
133 report(stderr, GT_("fetchmail: malloc failed\n"));
136 memset(argvec, 0, s);
137 for (c = p = plugin_copy, i = 0; *c; c++)
138 { if ((!isspace(*c)) && (c == p ? 1 : isspace(*p))) {
144 for (cp = plugin_copy; *cp; cp++)
148 return (char *const*)argvec;
151 static int handle_plugin(const char *host,
152 const char *service, const char *plugin)
153 /* get a socket mediated through a given external command */
159 * The author of this code, Felix von Leitner <felix@convergence.de>, says:
160 * he chose socketpair() instead of pipe() because socketpair creates
161 * bidirectional sockets while allegedly some pipe() implementations don't.
163 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
165 report(stderr, GT_("fetchmail: socketpair failed\n"));
171 report(stderr, GT_("fetchmail: fork failed\n"));
175 /* fds[1] is the parent's end; close it for proper EOF
177 (void) close(fds[1]);
178 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
179 report(stderr, GT_("dup2 failed\n"));
182 /* fds[0] is now connected to 0 and 1; close it */
183 (void) close(fds[0]);
184 if (outlevel >= O_VERBOSE)
185 report(stderr, GT_("running %s (host %s service %s)\n"), plugin, host, service);
186 argvec = parse_plugin(plugin,host,service);
187 execvp(*argvec, argvec);
188 report(stderr, GT_("execvp(%s) failed\n"), *argvec);
191 default: /* parent */
195 /* fds[0] is the child's end; close it for proper EOF detection */
196 (void) close(fds[0]);
199 #endif /* HAVE_SOCKETPAIR */
202 #include <sys/time.h>
204 int SockCheckOpen(int fd)
205 /* poll given socket; is it selectable? */
213 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
216 tv.tv_sec = 0; tv.tv_usec = 0;
217 rt = select(fd+1, &r, &w, &e, &tv);
218 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
224 #endif /* __UNUSED__ */
226 int UnixOpen(const char *path)
229 struct sockaddr_un ad;
230 memset(&ad, 0, sizeof(ad));
231 ad.sun_family = AF_UNIX;
232 strncpy(ad.sun_path, path, sizeof(ad.sun_path)-1);
234 sock = socket( AF_UNIX, SOCK_STREAM, 0 );
241 /* Socket opened saved. Usefull if connect timeout
242 * because it can be closed.
244 mailserver_socket_temp = sock;
246 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
249 fm_close(sock); /* don't use SockClose, no traffic yet */
255 /* No connect timeout, then no need to set mailserver_socket_temp */
256 mailserver_socket_temp = -1;
262 int SockOpen(const char *host, const char *service, const char *options,
265 struct addrinfo *ai, *ai0, req;
268 void *request = NULL;
270 #endif /* NET_SECURITY */
272 #ifdef HAVE_SOCKETPAIR
274 return handle_plugin(host,service,plugin);
275 #endif /* HAVE_SOCKETPAIR */
276 memset(&req, 0, sizeof(struct addrinfo));
277 req.ai_socktype = SOCK_STREAM;
279 if (getaddrinfo(host, service, &req, &ai0)) {
280 report(stderr, GT_("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
288 if (net_security_strtorequest((char *)options, &request, &requestlen))
291 i = inner_connect(ai0, request, requestlen, NULL, NULL, "fetchmail", NULL);
296 #else /* NET_SECURITY */
297 #ifdef HAVE_INNER_CONNECT
298 i = inner_connect(ai0, NULL, 0, NULL, NULL, "fetchmail", NULL);
304 for (ai = ai0; ai; ai = ai->ai_next) {
305 i = socket(ai->ai_family, ai->ai_socktype, 0);
309 /* Socket opened saved. Usefull if connect timeout
310 * because it can be closed.
312 mailserver_socket_temp = i;
314 if (connect(i, (struct sockaddr *) ai->ai_addr, ai->ai_addrlen) < 0) {
320 /* No connect timeout, then no need to set mailserver_socket_temp */
321 mailserver_socket_temp = -1;
327 #endif /* NET_SECURITY */
333 #else /* INET6_ENABLE */
334 #ifndef HAVE_INET_ATON
336 #ifdef INADDR_BROADCAST
337 #define INADDR_NONE INADDR_BROADCAST
339 #define INADDR_NONE -1
342 #endif /* HAVE_INET_ATON */
344 int SockOpen(const char *host, int clientPort, const char *options,
347 int sock = -1; /* pacify -Wall */
348 #ifndef HAVE_INET_ATON
349 unsigned long inaddr;
350 #endif /* HAVE_INET_ATON */
351 struct sockaddr_in ad, **pptr;
354 #ifdef HAVE_SOCKETPAIR
358 snprintf(buf, sizeof(buf), /* Yeah, paranoic. So what? :P */
361 #endif /* HAVE_SNPRINTF */
363 return handle_plugin(host,buf,plugin);
365 #endif /* HAVE_SOCKETPAIR */
367 memset(&ad, 0, sizeof(ad));
368 ad.sin_family = AF_INET;
370 /* we'll accept a quad address */
371 #ifndef HAVE_INET_ATON
372 inaddr = inet_addr((char*)host);
373 if (inaddr != INADDR_NONE)
375 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
377 if (inet_aton(host, &ad.sin_addr))
379 #endif /* HAVE_INET_ATON */
380 ad.sin_port = htons(clientPort);
382 sock = socket(AF_INET, SOCK_STREAM, 0);
389 /* Socket opened saved. Usefull if connect timeout because
392 mailserver_socket_temp = sock;
394 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
397 fm_close(sock); /* don't use SockClose, no traffic yet */
403 /* No connect timeout, then no need to set mailserver_socket_temp */
404 mailserver_socket_temp = -1;
406 #ifndef HAVE_INET_ATON
410 #endif /* HAVE_INET_ATON */
412 hp = gethostbyname((char*)host);
420 * Add a check to make sure the address has a valid IPv4 or IPv6
421 * length. This prevents buffer spamming by a broken DNS.
423 if(hp->h_length != 4 && hp->h_length != 8)
427 GT_("fetchmail: illegal address length received for host %s\n"),host);
431 * Try all addresses of a possibly multihomed host until we get
432 * a successful connect or until we run out of addresses.
434 pptr = (struct sockaddr_in **)hp->h_addr_list;
435 for(; *pptr != NULL; pptr++)
437 sock = socket(AF_INET, SOCK_STREAM, 0);
444 /* Socket opened saved. Usefull if connect timeout because
447 mailserver_socket_temp = sock;
449 ad.sin_port = htons(clientPort);
450 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
451 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0) {
452 /* No connect timeout, then no need to set mailserver_socket_temp */
453 mailserver_socket_temp = -1;
456 fm_close(sock); /* don't use SockClose, no traffic yet */
457 memset(&ad, 0, sizeof(ad));
458 ad.sin_family = AF_INET;
463 fm_close(sock); /* don't use SockClose, no traffic yet */
472 #endif /* INET6_ENABLE */
475 #if defined(HAVE_STDARG_H)
476 int SockPrintf(int sock, const char* format, ...)
479 int SockPrintf(sock,format,va_alist)
488 #if defined(HAVE_STDARG_H)
489 va_start(ap, format) ;
493 #ifdef HAVE_VSNPRINTF
494 vsnprintf(buf, sizeof(buf), format, ap);
496 vsprintf(buf, format, ap);
499 return SockWrite(sock, buf, strlen(buf));
504 #include "openssl/ssl.h"
505 #include "openssl/err.h"
506 #include "openssl/pem.h"
507 #include "openssl/x509.h"
509 static SSL_CTX *_ctx = NULL;
510 static SSL *_ssl_context[FD_SETSIZE];
512 SSL *SSLGetContext( int );
513 #endif /* SSL_ENABLE */
515 int SockWrite(int sock, char *buf, int len)
525 if( NULL != ( ssl = SSLGetContext( sock ) ) )
526 n = SSL_write(ssl, buf, len);
528 #endif /* SSL_ENABLE */
529 n = fm_write(sock, buf, len);
539 int SockRead(int sock, char *buf, int len)
541 char *newline, *bp = buf;
543 int maxavailable = 0;
560 * The reason for these gymnastics is that we want two things:
561 * (1) to read \n-terminated lines,
562 * (2) to return the true length of data read, even if the
563 * data coming in has embedded NULS.
566 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
568 /* OK... SSL_peek works a little different from MSG_PEEK
569 Problem is that SSL_peek can return 0 if there
570 is no data currently available. If, on the other
571 hand, we loose the socket, we also get a zero, but
572 the SSL_read then SEGFAULTS! To deal with this,
573 we'll check the error code any time we get a return
574 of zero from SSL_peek. If we have an error, we bail.
575 If we don't, we read one character in SSL_read and
576 loop. This should continue to work even if they
577 later change the behavior of SSL_peek
578 to "fix" this problem... :-( */
579 if ((n = SSL_peek(ssl, bp, len)) < 0) {
580 (void)SSL_get_error(ssl, n);
585 /* SSL_peek says no data... Does he mean no data
586 or did the connection blow up? If we got an error
588 if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
591 /* We didn't get an error so read at least one
592 character at this point and loop */
594 /* Make sure newline start out NULL!
595 * We don't have a string to pass through
596 * the strchr at this point yet */
598 } else if ((newline = memchr(bp, '\n', n)) != NULL)
599 n = newline - bp + 1;
600 /* Matthias Andree: SSL_read can return 0, in that case
601 * we must cal SSL_get_error to figure if there was
602 * an error or just a "no data" condition */
603 if ((n = SSL_read(ssl, bp, n)) <= 0) {
604 if ((n = SSL_get_error(ssl, n))) {
608 /* Check for case where our single character turned out to
609 * be a newline... (It wasn't going to get caught by
610 * the strchr above if it came from the hack... ). */
611 if( NULL == newline && 1 == n && '\n' == *bp ) {
612 /* Got our newline - this will break
613 out of the loop now */
618 #endif /* SSL_ENABLE */
622 if ((n = fm_read(sock, bp, 1)) <= 0)
624 if ((n = fm_peek(sock, bp, len)) <= 0)
628 if ((newline = memchr(bp, '\n', n)) != NULL)
629 n = newline - bp + 1;
631 if ((n = fm_read(sock, bp, n)) == -1)
633 #endif /* __BEOS__ */
640 /* OK, very weird hack coming up here:
641 * When POP and IMAP servers send us a message, they're supposed to
642 * terminate the message with a line containing only a dot. To protect
643 * against lines in the real message that might contain only a dot,
644 * they're supposed to preface any line that starts with a dot with
645 * an additional dot, which will be removed on the client side. That
646 * process, called byte-stuffing (and unstuffing) is really not the
647 * concern of this low-level routine, ordinarily, but there are some
648 * POP servers (and maybe IMAP servers too, who knows) that fail to
649 * do the byte-stuffing, and this routine is the best place to try to
650 * identify and fix that fault.
652 * Since the DOT line is supposed to come only at the end of a
653 * message, the implication is that right after we see it, the server
654 * is supposed to go back to waiting for the next command. There
655 * isn't supposed to be any more data to read after we see the dot.
656 * THEREFORE, if we see more data to be read after something that
657 * looks like the dot line, then probably the server is failing to
658 * do byte-stuffing. In that case, we'll byte-pack it for them so
659 * that the higher-level routines see things as hunky-dorey.
660 * This is not a perfect test or fix by any means (it has an
661 * obvious race condition, for one thing), but it should at least
662 * reduce the nastiness that ensues when people don't know how
663 * to write POP servers.
665 if ((maxavailable > (bp-buf)) &&
672 (buf[1] == '\n')))) {
674 memmove(buf+1, buf, (bp-buf)+1);
681 int SockPeek(int sock)
682 /* peek at the next socket character without actually reading it */
691 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
692 n = SSL_peek(ssl, &ch, 1);
694 (void)SSL_get_error(ssl, n);
698 /* This code really needs to implement a "hold back"
699 * to simulate a functioning SSL_peek()... sigh...
700 * Has to be coordinated with the read code above.
701 * Next on the list todo... */
703 /* SSL_peek says 0... Does that mean no data
704 or did the connection blow up? If we got an error
706 if( 0 != ( n = SSL_get_error(ssl, n) ) ) {
710 /* Haven't seen this case actually occur, but...
711 if the problem in SockRead can occur, this should
712 be possible... Just not sure what to do here.
713 This should be a safe "punt" the "peek" but don't
714 "punt" the "session"... */
716 return 0; /* Give him a '\0' character */
720 #endif /* SSL_ENABLE */
721 n = fm_peek(sock, &ch, 1);
733 static char *_ssl_server_cname = NULL;
734 static int _check_fp;
735 static char *_check_digest;
736 static char *_server_label;
737 static int _depth0ck;
739 SSL *SSLGetContext( int sock )
741 /* If SSLOpen has never initialized - just return NULL */
745 if( sock < 0 || sock > FD_SETSIZE )
747 return _ssl_context[sock];
751 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx, int strict )
756 unsigned char digest[EVP_MAX_MD_SIZE];
757 char text[EVP_MAX_MD_SIZE * 3 + 1], *tp, *te;
759 unsigned int dsz, i, esz;
760 X509_NAME *subj, *issuer;
762 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
763 err = X509_STORE_CTX_get_error(ctx);
764 depth = X509_STORE_CTX_get_error_depth(ctx);
766 subj = X509_get_subject_name(x509_cert);
767 issuer = X509_get_issuer_name(x509_cert);
772 if (outlevel == O_VERBOSE) {
773 if ((i = X509_NAME_get_text_by_NID(issuer, NID_organizationName, buf, sizeof(buf))) != -1) {
774 report(stdout, GT_("Issuer Organization: %s\n"), buf);
775 if (i >= sizeof(buf) - 1)
776 report(stdout, GT_("Warning: Issuer Organization Name too long (possibly truncated).\n"));
778 report(stdout, GT_("Unknown Organization\n"));
779 if ((i = X509_NAME_get_text_by_NID(issuer, NID_commonName, buf, sizeof(buf))) != -1) {
780 report(stdout, GT_("Issuer CommonName: %s\n"), buf);
781 if (i >= sizeof(buf) - 1)
782 report(stdout, GT_("Warning: Issuer CommonName too long (possibly truncated).\n"));
784 report(stdout, GT_("Unknown Issuer CommonName\n"));
786 if ((i = X509_NAME_get_text_by_NID(subj, NID_commonName, buf, sizeof(buf))) != -1) {
787 if (outlevel == O_VERBOSE)
788 report(stdout, GT_("Server CommonName: %s\n"), buf);
789 if (i >= sizeof(buf) - 1) {
790 /* Possible truncation. In this case, this is a DNS name, so this
791 * is really bad. We do not tolerate this even in the non-strict case. */
792 report(stderr, GT_("Bad certificate: Subject CommonName too long!\n"));
795 if (_ssl_server_cname != NULL) {
797 char *p2 = _ssl_server_cname;
802 n = strlen(p2) - strlen(p1);
806 if (0 != strcasecmp(p1, p2)) {
808 GT_("Server CommonName mismatch: %s != %s\n"),
809 buf, _ssl_server_cname );
810 if (ok_return && strict)
813 } else if (ok_return && strict) {
814 report(stderr, GT_("Server name not set, could not verify certificate!\n"));
818 if (outlevel == O_VERBOSE)
819 report(stdout, GT_("Unknown Server CommonName\n"));
820 if (ok_return && strict) {
821 report(stderr, GT_("Server name not specified in certificate!\n"));
825 /* Print the finger print. Note that on errors, we might print it more than once
826 * normally; we kluge around that by using a global variable. */
829 digest_tp = EVP_md5();
830 if (digest_tp == NULL) {
831 report(stderr, GT_("EVP_md5() failed!\n"));
834 if (!X509_digest(x509_cert, digest_tp, digest, &dsz)) {
835 report(stderr, GT_("Out of memory!\n"));
839 te = text + sizeof(text);
840 for (i = 0; i < dsz; i++) {
842 esz = snprintf(tp, te - tp, i > 0 ? ":%02X" : "%02X", digest[i]);
844 esz = sprintf(tp, i > 0 ? ":%02X" : "%02X", digest[i]);
846 if (esz >= te - tp) {
847 report(stderr, GT_("Digest text buffer too small!\n"));
852 if (outlevel > O_NORMAL)
853 report(stdout, GT_("%s key fingerprint: %s\n"), _server_label, text);
854 if (_check_digest != NULL) {
855 if (strcmp(text, _check_digest) == 0) {
856 if (outlevel > O_NORMAL)
857 report(stdout, GT_("%s fingerprints match.\n"), _server_label);
859 if (outlevel > O_SILENT)
860 report(stderr, GT_("%s fingerprints do not match!\n"), _server_label);
867 if (err != X509_V_OK && (strict || outlevel == O_VERBOSE)) {
868 report(strict ? stderr : stdout, GT_("Warning: server certificate verification: %s\n"), X509_verify_cert_error_string(err));
869 /* We gave the error code, but maybe we can add some more details for debugging */
871 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
872 X509_NAME_oneline(issuer, buf, sizeof(buf));
873 buf[sizeof(buf) - 1] = '\0';
874 report(stdout, GT_("unknown issuer (first %d characters): %s\n"), sizeof(buf), buf);
883 int SSL_nock_verify_callback( int ok_return, X509_STORE_CTX *ctx )
885 return SSL_verify_callback(ok_return, ctx, 0);
888 int SSL_ck_verify_callback( int ok_return, X509_STORE_CTX *ctx )
890 return SSL_verify_callback(ok_return, ctx, 1);
893 /* performs initial SSL handshake over the connected socket
894 * uses SSL *ssl global variable, which is currently defined
897 int SSLOpen(int sock, char *mycert, char *mykey, char *myproto, int certck, char *certpath,
898 char *fingerprint, char *servercname, char *label)
902 SSL_load_error_strings();
903 SSLeay_add_ssl_algorithms();
905 if( sock < 0 || sock > FD_SETSIZE ) {
906 report(stderr, GT_("File descriptor out of range for SSL") );
911 /* Be picky and make sure the memory is cleared */
912 memset( _ssl_context, 0, sizeof( _ssl_context ) );
914 if(!strcmp("ssl2",myproto)) {
915 _ctx = SSL_CTX_new(SSLv2_client_method());
916 } else if(!strcmp("ssl3",myproto)) {
917 _ctx = SSL_CTX_new(SSLv3_client_method());
918 } else if(!strcmp("tls1",myproto)) {
919 _ctx = SSL_CTX_new(TLSv1_client_method());
920 } else if (!strcmp("ssl23",myproto)) {
923 fprintf(stderr,GT_("Invalid SSL protocol '%s' specified, using default (SSLv23).\n"), myproto);
928 _ctx = SSL_CTX_new(SSLv23_client_method());
931 ERR_print_errors_fp(stderr);
937 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_ck_verify_callback);
939 SSL_CTX_load_verify_locations(_ctx, NULL, certpath);
941 /* In this case, we do not fail if verification fails. However,
942 * we provide the callback for output and possible fingerprint checks. */
943 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_nock_verify_callback);
946 _ssl_context[sock] = SSL_new(_ctx);
948 if(_ssl_context[sock] == NULL) {
949 ERR_print_errors_fp(stderr);
953 /* This static is for the verify callback */
954 _ssl_server_cname = servercname;
955 _server_label = label;
957 _check_digest = fingerprint;
960 if( mycert || mykey ) {
962 /* Ok... He has a certificate file defined, so lets declare it. If
963 * he does NOT have a separate certificate and private key file then
964 * assume that it's a combined key and certificate file.
970 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
971 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
974 SSL_set_fd(_ssl_context[sock], sock);
976 if(SSL_connect(_ssl_context[sock]) == -1) {
977 ERR_print_errors_fp(stderr);
981 /* Paranoia: was the callback not called as we expected? */
982 if ((fingerprint != NULL || certck) && !_depth0ck) {
983 report(stderr, GT_("Certificate/fingerprint verification was somehow skipped!\n"));
985 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
986 /* Clean up the SSL stack */
987 SSL_free( _ssl_context[sock] );
988 _ssl_context[sock] = NULL;
997 int SockClose(int sock)
998 /* close a socket gracefully */
1003 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
1004 /* Clean up the SSL stack */
1005 SSL_free( _ssl_context[sock] );
1006 _ssl_context[sock] = NULL;
1012 * This hangs in RedHat 6.2 after fetchmail runs for a while a
1013 * FIN_WAIT2 comes up in netstat and fetchmail never returns from
1014 * the recv system call. (Reported from jtnews
1015 * <jtnews@bellatlantic.net>, Wed, 24 May 2000 21:26:02.)
1017 * Half-close the connection first so the other end gets notified.
1019 * This stops sends but allows receives (effectively, it sends a
1021 if (shutdown(sock, 1) == 0) {
1023 /* If there is any data still waiting in the queue, discard it.
1024 * Call recv() until either it returns 0 (meaning we received a FIN)
1025 * or any error occurs. This makes sure all data sent by the other
1026 * side is acknowledged at the TCP level.
1028 if (fm_peek(sock, &ch, 1) > 0)
1029 while (fm_read(sock, &ch, 1) > 0)
1032 #endif /* __UNUSED__ */
1034 /* if there's an error closing at this point, not much we can do */
1035 return(fm_close(sock)); /* this is guarded */
1040 * Workaround Microsoft Winsock recv/WSARecv(..., MSG_PEEK) bug.
1041 * See http://sources.redhat.com/ml/cygwin/2001-08/msg00628.html
1044 static ssize_t cygwin_read(int sock, void *buf, size_t count)
1049 if ((n = read(sock, bp, count)) == -1)
1054 if (outlevel >= O_VERBOSE)
1055 report(stdout, GT_("Cygwin socket read retry\n"));
1056 n2 = read(sock, bp + n, count - n);
1057 if (n2 == -1 || n + n2 != count) {
1058 report(stderr, GT_("Cygwin socket read retry failed!\n"));
1065 #endif /* __CYGWIN__ */
1069 * Use the chargen service to test input buffering directly.
1070 * You may have to uncomment the `chargen' service description in your
1071 * inetd.conf (and then SIGHUP inetd) for this to work. */
1074 int sock = SockOpen("localhost", 19, NULL);
1077 while (SockRead(sock, buf, sizeof(buf)-1))
1078 SockWrite(1, buf, strlen(buf));
1083 /* socket.c ends here */