removed all references to sprintf from several files (not all files yet)
[citadel.git] / citadel / locate_host.c
1 /*
2  * $Id$
3  *
4  * locate the originating host
5  *
6  */
7
8 #ifdef DLL_EXPORT
9 #define IN_LIBCIT
10 #endif
11
12 #include "sysdep.h"
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <stdio.h>
16 #include <signal.h>
17 #include <sys/types.h>
18 #include <sys/socket.h>
19 #include <netinet/in.h>
20 #include <limits.h>
21 #include <netdb.h>
22 #include <string.h>
23 #include "citadel.h"
24 #include "server.h"
25 #include "dynloader.h"
26 #include "locate_host.h"
27 #include "sysdep_decls.h"
28 #include "config.h"
29 #include "tools.h"
30
31 void locate_host(char *tbuf, size_t n, const struct in_addr *addr)
32 {
33         struct hostent *ch;
34         char *i;
35         int a1, a2, a3, a4;
36
37         lprintf(9, "locate_host() called\n");
38
39 #ifdef HAVE_NONREENTRANT_NETDB
40         begin_critical_section(S_NETDB);
41 #endif
42
43         if ((ch = gethostbyaddr((char *) addr, sizeof(*addr), AF_INET)) ==
44             NULL) {
45               bad_dns:
46                 i = (char *) addr;
47                 a1 = ((*i++) & 0xff);
48                 a2 = ((*i++) & 0xff);
49                 a3 = ((*i++) & 0xff);
50                 a4 = ((*i++) & 0xff);
51                 snprintf(tbuf, n, "%d.%d.%d.%d", a1, a2, a3, a4);
52                 goto end;       /* because we might need to end the critical
53                                    section */
54         }
55         /* check if the forward DNS agrees; if not, they're spoofing */
56         i = strdoop(ch->h_name);
57         ch = gethostbyname(i);
58         phree(i);
59         if (ch == NULL)
60                 goto bad_dns;
61
62         /* check address for consistency */
63         for (; *ch->h_addr_list; ch->h_addr_list++)
64                 if (!memcmp(*ch->h_addr_list, addr,
65                             sizeof *addr)) {
66                         safestrncpy(tbuf, ch->h_name, 63);
67                         goto end;
68                 }
69         goto bad_dns;           /* they were spoofing. report a numeric IP
70                                    address. */
71
72       end:
73
74 #ifdef HAVE_NONREENTRANT_NETDB
75         end_critical_section(S_NETDB);
76 #endif
77
78         tbuf[63] = 0;
79         lprintf(9, "locate_host() exiting\n");
80 }