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