Use PCRE syntax in host patterns when configured
[privoxy.git] / jbsockets.c
1 const char jbsockets_rcs[] = "$Id: jbsockets.c,v 1.46 2008/03/21 11:13:57 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-2007 the SourceForge
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  * Revisions   :
37  *    $Log: jbsockets.c,v $
38  *    Revision 1.46  2008/03/21 11:13:57  fabiankeil
39  *    Only gather host information if it's actually needed.
40  *    Also move the code out of accept_connection() so it's less likely
41  *    to delay other incoming connections if the host is misconfigured.
42  *
43  *    Revision 1.45  2007/09/30 16:59:22  fabiankeil
44  *    Set the maximum listen() backlog to 128. Apparently SOMAXCONN is
45  *    neither high enough, nor a hard limit on mingw32. Again for BR#1795281.
46  *
47  *    Revision 1.44  2007/09/15 13:01:31  fabiankeil
48  *    Increase listen() backlog to SOMAXCONN (or 128) to decrease
49  *    chances of dropped connections under load. Problem reported
50  *    and fix suggested by nobody in BR#1795281.
51  *
52  *    Revision 1.43  2007/06/01 18:16:36  fabiankeil
53  *    Use the same mutex for gethostbyname() and gethostbyaddr() to prevent
54  *    deadlocks and crashes on OpenBSD and possibly other OS with neither
55  *    gethostbyname_r() nor gethostaddr_r(). Closes BR#1729174.
56  *    Thanks to Ralf Horstmann for report and solution.
57  *
58  *    Revision 1.42  2007/04/01 17:37:07  fabiankeil
59  *    - Add DNS retries for Solaris and other systems
60  *      whose gethostbyname_r version takes five arguments.
61  *    - Move maximum number of DNS retries into a macro.
62  *
63  *    Revision 1.41  2006/11/13 19:05:51  fabiankeil
64  *    Make pthread mutex locking more generic. Instead of
65  *    checking for OSX and OpenBSD, check for FEATURE_PTHREAD
66  *    and use mutex locking unless there is an _r function
67  *    available. Better safe than sorry.
68  *
69  *    Fixes "./configure --disable-pthread" and should result
70  *    in less threading-related problems on pthread-using platforms,
71  *    but it still doesn't fix BR#1122404.
72  *
73  *    Revision 1.40  2006/09/02 15:36:42  fabiankeil
74  *    Follow the OpenBSD port's lead and protect the resolve
75  *    functions on OpenBSD as well.
76  *
77  *    Revision 1.39  2006/08/03 02:46:41  david__schmidt
78  *    Incorporate Fabian Keil's patch work:\rhttp://www.fabiankeil.de/sourcecode/privoxy/
79  *
80  *    Revision 1.38  2006/07/18 14:48:46  david__schmidt
81  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
82  *    with what was really the latest development (the v_3_0_branch branch)
83  *
84  *    Revision 1.35.2.8  2006/01/21 16:16:08  david__schmidt
85  *    Thanks to  Edward Carrel for his patch to modernize OSX's\rpthreads support.  See bug #1409623.
86  *
87  *    Revision 1.35.2.7  2005/05/07 21:50:55  david__schmidt
88  *    A few memory leaks plugged (mostly on error paths)
89  *
90  *    Revision 1.35.2.6  2003/12/17 16:34:40  oes
91  *    Cosmetics
92  *
93  *    Revision 1.35.2.5  2003/04/29 11:32:54  oes
94  *    Don't rely on h_addr being non-NULL after gethostbyname.
95  *    Works around an oddness in Max OSX and closes bug #724796
96  *
97  *    Revision 1.35.2.4  2003/04/04 12:40:20  oes
98  *    Made sure the errno set by bind, not close[socket] is used in
99  *    bind_port. Probably fixes bugs #713777, #705562.
100  *
101  *    Revision 1.35.2.3  2003/03/07 03:41:04  david__schmidt
102  *    Wrapping all *_r functions (the non-_r versions of them) with mutex semaphores for OSX.  Hopefully this will take care of all of those pesky crash reports.
103  *
104  *    Revision 1.35.2.2  2002/11/20 14:37:24  oes
105  *    Fixed Win32 error logging in bind_port.
106  *    Thanks to Oliver Stoeneberg for the hint.
107  *
108  *    Revision 1.35.2.1  2002/05/26 23:41:27  joergs
109  *    AmigaOS: Fixed wrong type of len in write_socket()
110  *
111  *    Revision 1.35  2002/04/26 15:50:04  joergs
112  *    AmigaOS: No socklen_t, added AMIGA to the systems using int instead.
113  *
114  *    Revision 1.34  2002/04/08 20:31:41  swa
115  *    fixed JB spelling
116  *
117  *    Revision 1.33  2002/04/03 16:02:18  gliptak
118  *    Correcting compile warning with older gcc
119  *
120  *    Revision 1.32  2002/03/31 17:18:59  jongfoster
121  *    Win32 only: Enabling STRICT to fix a VC++ compile warning.
122  *
123  *    Revision 1.31  2002/03/29 03:33:13  david__schmidt
124  *    Fix Mac OSX compiler warnings
125  *
126  *    Revision 1.30  2002/03/27 14:32:43  david__schmidt
127  *    More compiler warning message maintenance
128  *
129  *    Revision 1.29  2002/03/26 22:29:54  swa
130  *    we have a new homepage!
131  *
132  *    Revision 1.28  2002/03/24 13:25:43  swa
133  *    name change related issues
134  *
135  *    Revision 1.27  2002/03/13 00:27:05  jongfoster
136  *    Killing warnings
137  *
138  *    Revision 1.26  2002/03/11 22:07:02  david__schmidt
139  *    OS/2 port maintenance:
140  *    - Fixed EMX build - it had decayed a little
141  *    - Fixed inexplicable crash during FD_ZERO - must be due to a bad macro.
142  *      substituted a memset for now.
143  *
144  *    Revision 1.25  2002/03/09 20:03:52  jongfoster
145  *    - Making various functions return int rather than size_t.
146  *      (Undoing a recent change).  Since size_t is unsigned on
147  *      Windows, functions like read_socket that return -1 on
148  *      error cannot return a size_t.
149  *
150  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
151  *      crashes, and also frequently caused JB to jump to 100%
152  *      CPU and stay there.  (Because it thought it had just
153  *      read ((unsigned)-1) == 4Gb of data...)
154  *
155  *    - The signature of write_socket has changed, it now simply
156  *      returns success=0/failure=nonzero.
157  *
158  *    - Trying to get rid of a few warnings --with-debug on
159  *      Windows, I've introduced a new type "jb_socket".  This is
160  *      used for the socket file descriptors.  On Windows, this
161  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
162  *      an int.  The error value can't be -1 any more, so it's
163  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
164  *      Windows it maps to the #define INVALID_SOCKET.)
165  *
166  *    - The signature of bind_port has changed.
167  *
168  *    Revision 1.24  2002/03/07 03:51:36  oes
169  *     - Improved handling of failed DNS lookups
170  *     - Fixed compiler warnings etc
171  *
172  *    Revision 1.23  2002/03/05 00:36:01  jongfoster
173  *    Fixing bug 514988 - unable to restart Junkbuster
174  *
175  *    Revision 1.22  2002/03/04 02:08:02  david__schmidt
176  *    Enable web editing of actions file on OS/2 (it had been broken all this time!)
177  *
178  *    Revision 1.21  2002/01/09 14:32:33  oes
179  *    Added support for gethostbyname_r and gethostbyaddr_r.
180  *
181  *    Revision 1.20  2001/11/16 00:48:48  jongfoster
182  *    Enabling duplicate-socket detection for all platforms, not
183  *    just Win32.
184  *
185  *    Revision 1.19  2001/10/25 03:40:47  david__schmidt
186  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
187  *    threads to call select() simultaneously.  So, it's time to do a real, live,
188  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
189  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
190  *
191  *    Revision 1.18  2001/09/21 23:02:02  david__schmidt
192  *    Cleaning up 2 compiler warnings on OS/2.
193  *
194  *    Revision 1.17  2001/09/13 20:11:46  jongfoster
195  *    Fixing 2 compiler warnings under Win32
196  *
197  *    Revision 1.16  2001/07/30 22:08:36  jongfoster
198  *    Tidying up #defines:
199  *    - All feature #defines are now of the form FEATURE_xxx
200  *    - Permanently turned off WIN_GUI_EDIT
201  *    - Permanently turned on WEBDAV and SPLIT_PROXY_ARGS
202  *
203  *    Revision 1.15  2001/07/29 17:40:43  jongfoster
204  *    Fixed compiler warning by adding a cast
205  *
206  *    Revision 1.14  2001/07/18 13:47:59  oes
207  *    Eliminated dirty hack for getsockbyname()
208  *
209  *    Revision 1.13  2001/07/15 13:56:57  jongfoster
210  *    Removing unused local variable.
211  *
212  *    Revision 1.12  2001/07/01 17:04:11  oes
213  *    Bugfix: accept_connection no longer uses the obsolete hstrerror() function
214  *
215  *    Revision 1.11  2001/06/29 21:45:41  oes
216  *    Indentation, CRLF->LF, Tab-> Space
217  *
218  *    Revision 1.10  2001/06/29 13:29:15  oes
219  *    - Added remote (server) host IP to csp->http->host_ip_addr_str
220  *    - Added detection of local socket IP and fqdn
221  *    - Removed logentry from cancelled commit
222  *
223  *    Revision 1.9  2001/06/07 23:06:09  jongfoster
224  *    The host parameter to connect_to() is now const.
225  *
226  *    Revision 1.8  2001/06/03 19:12:07  oes
227  *    filled comment
228  *
229  *    Revision 1.7  2001/05/28 16:14:00  jongfoster
230  *    Fixing bug in LOG_LEVEL_LOG
231  *
232  *    Revision 1.6  2001/05/26 17:28:32  jongfoster
233  *    Fixed LOG_LEVEL_LOG
234  *
235  *    Revision 1.5  2001/05/26 15:26:15  jongfoster
236  *    ACL feature now provides more security by immediately dropping
237  *    connections from untrusted hosts.
238  *
239  *    Revision 1.4  2001/05/26 00:37:42  jongfoster
240  *    Cosmetic indentation correction.
241  *
242  *    Revision 1.3  2001/05/25 21:57:54  jongfoster
243  *    Now gives a warning under Windows if you try to bind
244  *    it to a port that's already in use.
245  *
246  *    Revision 1.2  2001/05/17 23:01:01  oes
247  *     - Cleaned CRLF's from the sources and related files
248  *
249  *    Revision 1.1.1.1  2001/05/15 13:58:54  oes
250  *    Initial import of version 2.9.3 source tree
251  *
252  *
253  *********************************************************************/
254 \f
255
256 #include "config.h"
257
258 #include <stdlib.h>
259 #include <stdio.h>
260 #include <string.h>
261 #include <errno.h>
262 #include <fcntl.h>
263 #include <sys/types.h>
264
265 #ifdef _WIN32
266
267 #ifndef STRICT
268 #define STRICT
269 #endif
270 #include <windows.h>
271 #include <sys/timeb.h>
272 #include <io.h>
273
274 #else
275
276 #ifndef __OS2__
277 #include <unistd.h>
278 #endif
279 #include <sys/time.h>
280 #include <netinet/in.h>
281 #include <sys/ioctl.h>
282 #include <netdb.h>
283 #include <sys/socket.h>
284
285 #ifndef __BEOS__
286 #include <netinet/tcp.h>
287 #ifndef __OS2__
288 #include <arpa/inet.h>
289 #endif
290 #else
291 #include <socket.h>
292 #endif
293
294 #if defined(__EMX__) || defined (__OS2__)
295 #include <sys/select.h>  /* OS/2/EMX needs a little help with select */
296 #ifdef __OS2__
297 #include <nerrno.h>
298 #endif
299 #endif
300
301 #endif
302
303 #include "project.h"
304
305 #ifdef FEATURE_PTHREAD
306 #include "jcc.h"
307 /* jcc.h is for mutex semaphores only */
308 #endif /* def FEATURE_PTHREAD */
309
310 #include "jbsockets.h"
311 #include "filters.h"
312 #include "errlog.h"
313
314 const char jbsockets_h_rcs[] = JBSOCKETS_H_VERSION;
315
316 /*
317  * Maximum number of gethostbyname(_r) retries in case of
318  * soft errors (TRY_AGAIN).
319  * XXX: Does it make sense to make this a config option?
320  */
321 #define MAX_DNS_RETRIES 10
322
323 #define MAX_LISTEN_BACKLOG 128
324
325
326 /*********************************************************************
327  *
328  * Function    :  connect_to
329  *
330  * Description :  Open a socket and connect to it.  Will check
331  *                that this is allowed according to ACL.
332  *
333  * Parameters  :
334  *          1  :  host = hostname to connect to
335  *          2  :  portnum = port to connent on
336  *          3  :  csp = Current client state (buffers, headers, etc...)
337  *                      Not modified, only used for source IP and ACL.
338  *
339  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket
340  *                file descriptor.
341  *
342  *********************************************************************/
343 jb_socket connect_to(const char *host, int portnum, struct client_state *csp)
344 {
345    struct sockaddr_in inaddr;
346    jb_socket fd;
347    int addr;
348    fd_set wfds;
349    struct timeval tv[1];
350 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA)
351    int   flags;
352 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
353
354 #ifdef FEATURE_ACL
355    struct access_control_addr dst[1];
356 #endif /* def FEATURE_ACL */
357
358    memset((char *)&inaddr, 0, sizeof inaddr);
359
360    if ((addr = resolve_hostname_to_ip(host)) == INADDR_NONE)
361    {
362       csp->http->host_ip_addr_str = strdup("unknown");
363       return(JB_INVALID_SOCKET);
364    }
365
366 #ifdef FEATURE_ACL
367    dst->addr = ntohl((unsigned long) addr);
368    dst->port = portnum;
369
370    if (block_acl(dst, csp))
371    {
372 #ifdef __OS2__
373       errno = SOCEPERM;
374 #else
375       errno = EPERM;
376 #endif
377       return(JB_INVALID_SOCKET);
378    }
379 #endif /* def FEATURE_ACL */
380
381    inaddr.sin_addr.s_addr = addr;
382    inaddr.sin_family      = AF_INET;
383    csp->http->host_ip_addr_str = strdup(inet_ntoa(inaddr.sin_addr));
384
385 #ifndef _WIN32
386    if (sizeof(inaddr.sin_port) == sizeof(short))
387 #endif /* ndef _WIN32 */
388    {
389       inaddr.sin_port = htons((unsigned short) portnum);
390    }
391 #ifndef _WIN32
392    else
393    {
394       inaddr.sin_port = htonl((unsigned long)portnum);
395    }
396 #endif /* ndef _WIN32 */
397
398 #ifdef _WIN32
399    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) == JB_INVALID_SOCKET)
400 #else
401    if ((fd = socket(inaddr.sin_family, SOCK_STREAM, 0)) < 0)
402 #endif
403    {
404       return(JB_INVALID_SOCKET);
405    }
406
407 #ifdef TCP_NODELAY
408    {  /* turn off TCP coalescence */
409       int mi = 1;
410       setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *) &mi, sizeof (int));
411    }
412 #endif /* def TCP_NODELAY */
413
414 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
415    if ((flags = fcntl(fd, F_GETFL, 0)) != -1)
416    {
417       flags |= O_NDELAY;
418       fcntl(fd, F_SETFL, flags);
419    }
420 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
421
422    while (connect(fd, (struct sockaddr *) & inaddr, sizeof inaddr) == JB_INVALID_SOCKET)
423    {
424 #ifdef _WIN32
425       if (errno == WSAEINPROGRESS)
426 #elif __OS2__ 
427       if (sock_errno() == EINPROGRESS)
428 #else /* ifndef _WIN32 */
429       if (errno == EINPROGRESS)
430 #endif /* ndef _WIN32 || __OS2__ */
431       {
432          break;
433       }
434
435 #ifdef __OS2__ 
436       if (sock_errno() != EINTR)
437 #else
438       if (errno != EINTR)
439 #endif /* __OS2__ */
440       {
441          close_socket(fd);
442          return(JB_INVALID_SOCKET);
443       }
444    }
445
446 #if !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
447    if (flags != -1)
448    {
449       flags &= ~O_NDELAY;
450       fcntl(fd, F_SETFL, flags);
451    }
452 #endif /* !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__) */
453
454    /* wait for connection to complete */
455    FD_ZERO(&wfds);
456    FD_SET(fd, &wfds);
457
458    tv->tv_sec  = 30;
459    tv->tv_usec = 0;
460
461    /* MS Windows uses int, not SOCKET, for the 1st arg of select(). Wierd! */
462    if (select((int)fd + 1, NULL, &wfds, NULL, tv) <= 0)
463    {
464       close_socket(fd);
465       return(JB_INVALID_SOCKET);
466    }
467    return(fd);
468
469 }
470
471
472 /*********************************************************************
473  *
474  * Function    :  write_socket
475  *
476  * Description :  Write the contents of buf (for n bytes) to socket fd.
477  *
478  * Parameters  :
479  *          1  :  fd = file descriptor (aka. handle) of socket to write to.
480  *          2  :  buf = pointer to data to be written.
481  *          3  :  len = length of data to be written to the socket "fd".
482  *
483  * Returns     :  0 on success (entire buffer sent).
484  *                nonzero on error.
485  *
486  *********************************************************************/
487 #ifdef AMIGA
488 int write_socket(jb_socket fd, const char *buf, ssize_t len)
489 #else
490 int write_socket(jb_socket fd, const char *buf, size_t len)
491 #endif
492 {
493    if (len == 0)
494    {
495       return 0;
496    }
497
498    if (len < 0) /* constant condition - size_t isn't ever negative */ 
499    {
500       return 1;
501    }
502
503    log_error(LOG_LEVEL_LOG, "%N", len, buf);
504
505 #if defined(_WIN32)
506    return (send(fd, buf, (int)len, 0) != (int)len);
507 #elif defined(__BEOS__) || defined(AMIGA)
508    return (send(fd, buf, len, 0) != len);
509 #elif defined(__OS2__)
510    /*
511     * Break the data up into SOCKET_SEND_MAX chunks for sending...
512     * OS/2 seemed to complain when the chunks were too large.
513     */
514 #define SOCKET_SEND_MAX 65000
515    {
516       int write_len = 0, send_len, send_rc = 0, i = 0;
517       while ((i < len) && (send_rc != -1))
518       {
519          if ((i + SOCKET_SEND_MAX) > len)
520             send_len = len - i;
521          else
522             send_len = SOCKET_SEND_MAX;
523          send_rc = send(fd,(char*)buf + i, send_len, 0);
524          if (send_rc == -1)
525             return 1;
526          i = i + send_len;
527       }
528       return 0;
529    }
530 #else
531    return (write(fd, buf, len) != len);
532 #endif
533
534 }
535
536
537 /*********************************************************************
538  *
539  * Function    :  read_socket
540  *
541  * Description :  Read from a TCP/IP socket in a platform independent way.
542  *
543  * Parameters  :
544  *          1  :  fd = file descriptor of the socket to read
545  *          2  :  buf = pointer to buffer where data will be written
546  *                Must be >= len bytes long.
547  *          3  :  len = maximum number of bytes to read
548  *
549  * Returns     :  On success, the number of bytes read is returned (zero
550  *                indicates end of file), and the file position is advanced
551  *                by this number.  It is not an error if this number is
552  *                smaller than the number of bytes requested; this may hap-
553  *                pen for example because fewer bytes are actually available
554  *                right now (maybe because we were close to end-of-file, or
555  *                because we are reading from a pipe, or from a terminal,
556  *                or because read() was interrupted by a signal).  On error,
557  *                -1 is returned, and errno is set appropriately.  In this
558  *                case it is left unspecified whether the file position (if
559  *                any) changes.
560  *
561  *********************************************************************/
562 int read_socket(jb_socket fd, char *buf, int len)
563 {
564    if (len <= 0)
565    {
566       return(0);
567    }
568
569 #if defined(_WIN32)
570    return(recv(fd, buf, len, 0));
571 #elif defined(__BEOS__) || defined(AMIGA) || defined(__OS2__)
572    return(recv(fd, buf, (size_t)len, 0));
573 #else
574    return(read(fd, buf, (size_t)len));
575 #endif
576 }
577
578
579 /*********************************************************************
580  *
581  * Function    :  close_socket
582  *
583  * Description :  Closes a TCP/IP socket
584  *
585  * Parameters  :
586  *          1  :  fd = file descriptor of socket to be closed
587  *
588  * Returns     :  void
589  *
590  *********************************************************************/
591 void close_socket(jb_socket fd)
592 {
593 #if defined(_WIN32) || defined(__BEOS__)
594    closesocket(fd);
595 #elif defined(AMIGA)
596    CloseSocket(fd); 
597 #elif defined(__OS2__)
598    soclose(fd);
599 #else
600    close(fd);
601 #endif
602
603 }
604
605
606 /*********************************************************************
607  *
608  * Function    :  bind_port
609  *
610  * Description :  Call socket, set socket options, and listen.
611  *                Called by listen_loop to "boot up" our proxy address.
612  *
613  * Parameters  :
614  *          1  :  hostnam = TCP/IP address to bind/listen to
615  *          2  :  portnum = port to listen on
616  *          3  :  pfd = pointer used to return file descriptor.
617  *
618  * Returns     :  if success, returns 0 and sets *pfd.
619  *                if failure, returns -3 if address is in use,
620  *                                    -2 if address unresolvable,
621  *                                    -1 otherwise
622  *********************************************************************/
623 int bind_port(const char *hostnam, int portnum, jb_socket *pfd)
624 {
625    struct sockaddr_in inaddr;
626    jb_socket fd;
627 #ifndef _WIN32
628    int one = 1;
629 #endif /* ndef _WIN32 */
630
631    *pfd = JB_INVALID_SOCKET;
632
633    memset((char *)&inaddr, '\0', sizeof inaddr);
634
635    inaddr.sin_family      = AF_INET;
636    inaddr.sin_addr.s_addr = resolve_hostname_to_ip(hostnam);
637
638    if (inaddr.sin_addr.s_addr == INADDR_NONE)
639    {
640       return(-2);
641    }
642
643 #ifndef _WIN32
644    if (sizeof(inaddr.sin_port) == sizeof(short))
645 #endif /* ndef _WIN32 */
646    {
647       inaddr.sin_port = htons((unsigned short) portnum);
648    }
649 #ifndef _WIN32
650    else
651    {
652       inaddr.sin_port = htonl((unsigned long) portnum);
653    }
654 #endif /* ndef _WIN32 */
655
656    fd = socket(AF_INET, SOCK_STREAM, 0);
657
658 #ifdef _WIN32
659    if (fd == JB_INVALID_SOCKET)
660 #else
661    if (fd < 0)
662 #endif
663    {
664       return(-1);
665    }
666
667 #ifndef _WIN32
668    /*
669     * This is not needed for Win32 - in fact, it stops
670     * duplicate instances of Privoxy from being caught.
671     *
672     * On UNIX, we assume the user is sensible enough not
673     * to start Privoxy multiple times on the same IP.
674     * Without this, stopping and restarting Privoxy
675     * from a script fails.
676     * Note: SO_REUSEADDR is meant to only take over
677     * sockets which are *not* in listen state in Linux,
678     * e.g. sockets in TIME_WAIT. YMMV.
679     */
680    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof(one));
681 #endif /* ndef _WIN32 */
682
683    if (bind(fd, (struct sockaddr *)&inaddr, sizeof(inaddr)) < 0)
684    {
685 #ifdef _WIN32
686       errno = WSAGetLastError();
687       if (errno == WSAEADDRINUSE)
688 #else
689       if (errno == EADDRINUSE)
690 #endif
691       {
692          close_socket(fd);
693          return(-3);
694       }
695       else
696       {
697          close_socket(fd);
698          return(-1);
699       }
700    }
701
702    while (listen(fd, MAX_LISTEN_BACKLOG) == -1)
703    {
704       if (errno != EINTR)
705       {
706          return(-1);
707       }
708    }
709
710    *pfd = fd;
711    return 0;
712
713 }
714
715
716 /*********************************************************************
717  *
718  * Function    :  get_host_information
719  *
720  * Description :  Determines the IP address the client used to
721  *                reach us and the hostname associated with it.
722  *
723  *                XXX: Most of the code has been copy and pasted
724  *                from accept_connection() and not all of the
725  *                ifdefs paths have been tested afterwards.
726  *
727  * Parameters  :
728  *          1  :  afd = File descriptor returned from accept().
729  *          2  :  ip_address = Pointer to return the pointer to
730  *                             the ip address string.
731  *          3  :  hostname =   Pointer to return the pointer to
732  *                             the hostname or NULL if the caller
733  *                             isn't interested in it.
734  *
735  * Returns     :  void.
736  *
737  *********************************************************************/
738 void get_host_information(jb_socket afd, char **ip_address, char **hostname)
739 {
740    struct sockaddr_in server;
741    struct hostent *host = NULL;
742 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
743    /* according to accept_connection() this fixes a warning. */
744    int s_length;
745 #else
746    socklen_t s_length;
747 #endif
748 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS) ||  defined(HAVE_GETHOSTBYADDR_R_7_ARGS) || defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
749    struct hostent result;
750 #if defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
751    struct hostent_data hdata;
752 #else
753    char hbuf[HOSTENT_BUFFER_SIZE];
754    int thd_err;
755 #endif /* def HAVE_GETHOSTBYADDR_R_5_ARGS */
756 #endif /* def HAVE_GETHOSTBYADDR_R_(8|7|5)_ARGS */
757    s_length = sizeof(server);
758
759    if (NULL != hostname)
760    {
761       *hostname = NULL;
762    }
763    *ip_address = NULL;
764
765    if (!getsockname(afd, (struct sockaddr *) &server, &s_length))
766    {
767       *ip_address = strdup(inet_ntoa(server.sin_addr));
768
769       if (NULL == hostname)
770       {
771          /*
772           * We're done here, the caller isn't
773           * interested in knowing the hostname.
774           */
775          return;
776       }
777 #if defined(HAVE_GETHOSTBYADDR_R_8_ARGS)
778       gethostbyaddr_r((const char *)&server.sin_addr,
779                       sizeof(server.sin_addr), AF_INET,
780                       &result, hbuf, HOSTENT_BUFFER_SIZE,
781                       &host, &thd_err);
782 #elif defined(HAVE_GETHOSTBYADDR_R_7_ARGS)
783       host = gethostbyaddr_r((const char *)&server.sin_addr,
784                       sizeof(server.sin_addr), AF_INET,
785                       &result, hbuf, HOSTENT_BUFFER_SIZE, &thd_err);
786 #elif defined(HAVE_GETHOSTBYADDR_R_5_ARGS)
787       if (0 == gethostbyaddr_r((const char *)&server.sin_addr,
788                                sizeof(server.sin_addr), AF_INET,
789                                &result, &hdata))
790       {
791          host = &result;
792       }
793       else
794       {
795          host = NULL;
796       }
797 #elif FEATURE_PTHREAD
798       pthread_mutex_lock(&resolver_mutex);
799       host = gethostbyaddr((const char *)&server.sin_addr, 
800                            sizeof(server.sin_addr), AF_INET);
801       pthread_mutex_unlock(&resolver_mutex);
802 #else
803       host = gethostbyaddr((const char *)&server.sin_addr, 
804                            sizeof(server.sin_addr), AF_INET);
805 #endif
806       if (host == NULL)
807       {
808          log_error(LOG_LEVEL_ERROR, "Unable to get my own hostname: %E\n");
809       }
810       else
811       {
812          *hostname = strdup(host->h_name);
813       }
814    }
815
816    return;
817 }
818
819
820 /*********************************************************************
821  *
822  * Function    :  accept_connection
823  *
824  * Description :  Accepts a connection on a socket.  Socket must have
825  *                been created using bind_port().
826  *
827  * Parameters  :
828  *          1  :  csp = Client state, cfd, ip_addr_str, and 
829  *                ip_addr_long will be set by this routine.
830  *          2  :  fd  = file descriptor returned from bind_port
831  *
832  * Returns     :  when a connection is accepted, it returns 1 (TRUE).
833  *                On an error it returns 0 (FALSE).
834  *
835  *********************************************************************/
836 int accept_connection(struct client_state * csp, jb_socket fd)
837 {
838    struct sockaddr_in client;
839    jb_socket afd;
840 #if defined(_WIN32) || defined(__OS2__) || defined(__APPLE_CC__) || defined(AMIGA)
841    /* Wierdness - fix a warning. */
842    int c_length;
843 #else
844    socklen_t c_length;
845 #endif
846
847    c_length = sizeof(client);
848
849 #ifdef _WIN32
850    afd = accept (fd, (struct sockaddr *) &client, &c_length);
851    if (afd == JB_INVALID_SOCKET)
852    {
853       return 0;
854    }
855 #else
856    do
857    {
858       afd = accept (fd, (struct sockaddr *) &client, &c_length);
859    } while (afd < 1 && errno == EINTR);
860    if (afd < 0)
861    {
862       return 0;
863    }
864 #endif
865
866    csp->cfd = afd;
867    csp->ip_addr_str  = strdup(inet_ntoa(client.sin_addr));
868    csp->ip_addr_long = ntohl(client.sin_addr.s_addr);
869
870    return 1;
871
872 }
873
874
875 /*********************************************************************
876  *
877  * Function    :  resolve_hostname_to_ip
878  *
879  * Description :  Resolve a hostname to an internet tcp/ip address.
880  *                NULL or an empty string resolve to INADDR_ANY.
881  *
882  * Parameters  :
883  *          1  :  host = hostname to resolve
884  *
885  * Returns     :  INADDR_NONE => failure, INADDR_ANY or tcp/ip address if succesful.
886  *
887  *********************************************************************/
888 unsigned long resolve_hostname_to_ip(const char *host)
889 {
890    struct sockaddr_in inaddr;
891    struct hostent *hostp;
892    unsigned int dns_retries = 0;
893 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS) || defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
894    struct hostent result;
895 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS) || defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
896    char hbuf[HOSTENT_BUFFER_SIZE];
897    int thd_err;
898 #else /* defined(HAVE_GETHOSTBYNAME_R_3_ARGS) */
899    struct hostent_data hdata;
900 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5)_ARGS */
901 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
902
903    if ((host == NULL) || (*host == '\0'))
904    {
905       return(INADDR_ANY);
906    }
907
908    memset((char *) &inaddr, 0, sizeof inaddr);
909
910    if ((inaddr.sin_addr.s_addr = inet_addr(host)) == -1)
911    {
912 #if defined(HAVE_GETHOSTBYNAME_R_6_ARGS)
913       while (gethostbyname_r(host, &result, hbuf,
914                 HOSTENT_BUFFER_SIZE, &hostp, &thd_err)
915              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
916       {   
917          log_error(LOG_LEVEL_ERROR,
918             "Timeout #%u while trying to resolve %s. Trying again.",
919             dns_retries, host);
920       }
921 #elif defined(HAVE_GETHOSTBYNAME_R_5_ARGS)
922       while (NULL == (hostp = gethostbyname_r(host, &result,
923                                  hbuf, HOSTENT_BUFFER_SIZE, &thd_err))
924              && (thd_err == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
925       {   
926          log_error(LOG_LEVEL_ERROR,
927             "Timeout #%u while trying to resolve %s. Trying again.",
928             dns_retries, host);
929       }
930 #elif defined(HAVE_GETHOSTBYNAME_R_3_ARGS)
931       /*
932        * XXX: Doesn't retry in case of soft errors.
933        * Does this gethostbyname_r version set h_errno?
934        */
935       if (0 == gethostbyname_r(host, &result, &hdata))
936       {
937          hostp = &result;
938       }
939       else
940       {
941          hostp = NULL;
942       }
943 #elif FEATURE_PTHREAD
944       pthread_mutex_lock(&resolver_mutex);
945       while (NULL == (hostp = gethostbyname(host))
946              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
947       {   
948          log_error(LOG_LEVEL_ERROR,
949             "Timeout #%u while trying to resolve %s. Trying again.",
950             dns_retries, host);
951       }
952       pthread_mutex_unlock(&resolver_mutex);
953 #else
954       while (NULL == (hostp = gethostbyname(host))
955              && (h_errno == TRY_AGAIN) && (dns_retries++ < MAX_DNS_RETRIES))
956       {
957          log_error(LOG_LEVEL_ERROR,
958             "Timeout #%u while trying to resolve %s. Trying again.",
959             dns_retries, host);
960       }
961 #endif /* def HAVE_GETHOSTBYNAME_R_(6|5|3)_ARGS */
962       /*
963        * On Mac OSX, if a domain exists but doesn't have a type A
964        * record associated with it, the h_addr member of the struct
965        * hostent returned by gethostbyname is NULL, even if h_length
966        * is 4. Therefore the second test below.
967        */
968       if (hostp == NULL || hostp->h_addr == NULL)
969       {
970          errno = EINVAL;
971          log_error(LOG_LEVEL_ERROR, "could not resolve hostname %s", host);
972          return(INADDR_NONE);
973       }
974       if (hostp->h_addrtype != AF_INET)
975       {
976 #ifdef _WIN32
977          errno = WSAEPROTOTYPE;
978 #else
979          errno = EPROTOTYPE;
980 #endif 
981          log_error(LOG_LEVEL_ERROR, "hostname %s resolves to unknown address type.", host);
982          return(INADDR_NONE);
983       }
984       memcpy(
985          (char *) &inaddr.sin_addr,
986          (char *) hostp->h_addr,
987          sizeof(inaddr.sin_addr)
988       );
989    }
990    return(inaddr.sin_addr.s_addr);
991
992 }
993
994
995 /*
996   Local Variables:
997   tab-width: 3
998   end:
999 */