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