verify: new macro 'assume'
[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, 2006, 2008-2013 Free
3    Software Foundation, 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 3 of the License, or
8    (at your option) 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, see <http://www.gnu.org/licenses/>.  */
17
18 /* Based on xgethostname.c, written by Jim Meyering.  */
19
20 #include <config.h>
21
22 /* Specification.  */
23 #include "xgetdomainname.h"
24
25 /* Get getdomainname.  */
26 #include <unistd.h>
27
28 /* Get errno.  */
29 #include <errno.h>
30
31 /* Get free.  */
32 #include <stdlib.h>
33
34 #include "xalloc.h"
35
36 #ifndef INITIAL_DOMAINNAME_LENGTH
37 # define INITIAL_DOMAINNAME_LENGTH 34
38 #endif
39
40 /* Return the NIS domain name of the machine, in malloc'd storage.
41    WARNING! The NIS domain name is unrelated to the fully qualified host name
42             of the machine.  It is also unrelated to email addresses.
43    WARNING! The NIS domain name is usually the empty string or "(none)" when
44             not using NIS.
45    If malloc fails, exit.
46    Upon any other failure, set errno and return NULL.  */
47 char *
48 xgetdomainname (void)
49 {
50   char *domainname;
51   size_t size;
52
53   size = INITIAL_DOMAINNAME_LENGTH;
54   domainname = xmalloc (size);
55   while (1)
56     {
57       int k = size - 1;
58       int err;
59
60       errno = 0;
61       domainname[k] = '\0';
62       err = getdomainname (domainname, size);
63       if (err >= 0 && domainname[k] == '\0')
64         break;
65       else if (err < 0 && errno != EINVAL)
66         {
67           int saved_errno = errno;
68           free (domainname);
69           errno = saved_errno;
70           return NULL;
71         }
72       size *= 2;
73       domainname = xrealloc (domainname, size);
74     }
75
76   return domainname;
77 }