* locate_host.c: use strdoop() and phree() instead of strdup() and free()
[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;
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         i = strdoop(ch->h_name);
49         ch = gethostbyname(i);
50         phree(i);
51         if (ch == NULL)
52                 goto bad_dns;
53
54         /* check address for consistency */
55         for (; *ch->h_addr_list; ch->h_addr_list++)
56                 if (!memcmp(*ch->h_addr_list, addr,
57                             sizeof *addr)) {
58                         safestrncpy(tbuf, ch->h_name, 24);
59                         goto end;
60                 }
61         goto bad_dns;           /* they were spoofing. report a numeric IP
62                                    address. */
63
64       end:
65
66 #ifdef HAVE_NONREENTRANT_NETDB
67         end_critical_section(S_NETDB);
68 #endif
69
70         tbuf[24] = 0;
71 }