The '# URL = http://apps.facebook.com/onthefarm/track.php?...' split
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.70 2009/12/15 17:51:14 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/jbsockets.c,v $
5  *
6  * Purpose     :  Contains wrappers for system-specific sockets code,
7  *                so that the rest of Junkbuster can be more
8  *                OS-independent.  Contains #ifdefs to make this work
9  *                on many platforms.
10  *
11  * Copyright   :  Written by and Copyright (C) 2001-2009 the
12  *                Privoxy team. http://www.privoxy.org/
13  *
14  *                Based on the Internet Junkbuster originally written
15  *                by and Copyright (C) 1997 Anonymous Coders and 
16  *                Junkbusters Corporation.  http://www.junkbusters.com
17  *
18  *                This program is free software; you can redistribute it 
19  *                and/or modify it under the terms of the GNU General
20  *                Public License as published by the Free Software
21  *                Foundation; either version 2 of the License, or (at
22  *                your option) any later version.
23  *
24  *                This program is distributed in the hope that it will
25  *                be useful, but WITHOUT ANY WARRANTY; without even the
26  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
27  *                PARTICULAR PURPOSE.  See the GNU General Public
28  *                License for more details.
29  *
30  *                The GNU General Public License should be included with
31  *                this file.  If not, you can view it at
32  *                http://www.gnu.org/copyleft/gpl.html
33  *                or write to the Free Software Foundation, Inc., 59
34  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
35  *
36  *********************************************************************/
37
38
39 #include "config.h"
40
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <errno.h>
45 #include <fcntl.h>
46 #include <sys/types.h>
47
48 #ifdef _WIN32
49
50 #ifndef STRICT
51 #define STRICT
52 #endif
53 #include <windows.h>
54 #include <sys/timeb.h>
55 #include <io.h>
56
57 #else
58
59 #ifndef __OS2__
60 #include <unistd.h>
61 #endif
62 #include <sys/time.h>
63 #include <netinet/in.h>
64 #include <sys/ioctl.h>
65 #include <netdb.h>
66 #include <sys/socket.h>
67
68 #ifndef __BEOS__
69 #include <netinet/tcp.h>
70 #ifndef __OS2__
71 #include <arpa/inet.h>
72 #endif
73 #else
74 #include <socket.h>
75 #endif
76
77 #if defined(__EMX__) || defined (__OS2__)
78 #include <sys/select.h>  /* OS/2/EMX needs a little help with select */
79 #ifdef __OS2__
80 #include <nerrno.h>
81 #endif
82 #endif
83
84 #endif
85
86 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
87 #ifdef HAVE_POLL
88 #ifdef __GLIBC__
89 #include <sys/poll.h>
90 #else
91 #include <poll.h>
92 #endif /* def __GLIBC__ */
93 #endif /* HAVE_POLL */
94 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
95
96 #include "project.h"
97
98 /* For mutex semaphores only */
99 #include "jcc.h"
100
101 #include "jbsockets.h"
102 #include "filters.h"
103 #include "errlog.h"
104
105 /* Mac OSX doesn't define AI_NUMERICSESRV */
106 #ifndef AI_NUMERICSERV
107 #define AI_NUMERICSERV 0
108 #endif
109
110 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
111
112 /*
113  * Maximum number of gethostbyname(_r) retries in case of
114  * soft errors (TRY_AGAIN).
115  * XXX: Does it make sense to make this a config option?
116  */
117 #define MAX_DNS_RETRIES 10
118
119 #define MAX_LISTEN_BACKLOG 128
120
121
122 /*********************************************************************
123  *
124  * Function    :  connect_to
125  *
126  * Description :  Open a socket and connect to it.  Will check
127  *                that this is allowed according to ACL.
128  *
129  * Parameters  :
130  *          1  :  host = hostname to connect to
131  *          2  :  portnum = port to connent on (XXX: should be unsigned)
132  *          3  :  csp = Current client state (buffers, headers, etc...)
133  *                      Not modified, only used for source IP and ACL.
134  *
135  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket
136  *                file descriptor.
137  *
138  *********************************************************************/
139 #ifdef HAVE_RFC2553
140 /* Getaddrinfo implementation */
141 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
142 {
143    struct addrinfo hints, *result, *rp;
144    char service[6];
145    int retval;
146    jb_socket fd;
147    fd_set wfds;
148    struct timeval tv[1];
149 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
150    int   flags;
151 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
152    int connect_failed;
153
154 #ifdef FEATURE_ACL
155    struct access_control_addr dst[1];
156 #endif /* def FEATURE_ACL */
157
158    retval = snprintf(service, sizeof(service), "%d", portnum);
159    if ((-1 == retval) || (sizeof(service) <= retval))
160    {
161       log_error(LOG_LEVEL_ERROR,
162          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
163          portnum);
164       csp->http->host_ip_addr_str = strdup("unknown");
165       return(JB_INVALID_SOCKET);
166    }
167
168    memset((char *)&hints, 0, sizeof(hints));
169    hints.ai_family = AF_UNSPEC;
170    hints.ai_socktype = SOCK_STREAM;
171    hints.ai_flags = AI_NUMERICSERV; /* avoid service look-up */
172 #ifdef AI_ADDRCONFIG
173    hints.ai_flags |= AI_ADDRCONFIG;
174 #endif
175    if ((retval = getaddrinfo(host, service, &hints, &result)))
176    {
177       log_error(LOG_LEVEL_INFO,
178          "Can not resolve %s: %s", host, gai_strerror(retval));
179       csp->http->host_ip_addr_str = strdup("unknown");
180       return(JB_INVALID_SOCKET);
181    }
182
183    for (rp = result; rp != NULL; rp = rp->ai_next)
184    {
185
186 #ifdef FEATURE_ACL
187       memcpy(&dst->addr, rp->ai_addr, rp->ai_addrlen);
188
189       if (block_acl(dst, csp))
190       {
191 #ifdef __OS2__
192          errno = SOCEPERM;
193 #else
194          errno = EPERM;
195 #endif
196          continue;
197       }
198 #endif /* def FEATURE_ACL */
199
200       csp->http->host_ip_addr_str = malloc(NI_MAXHOST);
201       if (NULL == csp->http->host_ip_addr_str)
202       {
203          log_error(LOG_LEVEL_ERROR,
204             "Out of memory while getting the server IP address.");
205          return JB_INVALID_SOCKET;
206       }
207       retval = getnameinfo(rp->ai_addr, rp->ai_addrlen,
208          csp->http->host_ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
209       if (!csp->http->host_ip_addr_str || retval)
210       {
211          log_error(LOG_LEVEL_ERROR,
212             "Can not save csp->http->host_ip_addr_str: %s",
213             (csp->http->host_ip_addr_str) ?
214             gai_strerror(retval) : "Insufficient memory");
215          freez(csp->http->host_ip_addr_str);
216          continue;
217       }
218
219 #ifdef _WIN32
220       if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) ==
221             JB_INVALID_SOCKET)
222 #else
223       if ((fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol)) < 0)
224 #endif
225       {
226          continue;
227       }
228
229 #ifdef TCP_NODELAY
230       {  /* turn off TCP coalescence */
231          int mi = 1;
232          setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
233       }
234 #endif /* def TCP_NODELAY */
235
236 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
237       if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
238       {
239          flags |= O_NDELAY;
240          fcntl(fd, F_SETFL, flags);
241       }
242 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
243
244       connect_failed = 0;
245       while (connect(fd, rp->ai_addr, rp->ai_addrlen) == JB_INVALID_SOCKET)
246       {
247 #ifdef _WIN32
248          if (errno == WSAEINPROGRESS)
249 #elif __OS2__
250          if (sock_errno() == EINPROGRESS)
251 #else /* ifndef _WIN32 */
252          if (errno == EINPROGRESS)
253 #endif /* ndef _WIN32 || __OS2__ */
254          {
255             break;
256          }
257
258 #ifdef __OS2__
259          if (sock_errno() != EINTR)
260 #else
261          if (errno != EINTR)
262 #endif /* __OS2__ */
263          {
264             close_socket(fd);
265             connect_failed = 1;
266             break;
267          }
268       }
269       if (connect_failed)
270       {
271          continue;
272       }
273
274 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
275       if (flags != -1)
276       {
277          flags &= ~O_NDELAY;
278          fcntl(fd, F_SETFL, flags);
279       }
280 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
281
282       /* wait for connection to complete */
283       FD_ZERO(&wfds);
284       FD_SET(fd, &wfds);
285
286       tv->tv_sec  = 30;
287       tv->tv_usec = 0;
288
289       /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
290       if ((select((int)fd + 1, NULL, &wfds, NULL, tv) > 0)
291          && FD_ISSET(fd, &wfds))
292       {
293          /*
294           * See Linux connect(2) man page for more info
295           * about connecting on non-blocking socket.
296           */
297          int socket_in_error;
298          socklen_t optlen = sizeof(socket_in_error);
299          if (!getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_in_error, &optlen))
300          {
301             if (!socket_in_error)
302             {
303                /* Connection established, no need to try other addresses. */
304                break;
305             }
306             log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s: %s.",
307                csp->http->host_ip_addr_str, service, strerror(socket_in_error));
308          }
309          else
310          {
311             log_error(LOG_LEVEL_ERROR, "Could not get the state of "
312                "the connection to [%s]:%s: %s; dropping connection.",
313                csp->http->host_ip_addr_str, service, strerror(errno));
314          }
315       }
316
317       /* Connection failed, try next address */
318       close_socket(fd);
319    }
320
321    freeaddrinfo(result);
322    if (!rp)
323    {
324       log_error(LOG_LEVEL_CONNECT, "Could not connect to [%s]:%s.",
325          host, service);
326       return(JB_INVALID_SOCKET);
327    }
328    log_error(LOG_LEVEL_CONNECT, "Connected to %s[%s]:%s.",
329       host, csp->http->host_ip_addr_str, service);
330
331    return(fd);
332
333 }
334
335 #else /* ndef HAVE_RFC2553 */
336 /* Pre-getaddrinfo implementation */
337
338 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
339 {
340    struct sockaddr_in inaddr;
341    jb_socket fd;
342    unsigned int addr;
343    fd_set wfds;
344    struct timeval tv[1];
345 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
346    int   flags;
347 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
348
349 #ifdef FEATURE_ACL
350    struct access_control_addr dst[1];
351 #endif /* def FEATURE_ACL */
352
353    memset((char *)&inaddr, 0, sizeof inaddr);
354
355    if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
356    {
357       csp->http->host_ip_addr_str = strdup("unknown");
358       return(JB_INVALID_SOCKET);
359    }
360
361 #ifdef FEATURE_ACL
362    dst->addr = ntohl(addr);
363    dst->port = portnum;
364
365    if (block_acl(dst, csp))
366    {
367 #ifdef __OS2__
368       errno = SOCEPERM;
369 #else
370       errno = EPERM;
371 #endif
372       return(JB_INVALID_SOCKET);
373    }
374 #endif /* def FEATURE_ACL */
375
376    inaddr.sin_addr.s_addr = addr;
377    inaddr.sin_family      = AF_INET;
378    csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
379
380 #ifndef _WIN32
381    if (sizeof(inaddr.sin_port) == sizeof(short))
382 #endif /* ndef _WIN32 */
383    {
384       inaddr.sin_port = htons((unsigned short) portnum);
385    }
386 #ifndef _WIN32
387    else
388    {
389       inaddr.sin_port = htonl((unsigned long)portnum);
390    }
391 #endif /* ndef _WIN32 */
392
393 #ifdef _WIN32
394    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
395 #else
396    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
397 #endif
398    {
399       return(JB_INVALID_SOCKET);
400    }
401
402 #ifdef TCP_NODELAY
403    {  /* turn off TCP coalescence */
404       int mi = 1;
405       setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
406    }
407 #endif /* def TCP_NODELAY */
408
409 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
410    if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
411    {
412       flags |= O_NDELAY;
413       fcntl(fd, F_SETFL, flags);
414    }
415 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
416
417    while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
418    {
419 #ifdef _WIN32
420       if (errno == WSAEINPROGRESS)
421 #elif __OS2__ 
422       if (sock_errno() == EINPROGRESS)
423 #else /* ifndef _WIN32 */
424       if (errno == EINPROGRESS)
425 #endif /* ndef _WIN32 || __OS2__ */
426       {
427          break;
428       }
429
430 #ifdef __OS2__ 
431       if (sock_errno() != EINTR)
432 #else
433       if (errno != EINTR)
434 #endif /* __OS2__ */
435       {
436          close_socket(fd);
437          return(JB_INVALID_SOCKET);
438       }
439    }
440
441 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
442    if (flags != -1)
443    {
444       flags &= ~O_NDELAY;
445       fcntl(fd, F_SETFL, flags);
446    }
447 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
448
449    /* wait for connection to complete */
450    FD_ZERO(&wfds);
451    FD_SET(fd, &wfds);
452
453    tv->tv_sec  = 30;
454    tv->tv_usec = 0;
455
456    /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
457    if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
458    {
459       close_socket(fd);
460       return(JB_INVALID_SOCKET);
461    }
462    return(fd);
463
464 }
465 #endif /* ndef HAVE_RFC2553 */
466
467
468 /*********************************************************************
469  *
470  * Function    :  write_socket
471  *
472  * Description :  Write the contents of buf (for n bytes) to socket fd.
473  *
474  * Parameters  :
475  *          1  :  fd = file descriptor (aka. handle) of socket to write to.
476  *          2  :  buf = pointer to data to be written.
477  *          3  :  len = length of data to be written to the socket "fd".
478  *
479  * Returns     :  0 on success (entire buffer sent).
480  *                nonzero on error.
481  *
482  *********************************************************************/
483 #ifdef AMIGA
484 int write_socket(jb_socket fd, const char *buf, ssize_t len)
485 #else
486 int write_socket(jb_socket fd, const char *buf, size_t len)
487 #endif
488 {
489    if (len == 0)
490    {
491       return 0;
492    }
493
494    if (len < 0) /* constant condition - size_t isn't ever negative */ 
495    {
496       return 1;
497    }
498
499    log_error(LOG_LEVEL_LOG, "%N", len, buf);
500
501 #if defined(_WIN32)
502    return (send(fd, buf, (int)len, 0) != (int)len);
503 #elif defined(__BEOS__) || defined(AMIGA)
504    return (send(fd, buf, len, 0) != len);
505 #elif defined(__OS2__)
506    /*
507     * Break the data up into SOCKET_SEND_MAX chunks for sending...
508     * OS/2 seemed to complain when the chunks were too large.
509     */
510 #define SOCKET_SEND_MAX 65000
511    {
512       int write_len = 0, send_len, send_rc = 0, i = 0;
513       while ((i < len) && (send_rc != -1))
514       {
515          if ((i + SOCKET_SEND_MAX) > len)
516             send_len = len - i;
517          else
518             send_len = SOCKET_SEND_MAX;
519          send_rc = send(fd,(char*)buf + i, send_len, 0);
520          if (send_rc == -1)
521             return 1;
522          i = i + send_len;
523       }
524       return 0;
525    }
526 #else
527    return (write(fd, buf, len) != len);
528 #endif
529
530 }
531
532
533 /*********************************************************************
534  *
535  * Function    :  read_socket
536  *
537  * Description :  Read from a TCP/IP socket in a platform independent way.
538  *
539  * Parameters  :
540  *          1  :  fd = file descriptor of the socket to read
541  *          2  :  buf = pointer to buffer where data will be written
542  *                Must be >= len bytes long.
543  *          3  :  len = maximum number of bytes to read
544  *
545  * Returns     :  On success, the number of bytes read is returned (zero
546  *                indicates end of file), and the file position is advanced
547  *                by this number.  It is not an error if this number is
548  *                smaller than the number of bytes requested; this may hap-
549  *                pen for example because fewer bytes are actually available
550  *                right now (maybe because we were close to end-of-file, or
551  *                because we are reading from a pipe, or from a terminal,
552  *                or because read() was interrupted by a signal).  On error,
553  *                -1 is returned, and errno is set appropriately.  In this
554  *                case it is left unspecified whether the file position (if
555  *                any) changes.
556  *
557  *********************************************************************/
558 int read_socket(jb_socket fd, char *buf, int len)
559 {
560    if (len <= 0)
561    {
562       return(0);
563    }
564
565 #if defined(_WIN32)
566    return(recv(fd, buf, len, 0));
567 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
568    return(recv(fd, buf, (size_t)len, 0));
569 #else
570    return((int)read(fd, buf, (size_t)len));
571 #endif
572 }
573
574
575 /*********************************************************************
576  *
577  * Function    :  data_is_available
578  *
579  * Description :  Waits for data to arrive on a socket.
580  *
581  * Parameters  :
582  *          1  :  fd = file descriptor of the socket to read
583  *          2  :  seconds_to_wait = number of seconds after which we give up.
584  *
585  * Returns     :  TRUE if data arrived in time,
586  *                FALSE otherwise.
587  *
588  *********************************************************************/
589 int data_is_available(jb_socket fd, int seconds_to_wait)
590 {
591    char buf[10];
592    fd_set rfds;
593    struct timeval timeout;
594    int n;
595
596    memset(&timeout, 0, sizeof(timeout));
597    timeout.tv_sec = seconds_to_wait;
598
599 #ifdef __OS2__
600    /* Copy and pasted from jcc.c ... */
601    memset(&rfds, 0, sizeof(fd_set));
602 #else
603    FD_ZERO(&rfds);
604 #endif
605    FD_SET(fd, &rfds);
606
607    n = select(fd+1, &rfds, NULL, NULL, &timeout);
608
609    /*
610     * XXX: Do we care about the different error conditions?
611     */
612    return ((n == 1) && (1 == recv(fd, buf, 1, MSG_PEEK)));
613 }
614
615
616 /*********************************************************************
617  *
618  * Function    :  close_socket
619  *
620  * Description :  Closes a TCP/IP socket
621  *
622  * Parameters  :
623  *          1  :  fd = file descriptor of socket to be closed
624  *
625  * Returns     :  void
626  *
627  *********************************************************************/
628 void close_socket(jb_socket fd)
629 {
630 #if defined(_WIN32) || defined(__BEOS__)
631    closesocket(fd);
632 #elif defined(AMIGA)
633    CloseSocket(fd); 
634 #elif defined(__OS2__)
635    soclose(fd);
636 #else
637    close(fd);
638 #endif
639
640 }
641
642
643 /*********************************************************************
644  *
645  * Function    :  bind_port
646  *
647  * Description :  Call socket, set socket options, and listen.
648  *                Called by listen_loop to "boot up" our proxy address.
649  *
650  * Parameters  :
651  *          1  :  hostnam = TCP/IP address to bind/listen to
652  *          2  :  portnum = port to listen on
653  *          3  :  pfd = pointer used to return file descriptor.
654  *
655  * Returns     :  if success, returns 0 and sets *pfd.
656  *                if failure, returns -3 if address is in use,
657  *                                    -2 if address unresolvable,
658  *                                    -1 otherwise
659  *********************************************************************/
660 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
661 {
662 #ifdef HAVE_RFC2553
663    struct addrinfo hints;
664    struct addrinfo *result, *rp;
665    /*
666     * XXX: portnum should be a string to allow symbolic service
667     * names in the configuration file and to avoid the following
668     * int2string.
669     */
670    char servnam[6];
671    int retval;
672 #else
673    struct sockaddr_in inaddr;
674 #endif /* def HAVE_RFC2553 */
675    jb_socket fd;
676 #ifndef _WIN32
677    int one = 1;
678 #endif /* ndef _WIN32 */
679
680    *pfd = JB_INVALID_SOCKET;
681
682 #ifdef HAVE_RFC2553
683    retval = snprintf(servnam, sizeof(servnam), "%d", portnum);
684    if ((-1 == retval) || (sizeof(servnam) <= retval))
685    {
686       log_error(LOG_LEVEL_ERROR,
687          "Port number (%d) ASCII decimal representation doesn't fit into 6 bytes",
688          portnum);
689       return -1;
690    }
691
692    memset(&hints, 0, sizeof(struct addrinfo));
693    if (hostnam == NULL)
694    {
695       /*
696        * XXX: This is a hack. The right thing to do
697        * would be to bind to both AF_INET and AF_INET6.
698        * This will also fail if there is no AF_INET
699        * version available.
700        */
701       hints.ai_family = AF_INET;
702    }
703    else
704    {
705       hints.ai_family = AF_UNSPEC;
706    }
707    hints.ai_socktype = SOCK_STREAM;
708    hints.ai_flags = AI_PASSIVE;
709 #ifdef AI_ADDRCONFIG
710    hints.ai_flags |= AI_ADDRCONFIG;
711 #endif
712    hints.ai_protocol = 0; /* Realy any stream protocol or TCP only */
713    hints.ai_canonname = NULL;
714    hints.ai_addr = NULL;
715    hints.ai_next = NULL;
716
717    if ((retval = getaddrinfo(hostnam, servnam, &hints, &result)))
718    {
719       log_error(LOG_LEVEL_ERROR,
720          "Can not resolve %s: %s", hostnam, gai_strerror(retval));
721       return -2;
722    }
723 #else
724    memset((char *)&inaddr, '\0', sizeof inaddr);
725
726    inaddr.sin_family      = AF_INET;
727    inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
728
729    if (inaddr.sin_addr.s_addr == INADDR_NONE)
730    {
731       return(-2);
732    }
733
734 #ifndef _WIN32
735    if (sizeof(inaddr.sin_port) == sizeof(short))
736 #endif /* ndef _WIN32 */
737    {
738       inaddr.sin_port = htons((unsigned short) portnum);
739    }
740 #ifndef _WIN32
741    else
742    {
743       inaddr.sin_port = htonl((unsigned long) portnum);
744    }
745 #endif /* ndef _WIN32 */
746 #endif /* def HAVE_RFC2553 */
747
748 #ifdef HAVE_RFC2553
749    for (rp = result; rp != NULL; rp = rp->ai_next)
750    {
751       fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
752 #else
753    fd = socket(AF_INET, SOCK_STREAM, 0);
754 #endif /* def HAVE_RFC2553 */
755
756 #ifdef _WIN32
757    if (fd == JB_INVALID_SOCKET)
758 #else
759    if (fd < 0)
760 #endif
761    {
762 #ifdef HAVE_RFC2553
763       continue;
764 #else
765       return(-1);
766 #endif
767    }
768
769 #ifndef _WIN32
770    /*
771     * This is not needed for Win32 - in fact, it stops
772     * duplicate instances of Privoxy from being caught.
773     *
774     * On UNIX, we assume the user is sensible enough not
775     * to start Privoxy multiple times on the same IP.
776     * Without this, stopping and restarting Privoxy
777     * from a script fails.
778     * Note: SO_REUSEADDR is meant to only take over
779     * sockets which are *not* in listen state in Linux,
780     * e.g. sockets in TIME_WAIT. YMMV.
781     */
782    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
783 #endif /* ndef _WIN32 */
784
785 #ifdef HAVE_RFC2553
786    if (bind(fd, rp->ai_addr, rp->ai_addrlen) < 0)
787 #else
788    if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
789 #endif
790    {
791 #ifdef _WIN32
792       errno = WSAGetLastError();
793       if (errno == WSAEADDRINUSE)
794 #else
795       if (errno == EADDRINUSE)
796 #endif
797       {
798 #ifdef HAVE_RFC2553
799          freeaddrinfo(result);
800 #endif
801          close_socket(fd);
802          return(-3);
803       }
804       else
805       {
806          close_socket(fd);
807 #ifndef HAVE_RFC2553
808          return(-1);
809       }
810    }
811 #else
812       }
813    }
814    else
815    {
816       /* bind() succeeded, escape from for-loop */
817       /*
818        * XXX: Support multiple listening sockets (e.g. localhost
819        * resolves to AF_INET and AF_INET6, but only the first address
820        * is used
821        */
822       break;
823    }
824    }
825
826    freeaddrinfo(result);
827    if (rp == NULL)
828    {
829       /* All bind()s failed */
830       return(-1);
831    }
832 #endif /* ndef HAVE_RFC2553 */
833
834    while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
835    {
836       if (errno != EINTR)
837       {
838          return(-1);
839       }
840    }
841
842    *pfd = fd;
843    return 0;
844
845 }
846
847
848 /*********************************************************************
849  *
850  * Function    :  get_host_information
851  *
852  * Description :  Determines the IP address the client used to
853  *                reach us and the hostname associated with it.
854  *
855  *                XXX: Most of the code has been copy and pasted
856  *                from accept_connection() and not all of the
857  *                ifdefs paths have been tested afterwards.
858  *
859  * Parameters  :
860  *          1  :  afd = File descriptor returned from accept().
861  *          2  :  ip_address = Pointer to return the pointer to
862  *                             the ip address string.
863  *          3  :  hostname =   Pointer to return the pointer to
864  *                             the hostname or NULL if the caller
865  *                             isn't interested in it.
866  *
867  * Returns     :  void.
868  *
869  *********************************************************************/
870 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
871 {
872 #ifdef HAVE_RFC2553
873    struct sockaddr_storage server;
874    int retval;
875 #else
876    struct sockaddr_in server;
877    struct hostent *host = NULL;
878 #endif /* HAVE_RFC2553 */
879 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
880    /* according to accept_connection() this fixes a warning. */
881    int s_length, s_length_provided;
882 #else
883    socklen_t s_length, s_length_provided;
884 #endif
885 #ifndef HAVE_RFC2553
886 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) ||  defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
887    struct hostent result;
888 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
889    struct hostent_data hdata;
890 #else
891    char hbuf[HOSTENT_BUFFER_SIZE];
892    int thd_err;
893 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
894 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
895 #endif /* ifndef HAVE_RFC2553 */
896    s_length = s_length_provided = sizeof(server);
897
898    if (NULL != hostname)
899    {
900       *hostname = NULL;
901    }
902    *ip_address = NULL;
903
904    if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
905    {
906       if (s_length > s_length_provided)
907       {
908          log_error(LOG_LEVEL_ERROR, "getsockname() truncated server address");
909          return;
910       }
911 #ifdef HAVE_RFC2553
912       *ip_address = malloc(NI_MAXHOST);
913       if (NULL == *ip_address)
914       {
915          log_error(LOG_LEVEL_ERROR,
916             "Out of memory while getting the client's IP address.");
917          return;
918       }
919       retval = getnameinfo((struct sockaddr *) &server, s_length,
920          *ip_address, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
921       if (retval)
922       {
923          log_error(LOG_LEVEL_ERROR,
924             "Unable to print my own IP address: %s", gai_strerror(retval));
925          freez(*ip_address);
926          return;
927       }
928 #else
929       *ip_address = strdup(inet_ntoa(server.sin_addr));
930 #endif /* HAVE_RFC2553 */
931       if (NULL == hostname)
932       {
933          /*
934           * We're done here, the caller isn't
935           * interested in knowing the hostname.
936           */
937          return;
938       }
939
940 #ifdef HAVE_RFC2553
941       *hostname = malloc(NI_MAXHOST);
942       if (NULL == *hostname)
943       {
944          log_error(LOG_LEVEL_ERROR,
945             "Out of memory while getting the client's hostname.");
946          return;
947       }
948       retval = getnameinfo((struct sockaddr *) &server, s_length,
949          *hostname, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
950       if (retval)
951       {
952          log_error(LOG_LEVEL_ERROR,
953             "Unable to resolve my own IP address: %s", gai_strerror(retval));
954          freez(*hostname);
955       }
956 #else
957 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
958       gethostbyaddr_r((const char *)&server.sin_addr,
959                       sizeof(server.sin_addr), AF_INET,
960                       &result, hbuf, HOSTENT_BUFFER_SIZE,
961                       &host, &thd_err);
962 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
963       host = gethostbyaddr_r((const char *)&server.sin_addr,
964                       sizeof(server.sin_addr), AF_INET,
965                       &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
966 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
967       if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
968                                sizeof(server.sin_addr), AF_INET,
969                                &result, &hdata))
970       {
971          host = &result;
972       }
973       else
974       {
975          host = NULL;
976       }
977 #elif defined(MUTEX_LOCKS_AVAILABLE)
978       privoxy_mutex_lock(&resolver_mutex);
979       host = gethostbyaddr((const char *)&server.sin_addr, 
980                            sizeof(server.sin_addr), AF_INET);
981       privoxy_mutex_unlock(&resolver_mutex);
982 #else
983       host = gethostbyaddr((const char *)&server.sin_addr, 
984                            sizeof(server.sin_addr), AF_INET);
985 #endif
986       if (host == NULL)
987       {
988          log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
989       }
990       else
991       {
992          *hostname = strdup(host->h_name);
993       }
994 #endif /* else def HAVE_RFC2553 */
995    }
996
997    return;
998 }
999
1000
1001 /*********************************************************************
1002  *
1003  * Function    :  accept_connection
1004  *
1005  * Description :  Accepts a connection on a socket.  Socket must have
1006  *                been created using bind_port().
1007  *
1008  * Parameters  :
1009  *          1  :  csp = Client state, cfd, ip_addr_str, and 
1010  *                ip_addr_long will be set by this routine.
1011  *          2  :  fd  = file descriptor returned from bind_port
1012  *
1013  * Returns     :  when a connection is accepted, it returns 1 (TRUE).
1014  *                On an error it returns 0 (FALSE).
1015  *
1016  *********************************************************************/
1017 int accept_connection(struct client_state * csp, jb_socket fd)
1018 {
1019 #ifdef HAVE_RFC2553
1020    /* XXX: client is stored directly into csp->tcp_addr */
1021 #define client (csp->tcp_addr)
1022    int retval;
1023 #else
1024    struct sockaddr_in client;
1025 #endif
1026    jb_socket afd;
1027 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
1028    /* Wierdness - fix a warning. */
1029    int c_length;
1030 #else
1031    socklen_t c_length;
1032 #endif
1033
1034    c_length = sizeof(client);
1035
1036 #ifdef _WIN32
1037    afd = accept (fd, (struct sockaddr *) &client, &c_length);
1038    if (afd == JB_INVALID_SOCKET)
1039    {
1040       return 0;
1041    }
1042 #else
1043    do
1044    {
1045 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
1046       struct accept_filter_arg af_options;
1047       bzero(&af_options, sizeof(af_options));
1048       strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
1049       setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &af_options, sizeof(af_options));
1050 #endif
1051       afd = accept (fd, (struct sockaddr *) &client, &c_length);
1052    } while (afd < 1 && errno == EINTR);
1053    if (afd < 0)
1054    {
1055       return 0;
1056    }
1057 #endif
1058
1059    csp->cfd = afd;
1060 #ifdef HAVE_RFC2553
1061    csp->ip_addr_str = malloc(NI_MAXHOST);
1062    if (NULL == csp->ip_addr_str)
1063    {
1064       log_error(LOG_LEVEL_ERROR,
1065          "Out of memory while getting the client's IP address.");
1066       return 0;
1067    }
1068    retval = getnameinfo((struct sockaddr *) &client, c_length,
1069          csp->ip_addr_str, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
1070    if (!csp->ip_addr_str || retval)
1071    {
1072       log_error(LOG_LEVEL_ERROR, "Can not save csp->ip_addr_str: %s",
1073             (csp->ip_addr_str) ? gai_strerror(retval) : "Insuffcient memory");
1074       freez(csp->ip_addr_str);
1075    }
1076 #undef client
1077 #else
1078    csp->ip_addr_str  = strdup(inet_ntoa(client.sin_addr));
1079    csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
1080 #endif /* def HAVE_RFC2553 */
1081
1082    return 1;
1083
1084 }
1085
1086
1087 /*********************************************************************
1088  *
1089  * Function    :  resolve_hostname_to_ip
1090  *
1091  * Description :  Resolve a hostname to an internet tcp/ip address.
1092  *                NULL or an empty string resolve to INADDR_ANY.
1093  *
1094  * Parameters  :
1095  *          1  :  host = hostname to resolve
1096  *
1097  * Returns     :  INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
1098  *
1099  *********************************************************************/
1100 unsigned long resolve_hostname_to_ip(const char *host)
1101 {
1102    struct sockaddr_in inaddr;
1103    struct hostent *hostp;
1104    unsigned int dns_retries = 0;
1105 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1106    struct hostent result;
1107 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1108    char hbuf[HOSTENT_BUFFER_SIZE];
1109    int thd_err;
1110 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
1111    struct hostent_data hdata;
1112 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
1113 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1114
1115    if ((host == NULL) || (*host == '\0'))
1116    {
1117       return(INADDR_ANY);
1118    }
1119
1120    memset((char *) &inaddr, 0, sizeof inaddr);
1121
1122    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
1123    {
1124 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
1125       while (gethostbyname_r(host, &result, hbuf,
1126                 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
1127              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1128       {   
1129          log_error(LOG_LEVEL_ERROR,
1130             "Timeout #%u while trying to resolve %s. Trying again.",
1131             dns_retries, host);
1132       }
1133 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
1134       while (NULL == (hostp = gethostbyname_r(host, &result,
1135                                  hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
1136              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1137       {   
1138          log_error(LOG_LEVEL_ERROR,
1139             "Timeout #%u while trying to resolve %s. Trying again.",
1140             dns_retries, host);
1141       }
1142 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
1143       /*
1144        * XXX: Doesn't retry in case of soft errors.
1145        * Does this gethostbyname_r version set h_errno?
1146        */
1147       if (0 == gethostbyname_r(host, &result, &hdata))
1148       {
1149          hostp = &result;
1150       }
1151       else
1152       {
1153          hostp = NULL;
1154       }
1155 #elif defined(MUTEX_LOCKS_AVAILABLE)
1156       privoxy_mutex_lock(&resolver_mutex);
1157       while (NULL == (hostp = gethostbyname(host))
1158              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1159       {   
1160          log_error(LOG_LEVEL_ERROR,
1161             "Timeout #%u while trying to resolve %s. Trying again.",
1162             dns_retries, host);
1163       }
1164       privoxy_mutex_unlock(&resolver_mutex);
1165 #else
1166       while (NULL == (hostp = gethostbyname(host))
1167              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
1168       {
1169          log_error(LOG_LEVEL_ERROR,
1170             "Timeout #%u while trying to resolve %s. Trying again.",
1171             dns_retries, host);
1172       }
1173 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
1174       /*
1175        * On Mac OSX, if a domain exists but doesn't have a type A
1176        * record associated with it, the h_addr member of the struct
1177        * hostent returned by gethostbyname is NULL, even if h_length
1178        * is 4. Therefore the second test below.
1179        */
1180       if (hostp == NULL || hostp->h_addr == NULL)
1181       {
1182          errno = EINVAL;
1183          log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
1184          return(INADDR_NONE);
1185       }
1186       if (hostp->h_addrtype != AF_INET)
1187       {
1188 #ifdef _WIN32
1189          errno = WSAEPROTOTYPE;
1190 #else
1191          errno = EPROTOTYPE;
1192 #endif 
1193          log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
1194          return(INADDR_NONE);
1195       }
1196       memcpy(
1197          (char *) &inaddr.sin_addr,
1198          (char *) hostp->h_addr,
1199          sizeof(inaddr.sin_addr)
1200       );
1201    }
1202    return(inaddr.sin_addr.s_addr);
1203
1204 }
1205
1206
1207 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1208 /*********************************************************************
1209  *
1210  * Function    :  socket_is_still_usable
1211  *
1212  * Description :  Decides whether or not an open socket is still usable.
1213  *
1214  * Parameters  :
1215  *          1  :  sfd = The socket to check.
1216  *
1217  * Returns     :  TRUE for yes, otherwise FALSE.
1218  *
1219  *********************************************************************/
1220 int socket_is_still_usable(jb_socket sfd)
1221 {
1222    char buf[10];
1223    int no_data_waiting;
1224
1225 #ifdef HAVE_POLL
1226    int poll_result;
1227    struct pollfd poll_fd[1];
1228
1229    memset(poll_fd, 0, sizeof(poll_fd));
1230    poll_fd[0].fd = sfd;
1231    poll_fd[0].events = POLLIN;
1232
1233    poll_result = poll(poll_fd, 1, 0);
1234
1235    if (-1 == poll_result)
1236    {
1237       log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
1238       return FALSE;
1239    }
1240    no_data_waiting = !(poll_fd[0].revents & POLLIN);
1241 #else
1242    fd_set readable_fds;
1243    struct timeval timeout;
1244    int ret;
1245
1246    memset(&timeout, '\0', sizeof(timeout));
1247    FD_ZERO(&readable_fds);
1248    FD_SET(sfd, &readable_fds);
1249
1250    ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
1251    if (ret < 0)
1252    {
1253       log_error(LOG_LEVEL_CONNECT, "select() on socket %d failed: %E", sfd);
1254       return FALSE;
1255    }
1256    no_data_waiting = !FD_ISSET(sfd, &readable_fds);
1257 #endif /* def HAVE_POLL */
1258
1259    return (no_data_waiting || (1 == recv(sfd, buf, 1, MSG_PEEK)));
1260 }
1261 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1262
1263
1264 /*
1265   Local Variables:
1266   tab-width: 3
1267   end:
1268 */