got it right this time... also, more general interface to locate_host
[citadel.git] / citadel / locate_host.c
1 /*
2  * locate the originating host
3  * $Id$
4  */
5
6 #include "sysdep.h"
7 #include <stdlib.h>
8 #include <unistd.h>
9 #include <stdio.h>
10 #include <signal.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <netinet/in.h>
14 #include <limits.h>
15 #include <netdb.h>
16 #include <string.h>
17 #ifdef HAVE_PTHREAD_H
18 #include <pthread.h>
19 #endif
20 #include "citadel.h"
21 #include "server.h"
22 #include "locate_host.h"
23 #include "config.h"
24
25 void locate_host(char *tbuf, const struct in_addr *addr)
26 {
27         struct hostent *ch, *ch2;
28         char *i;
29         int a1, a2, a3, a4;
30
31 #ifdef HAVE_NONREENTRANT_NETDB
32         begin_critical_section(S_NETDB);
33 #endif
34
35         if ((ch = gethostbyaddr((char *) addr, sizeof(*addr), AF_INET)) ==
36             NULL) {
37               bad_dns:
38                 i = (char *) addr;
39                 a1 = ((*i++) & 0xff);
40                 a2 = ((*i++) & 0xff);
41                 a3 = ((*i++) & 0xff);
42                 a4 = ((*i++) & 0xff);
43                 sprintf(tbuf, "%d.%d.%d.%d", a1, a2, a3, a4);
44                 goto end;       /* because we might need to end the critical
45                                    section */
46         }
47         /* check if the forward DNS agrees; if not, they're spoofing */
48         if ((ch2 = gethostbyname(ch->h_name)) == NULL)
49                 goto bad_dns;
50
51         /* check address for consistency */
52         for (; *ch2->h_addr_list; ch2->h_addr_list++)
53                 if (!memcmp(*ch2->h_addr_list, addr,
54                             sizeof *addr)) {
55                         strncpy(tbuf, ch->h_name, 24);
56                         goto end;
57                 }
58         goto bad_dns;           /* they were spoofing. report a numeric IP
59                                    address. */
60
61       end:
62
63 #ifdef HAVE_NONREENTRANT_NETDB
64         end_critical_section(S_NETDB);
65 #endif
66
67         tbuf[24] = 0;
68 }