]> andersk Git - moira.git/blob - lib/fixhost.c
assume POSIX (uname vs gethostname)
[moira.git] / lib / fixhost.c
1 /*
2  *      $Source$
3  *      $Author$
4  *      $Header$
5  *
6  *      Copyright (C) 1987 by the Massachusetts Institute of Technology
7  *      For copying and distribution information, please see the file
8  *      <mit-copyright.h>.
9  */
10
11 #ifndef lint
12 static char *rcsid_fixhost_c = "$Header$";
13 #endif
14
15 #include <mit-copyright.h>
16 #include <sys/types.h>
17 #include <sys/socket.h>
18 #include <netinet/in.h>
19 #include <netdb.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <sys/utsname.h>
23 #include <string.h>
24 #include <ctype.h>
25 #include <moira.h>
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 *
39 canonicalize_hostname(host)
40     char *host;
41 {
42     register struct hostent *hp;
43     int n_len;
44     int has_dot = 0;
45     char tbuf[BUFSIZ];
46     struct utsname name;
47     register char *cp;
48     
49     if (strlen(host) > 2 && host[0] == '"' && host[strlen(host)-1] == '"') {
50         strcpy(tbuf, host+1);
51         free(host);
52         tbuf[strlen(tbuf)-1] = 0;
53         return(strsave(tbuf));
54     }
55
56     if (strchr(host, '*') || strchr(host, '?') || strchr(host, '['))
57       return(host);
58
59     hp = gethostbyname(host);
60
61     if (hp) {
62         n_len = strlen(hp->h_name) + 1;
63         host = realloc(host, (unsigned)n_len);
64         
65         (void) strcpy(host, hp->h_name);
66         return host;
67     } else {
68         /* can't get name from nameserver; fix up the format a bit */
69         for (cp = host; *cp; cp++) {
70             register int c;     /* pcc doesn't like register char */
71             if (islower(c = *cp)) *cp = toupper(c);
72             has_dot |= (c == '.');
73         }
74         if (!has_dot) {
75             static char *domain = NULL;
76
77             if (domain == NULL) {
78                 (void) uname(&name);
79                 hp = gethostbyname(name.nodename);
80                 cp = strchr(hp->h_name, '.');
81                 if (cp)
82                   domain = strsave(++cp);
83                 else
84                   domain = "";
85             }
86             (void) sprintf(tbuf, "%s.%s", host, domain);
87             free(host);
88             host = strsave(tbuf);
89         }
90         return host;
91     }
92 }
This page took 0.051247 seconds and 5 git commands to generate.