havelib: Fix for Solaris 11 OpenIndiana and Solaris 11 OmniOS.
[gnulib.git] / lib / xgetdomainname.c
blobbaaab4c21bb22caed5fcf2fc8e226b0e5a979056
1 /* xgetdomainname.c -- Return the NIS domain name, without size limitations.
2 Copyright (C) 1992, 1996, 2000-2001, 2003-2004, 2006, 2008-2020 Free
3 Software Foundation, Inc.
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.
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.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 /* Based on xgethostname.c, written by Jim Meyering. */
20 #include <config.h>
22 /* Specification. */
23 #include "xgetdomainname.h"
25 /* Get getdomainname. */
26 #include <unistd.h>
28 /* Get errno. */
29 #include <errno.h>
31 /* Get strlen. */
32 #include <string.h>
34 /* Get free. */
35 #include <stdlib.h>
37 #include "xalloc.h"
39 #ifndef INITIAL_DOMAINNAME_LENGTH
40 # define INITIAL_DOMAINNAME_LENGTH 34
41 #endif
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)
53 char *domainname;
54 size_t size;
56 size = INITIAL_DOMAINNAME_LENGTH;
57 domainname = xmalloc (size);
58 while (1)
60 int k = size - 1;
61 int err;
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)
70 int saved_errno = errno;
71 free (domainname);
72 errno = saved_errno;
73 return NULL;
75 size *= 2;
76 domainname = xrealloc (domainname, size);
79 /* Shrink DOMAINNAME before returning it. */
81 size_t actual_size = strlen (domainname) + 1;
82 if (actual_size < size)
84 char *shrinked_domainname = realloc (domainname, actual_size);
85 if (shrinked_domainname != NULL)
86 domainname = shrinked_domainname;
90 return domainname;