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