]> andersk Git - moira.git/blob - lib/fixhost.c
c0c39ddf32324f269bd523179b959a7847b3a958
[moira.git] / lib / fixhost.c
1 /* $Id$
2  *
3  * Canonicalize a hostname
4  *
5  * Copyright (C) 1987-1998 by the Massachusetts Institute of Technology
6  * For copying and distribution information, please see the file
7  * <mit-copyright.h>.
8  */
9
10 #include <mit-copyright.h>
11 #include <moira.h>
12
13 #include <sys/types.h>
14 #include <sys/socket.h>
15 #include <sys/utsname.h>
16
17 #include <netdb.h>
18 #include <netinet/in.h>
19
20 #include <ctype.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24
25 RCSID("$Header$");
26
27 /*
28  * Canonicalize hostname:
29  *  if it is in double-quotes, then strip the quotes and return the name.
30  *  if it is in the namespace, call the nameserver to expand it
31  *  otherwise uppercase it and append the default domain (using an, er,
32  *    undocumented global of the nameserver).
33  *
34  * Assumes that host was allocated using malloc(); it may be freed or
35  * realloc'ed, so the old pointer should not be considered valid.
36  */
37
38 char *canonicalize_hostname(char *host)
39 {
40   struct hostent *hp;
41   int n_len;
42   int has_dot = 0;
43   char tbuf[BUFSIZ];
44   struct utsname name;
45   char *cp;
46
47   if (strlen(host) > 2 && host[0] == '"' && host[strlen(host) - 1] == '"')
48     {
49       strcpy(tbuf, host + 1);
50       free(host);
51       tbuf[strlen(tbuf) - 1] = '\0';
52       return strdup(tbuf);
53     }
54
55   if (strchr(host, '*') || strchr(host, '?') || strchr(host, '['))
56     return host;
57
58   hp = gethostbyname(host);
59
60   if (hp)
61     {
62       n_len = strlen(hp->h_name) + 1;
63       host = realloc(host, n_len);
64
65       strcpy(host, hp->h_name);
66       return host;
67     }
68   else
69     {
70       /* can't get name from nameserver; fix up the format a bit */
71       for (cp = host; *cp; cp++)
72         {
73           int c;
74           if (islower(c = *cp))
75             *cp = toupper(c);
76           has_dot |= (c == '.');
77         }
78       if (!has_dot)
79         {
80           static char *domain = NULL;
81
82           if (domain == NULL)
83             {
84               uname(&name);
85               hp = gethostbyname(name.nodename);
86               cp = strchr(hp->h_name, '.');
87               if (cp)
88                 domain = strdup(++cp);
89               else
90                 domain = "";
91             }
92           sprintf(tbuf, "%s.%s", host, domain);
93           free(host);
94           host = strdup(tbuf);
95         }
96       return host;
97     }
98 }
This page took 0.029625 seconds and 3 git commands to generate.