1 /*	$NetBSD: get_hostname.c,v 1.1.1.1 2009/06/23 10:09:00 tron Exp $	*/
2 
3 /*++
4 /* NAME
5 /*	get_hostname 3
6 /* SUMMARY
7 /*	network name lookup
8 /* SYNOPSIS
9 /*	#include <get_hostname.h>
10 /*
11 /*	const char *get_hostname()
12 /* DESCRIPTION
13 /*	get_hostname() returns the local hostname as obtained
14 /*	via gethostname() or its moral equivalent. This routine
15 /*	goes to great length to avoid dependencies on any network
16 /*	services.
17 /* DIAGNOSTICS
18 /*	Fatal errors: no hostname, invalid hostname.
19 /* SEE ALSO
20 /*	valid_hostname(3)
21 /* LICENSE
22 /* .ad
23 /* .fi
24 /*	The Secure Mailer license must be distributed with this software.
25 /* AUTHOR(S)
26 /*	Wietse Venema
27 /*	IBM T.J. Watson Research
28 /*	P.O. Box 704
29 /*	Yorktown Heights, NY 10598, USA
30 /*--*/
31 
32 /* System library. */
33 
34 #include <sys_defs.h>
35 #include <sys/param.h>
36 #include <string.h>
37 #include <unistd.h>
38 
39 #if (MAXHOSTNAMELEN < 256)
40 #undef MAXHOSTNAMELEN
41 #define MAXHOSTNAMELEN	256
42 #endif
43 
44 /* Utility library. */
45 
46 #include "mymalloc.h"
47 #include "msg.h"
48 #include "valid_hostname.h"
49 #include "get_hostname.h"
50 
51 /* Local stuff. */
52 
53 static char *my_host_name;
54 
55 /* get_hostname - look up my host name */
56 
get_hostname(void)57 const char *get_hostname(void)
58 {
59     char    namebuf[MAXHOSTNAMELEN + 1];
60 
61     /*
62      * The gethostname() call is not (or not yet) in ANSI or POSIX, but it is
63      * part of the socket interface library. We avoid the more politically-
64      * correct uname() routine because that has no portable way of dealing
65      * with long (FQDN) hostnames.
66      *
67      * DO NOT CALL GETHOSTBYNAME FROM THIS FUNCTION. IT BREAKS MAILDIR DELIVERY
68      * AND OTHER THINGS WHEN THE MACHINE NAME IS NOT FOUND IN /ETC/HOSTS OR
69      * CAUSES PROCESSES TO HANG WHEN THE NETWORK IS DISCONNECTED.
70      *
71      * POSTFIX NO LONGER NEEDS A FULLY QUALIFIED HOSTNAME. INSTEAD POSTFIX WILL
72      * USE A DEFAULT DOMAIN NAME "LOCALDOMAIN".
73      */
74     if (my_host_name == 0) {
75 	/* DO NOT CALL GETHOSTBYNAME FROM THIS FUNCTION */
76 	if (gethostname(namebuf, sizeof(namebuf)) < 0)
77 	    msg_fatal("gethostname: %m");
78 	namebuf[MAXHOSTNAMELEN] = 0;
79 	/* DO NOT CALL GETHOSTBYNAME FROM THIS FUNCTION */
80 	if (valid_hostname(namebuf, DO_GRIPE) == 0)
81 	    msg_fatal("unable to use my own hostname");
82 	/* DO NOT CALL GETHOSTBYNAME FROM THIS FUNCTION */
83 	my_host_name = mystrdup(namebuf);
84     }
85     return (my_host_name);
86 }
87