* Changed the comments at the beginning of each file to a consistent format
[citadel.git] / citadel / locate_host.c
1 /*
2  * $Id$
3  *
4  * locate the originating host
5  *
6  */
7
8 #include "sysdep.h"
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdio.h>
12 #include <signal.h>
13 #include <sys/types.h>
14 #include <sys/socket.h>
15 #include <netinet/in.h>
16 #include <limits.h>
17 #include <netdb.h>
18 #include <string.h>
19 #include "citadel.h"
20 #include "server.h"
21 #include "locate_host.h"
22 #include "sysdep_decls.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         lprintf(9, "locate_host() called\n");
33
34 #ifdef HAVE_NONREENTRANT_NETDB
35         begin_critical_section(S_NETDB);
36 #endif
37
38         if ((ch = gethostbyaddr((char *) addr, sizeof(*addr), AF_INET)) ==
39             NULL) {
40               bad_dns:
41                 i = (char *) addr;
42                 a1 = ((*i++) & 0xff);
43                 a2 = ((*i++) & 0xff);
44                 a3 = ((*i++) & 0xff);
45                 a4 = ((*i++) & 0xff);
46                 sprintf(tbuf, "%d.%d.%d.%d", a1, a2, a3, a4);
47                 goto end;       /* because we might need to end the critical
48                                    section */
49         }
50         /* check if the forward DNS agrees; if not, they're spoofing */
51         i = strdoop(ch->h_name);
52         ch = gethostbyname(i);
53         phree(i);
54         if (ch == NULL)
55                 goto bad_dns;
56
57         /* check address for consistency */
58         for (; *ch->h_addr_list; ch->h_addr_list++)
59                 if (!memcmp(*ch->h_addr_list, addr,
60                             sizeof *addr)) {
61                         safestrncpy(tbuf, ch->h_name, 25);
62                         goto end;
63                 }
64         goto bad_dns;           /* they were spoofing. report a numeric IP
65                                    address. */
66
67       end:
68
69 #ifdef HAVE_NONREENTRANT_NETDB
70         end_critical_section(S_NETDB);
71 #endif
72
73         tbuf[25] = 0;
74         lprintf(9, "locate_host() exiting\n");
75 }