2 * socket.c -- socket library functions
4 * Copyright 1998 by Eric S. Raymond.
5 * For license terms, see the file COPYING in this directory.
14 #endif /* HAVE_MEMORY_H */
15 #include <sys/types.h>
16 #include <sys/socket.h>
17 #include <netinet/in.h>
18 #include <arpa/inet.h>
20 #if defined(STDC_HEADERS)
23 #if defined(HAVE_UNISTD_H)
26 #if defined(HAVE_STDARG_H)
32 #include "fetchmail.h"
35 /* We need to define h_errno only if it is not already */
38 #ifdef HAVE_RES_SEARCH
39 /* some versions of FreeBSD should declare this but don't */
42 /* pretend we have h_errno to avoid some #ifdef's later */
46 #endif /* ndef h_errno */
49 #include <net/security.h>
50 #endif /* NET_SECURITY */
52 #ifdef HAVE_SOCKETPAIR
53 static int handle_plugin(const char *host,
54 const char *service, const char *plugin)
55 /* get a socket mediated through a given external command */
58 if (socketpair(AF_UNIX,SOCK_STREAM,0,fds))
60 report(stderr, _("fetchmail: socketpair failed\n"));
66 report(stderr, _("fetchmail: fork failed\n"));
70 /* fds[1] is the parent's end; close it for proper EOF
73 if ( (dup2(fds[0],0) == -1) || (dup2(fds[0],1) == -1) ) {
74 report(stderr, _("dup2 failed\n"));
77 /* fds[0] is now connected to 0 and 1; close it */
79 if (outlevel >= O_VERBOSE)
80 report(stderr, _("running %s %s %s\n"), plugin, host, service);
81 execlp(plugin,plugin,host,service,0);
82 report(stderr, _("execl(%s) failed\n"), plugin);
89 /* fds[0] is the child's end; close it for proper EOF detection */
93 #endif /* HAVE_SOCKETPAIR */
98 int SockCheckOpen(int fd)
99 /* poll given socket; is it selectable? */
107 FD_ZERO(&r); FD_ZERO(&w); FD_ZERO(&e);
110 tv.tv_sec = 0; tv.tv_usec = 0;
111 rt = select(fd+1, &r, &w, &e, &tv);
112 if (rt == -1 && (errno != EAGAIN && errno != EINTR))
118 #endif /* __UNUSED__ */
121 int SockOpen(const char *host, const char *service, const char *options,
124 struct addrinfo *ai, req;
126 void *request = NULL;
128 #endif /* NET_SECURITY */
130 #ifdef HAVE_SOCKETPAIR
132 return handle_plugin(host,service,plugin);
133 #endif /* HAVE_SOCKETPAIR */
134 memset(&req, 0, sizeof(struct addrinfo));
135 req.ai_socktype = SOCK_STREAM;
137 if (getaddrinfo(host, service, &req, &ai)) {
138 report(stderr, _("fetchmail: getaddrinfo(%s.%s)\n"), host,service);
146 if (net_security_strtorequest((char *)options, &request, &requestlen))
149 i = inner_connect(ai, request, requestlen, NULL, NULL, "fetchmail", NULL);
154 #else /* NET_SECURITY */
155 i = inner_connect(ai, NULL, 0, NULL, NULL, "fetchmail", NULL);
156 #endif /* NET_SECURITY */
163 #ifndef HAVE_INET_ATON
165 #ifdef INADDR_BROADCAST
166 #define INADDR_NONE INADDR_BROADCAST
168 #define INADDR_NONE -1
171 #endif /* HAVE_INET_ATON */
173 int SockOpen(const char *host, int clientPort, const char *options,
176 int sock = -1; /* pacify -Wall */
177 #ifndef HAVE_INET_ATON
178 unsigned long inaddr;
179 #endif /* HAVE_INET_ATON */
180 struct sockaddr_in ad, **pptr;
183 #ifdef HAVE_SOCKETPAIR
186 sprintf(buf,"%d",clientPort);
187 return handle_plugin(host,buf,plugin);
189 #endif /* HAVE_SOCKETPAIR */
191 memset(&ad, 0, sizeof(ad));
192 ad.sin_family = AF_INET;
194 /* we'll accept a quad address */
195 #ifndef HAVE_INET_ATON
196 inaddr = inet_addr(host);
197 if (inaddr != INADDR_NONE)
198 memcpy(&ad.sin_addr, &inaddr, sizeof(inaddr));
201 if (!inet_aton(host, &ad.sin_addr))
202 #endif /* HAVE_INET_ATON */
204 hp = gethostbyname(host);
212 * Add a check to make sure the address has a valid IPv4 or IPv6
213 * length. This prevents buffer spamming by a broken DNS.
215 if(hp->h_length != 4 && hp->h_length != 8)
219 _("fetchmail: illegal address length received for host %s\n"),host);
223 * Try all addresses of a possibly multihomed host until we get
224 * a successful connect or until we run out of addresses.
226 pptr = (struct sockaddr_in **)hp->h_addr_list;
227 for(; *pptr != NULL; pptr++)
229 sock = socket(AF_INET, SOCK_STREAM, 0);
235 ad.sin_port = htons(clientPort);
236 memcpy(&ad.sin_addr, *pptr, sizeof(struct in_addr));
237 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) == 0)
240 memset(&ad, 0, sizeof(ad));
241 ad.sin_family = AF_INET;
252 ad.sin_port = htons(clientPort);
254 sock = socket(AF_INET, SOCK_STREAM, 0);
260 if (connect(sock, (struct sockaddr *) &ad, sizeof(ad)) < 0)
274 #if defined(HAVE_STDARG_H)
275 int SockPrintf(int sock, const char* format, ...)
278 int SockPrintf(sock,format,va_alist)
287 #if defined(HAVE_STDARG_H)
288 va_start(ap, format) ;
292 #ifdef HAVE_VSNPRINTF
293 vsnprintf(buf, sizeof(buf), format, ap);
295 vsprintf(buf, format, ap);
298 return SockWrite(sock, buf, strlen(buf));
308 static SSL_CTX *_ctx = NULL;
309 static SSL *_ssl_context[FD_SETSIZE];
311 SSL *SSLGetContext( int );
312 #endif /* SSL_ENABLE */
314 int SockWrite(int sock, char *buf, int len)
324 if( NULL != ( ssl = SSLGetContext( sock ) ) )
325 n = SSL_write(ssl, buf, len);
327 n = write(sock, buf, len);
329 n = write(sock, buf, len);
340 int SockRead(int sock, char *buf, int len)
342 char *newline, *bp = buf;
352 * The reason for these gymnastics is that we want two things:
353 * (1) to read \n-terminated lines,
354 * (2) to return the true length of data read, even if the
355 * data coming in has embedded NULS.
358 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
360 /* OK... SSL_peek works a little different from MSG_PEEK
361 Problem is that SSL_peek can return 0 if there
362 is no data currently available. If, on the other
363 hand, we loose the socket, we also get a zero, but
364 the SSL_read then SEGFAULTS! To deal with this,
365 we'll check the error code any time we get a return
366 of zero from SSL_peek. If we have an error, we bail.
367 If we don't, we read one character in SSL_read and
368 loop. This should continue to work even if they
369 later change the behavior of SSL_peek
370 to "fix" this problem... :-( */
371 if ((n = SSL_peek(ssl, bp, len)) < 0) {
375 /* SSL_peek says no data... Does he mean no data
376 or did the connection blow up? If we got an error
378 if( 0 != ( n = ERR_get_error() ) ) {
381 /* We didn't get an error so read at least one
382 character at this point and loop */
384 /* Make sure newline start out NULL!
385 * We don't have a string to pass through
386 * the strchr at this point yet */
388 } else if ((newline = memchr(bp, '\n', n)) != NULL)
389 n = newline - bp + 1;
390 if ((n = SSL_read(ssl, bp, n)) == -1) {
393 /* Check for case where our single character turned out to
394 * be a newline... (It wasn't going to get caught by
395 * the strchr above if it came from the hack... ). */
396 if( NULL == newline && 1 == n && '\n' == *bp ) {
397 /* Got our newline - this will break
398 out of the loop now */
402 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
404 if ((newline = memchr(bp, '\n', n)) != NULL)
405 n = newline - bp + 1;
406 if ((n = read(sock, bp, n)) == -1)
410 if ((n = recv(sock, bp, len, MSG_PEEK)) <= 0)
412 if ((newline = memchr(bp, '\n', n)) != NULL)
413 n = newline - bp + 1;
414 if ((n = read(sock, bp, n)) == -1)
425 int SockPeek(int sock)
426 /* peek at the next socket character without actually reading it */
435 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
436 n = SSL_peek(ssl, &ch, 1);
438 /* This code really needs to implement a "hold back"
439 * to simulate a functioning SSL_peek()... sigh...
440 * Has to be coordinated with the read code above.
441 * Next on the list todo... */
443 /* SSL_peek says no data... Does he mean no data
444 or did the connection blow up? If we got an error
446 if( 0 != ( n = ERR_get_error() ) ) {
450 /* Haven't seen this case actually occur, but...
451 if the problem in SockRead can occur, this should
452 be possible... Just not sure what to do here.
453 This should be a safe "punt" the "peek" but don't
454 "punt" the "session"... */
456 return 0; /* Give him a '\0' character */
459 n = recv(sock, &ch, 1, MSG_PEEK);
462 n = recv(sock, &ch, 1, MSG_PEEK);
472 static char *_ssl_server_cname = NULL;
474 SSL *SSLGetContext( int sock )
476 /* If SSLOpen has never initialized - just return NULL */
480 if( sock < 0 || sock > FD_SETSIZE )
482 return _ssl_context[sock];
486 int SSL_verify_callback( int ok_return, X509_STORE_CTX *ctx )
495 x509_cert = X509_STORE_CTX_get_current_cert(ctx);
496 err = X509_STORE_CTX_get_error(ctx);
497 depth = X509_STORE_CTX_get_error_depth(ctx);
499 X509_NAME_oneline(X509_get_subject_name(x509_cert), buf, 256);
500 X509_NAME_oneline(X509_get_issuer_name(x509_cert), ibuf, 256);
502 /* Just to be sure those buffers are terminated... I think the
503 X509 libraries do, but... */
504 buf[256] = ibuf[256] = '\0';
507 if( ( str_ptr = strstr( ibuf, "/O=" ) ) ) {
509 strcpy( cbuf, str_ptr );
510 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
513 if (outlevel == O_VERBOSE)
514 report(stdout, "Issuer Organization: %s", cbuf );
516 if (outlevel == O_VERBOSE)
517 report(stdout, "Unknown Organization", cbuf );
519 if( ( str_ptr = strstr( ibuf, "/CN=" ) ) ) {
521 strcpy( cbuf, str_ptr );
522 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
525 if (outlevel == O_VERBOSE)
526 report(stdout, "Issuer CommonName: %s", cbuf );
528 if (outlevel == O_VERBOSE)
529 report(stdout, "Unknown Issuer CommonName", cbuf );
531 if( ( str_ptr = strstr( buf, "/CN=" ) ) ) {
533 strcpy( cbuf, str_ptr );
534 if( ( str_ptr = strchr(cbuf, '/' ) ) ) {
537 if (outlevel == O_VERBOSE)
538 report(stdout, "Server CommonName: %s", cbuf );
539 /* Should we have some wildcarding here? */
540 if ( NULL != _ssl_server_cname && 0 != strcmp( cbuf, _ssl_server_cname ) ) {
541 report(stdout, "Server CommonName mismatch: %s != %s", cbuf, _ssl_server_cname );
544 if (outlevel == O_VERBOSE)
545 report(stdout, "Unknown Server CommonName", cbuf );
549 switch (ctx->error) {
550 case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
551 X509_NAME_oneline(X509_get_issuer_name(ctx->current_cert), buf, 256);
552 report(stdout, "unknown issuer= %s", buf);
554 case X509_V_ERR_CERT_NOT_YET_VALID:
555 case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
556 report(stderr, "Server Certificate not yet valid");
558 case X509_V_ERR_CERT_HAS_EXPIRED:
559 case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
560 report(stderr, "Server Certificate expired");
563 /* We are not requiring or validating server or issuer id's as yet */
564 /* Always return OK from here */
570 /* performs initial SSL handshake over the connected socket
571 * uses SSL *ssl global variable, which is currently defined
574 int SSLOpen(int sock, char *mycert, char *mykey, char *servercname )
576 SSL_load_error_strings();
577 SSLeay_add_ssl_algorithms();
579 if( sock < 0 || sock > FD_SETSIZE ) {
580 report(stderr, "File descriptor out of range for SSL" );
585 /* Be picky and make sure the memory is cleared */
586 memset( _ssl_context, 0, sizeof( _ssl_context ) );
587 _ctx = SSL_CTX_new(SSLv23_client_method());
589 ERR_print_errors_fp(stderr);
594 _ssl_context[sock] = SSL_new(_ctx);
596 if(_ssl_context[sock] == NULL) {
597 ERR_print_errors_fp(stderr);
601 /* This static is for the verify callback */
602 _ssl_server_cname = servercname;
604 SSL_CTX_set_verify(_ctx, SSL_VERIFY_PEER, SSL_verify_callback);
606 if( mycert || mykey ) {
608 /* Ok... He has a certificate file defined, so lets declare it. If
609 * he does NOT have a separate certificate and private key file then
610 * assume that it's a combined key and certificate file.
616 SSL_use_certificate_file(_ssl_context[sock], mycert, SSL_FILETYPE_PEM);
617 SSL_use_RSAPrivateKey_file(_ssl_context[sock], mykey, SSL_FILETYPE_PEM);
620 SSL_set_fd(_ssl_context[sock], sock);
622 if(SSL_connect(_ssl_context[sock]) == -1) {
623 ERR_print_errors_fp(stderr);
631 int SockClose(int sock)
632 /* close a socket (someday we may do other cleanup here) */
637 if( NULL != ( ssl = SSLGetContext( sock ) ) ) {
638 /* Clean up the SSL stack */
639 SSL_free( _ssl_context[sock] );
640 _ssl_context[sock] = NULL;
648 * Use the chargen service to test input buffering directly.
649 * You may have to uncomment the `chargen' service description in your
650 * inetd.conf (and then SIGHUP inetd) for this to work.
654 int sock = SockOpen("localhost", 19, NULL);
657 while (SockRead(sock, buf, sizeof(buf)-1))
658 SockWrite(1, buf, strlen(buf));
663 /* socket.c ends here */