bb1162bb3f4b68a73363ceacfb6a5d15ff9697da
[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 #include "tools.h"
25
26 void locate_host(char *tbuf, const struct in_addr *addr)
27 {
28         struct hostent *ch;
29         char *i;
30         int a1, a2, a3, a4;
31
32 #ifdef HAVE_NONREENTRANT_NETDB
33         begin_critical_section(S_NETDB);
34 #endif
35
36         if ((ch = gethostbyaddr((char *) addr, sizeof(*addr), AF_INET)) ==
37             NULL) {
38               bad_dns:
39                 i = (char *) addr;
40                 a1 = ((*i++) & 0xff);
41                 a2 = ((*i++) & 0xff);
42                 a3 = ((*i++) & 0xff);
43                 a4 = ((*i++) & 0xff);
44                 sprintf(tbuf, "%d.%d.%d.%d", a1, a2, a3, a4);
45                 goto end;       /* because we might need to end the critical
46                                    section */
47         }
48         /* check if the forward DNS agrees; if not, they're spoofing */
49         i = strdoop(ch->h_name);
50         ch = gethostbyname(i);
51         phree(i);
52         if (ch == NULL)
53                 goto bad_dns;
54
55         /* check address for consistency */
56         for (; *ch->h_addr_list; ch->h_addr_list++)
57                 if (!memcmp(*ch->h_addr_list, addr,
58                             sizeof *addr)) {
59                         safestrncpy(tbuf, ch->h_name, 25);
60                         goto end;
61                 }
62         goto bad_dns;           /* they were spoofing. report a numeric IP
63                                    address. */
64
65       end:
66
67 #ifdef HAVE_NONREENTRANT_NETDB
68         end_critical_section(S_NETDB);
69 #endif
70
71         tbuf[25] = 0;
72 }