2004-08-01 Simon Josefsson <jas@extundo.com>
[gnulib.git] / lib / xgetdomainname.c
1 /* xgetdomainname.c -- Return the NIS domain name, without size limitations.
2    Copyright (C) 1992, 1996, 2000, 2001, 2003, 2004 Free Software Foundation,
3    Inc.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 /* Based on xgethostname.c, written by Jim Meyering.  */
20
21 #ifdef HAVE_CONFIG_H
22 # include <config.h>
23 #endif
24
25 /* Specification.  */
26 #include "xgetdomainname.h"
27
28 /* Get getdomainname.  */
29 #include "getdomainname.h"
30
31 /* Get errno.  */
32 #include <errno.h>
33
34 /* Get free.  */
35 #include <stdlib.h>
36
37 #include "xalloc.h"
38
39 #ifndef INITIAL_DOMAINNAME_LENGTH
40 # define INITIAL_DOMAINNAME_LENGTH 34
41 #endif
42
43 /* Return the NIS domain name of the machine, in malloc'd storage.
44    WARNING! The NIS domain name is unrelated to the fully qualified host name
45             of the machine.  It is also unrelated to email addresses.
46    WARNING! The NIS domain name is usually the empty string or "(none)" when
47             not using NIS.
48    If malloc fails, exit.
49    Upon any other failure, set errno and return NULL.  */
50 char *
51 xgetdomainname (void)
52 {
53   char *domainname;
54   size_t size;
55
56   size = INITIAL_DOMAINNAME_LENGTH;
57   domainname = xmalloc (size);
58   while (1)
59     {
60       int k = size - 1;
61       int err;
62
63       errno = 0;
64       domainname[k] = '\0';
65       err = getdomainname (domainname, size);
66       if (err >= 0 && domainname[k] == '\0')
67         break;
68       else if (err < 0 && errno != EINVAL)
69         {
70           int saved_errno = errno;
71           free (domainname);
72           errno = saved_errno;
73           return NULL;
74         }
75       size *= 2;
76       domainname = xrealloc (domainname, size);
77     }
78
79   return domainname;
80 }