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