libexplain  1.4.D001
libexplain/gethostname_or_die.c
Go to the documentation of this file.
00001 /*
00002  * libexplain - Explain errno values returned by libc functions
00003  * Copyright (C) 2009, 2010, 2012, 2013 Peter Miller
00004  *
00005  * This program is free software; you can redistribute it and/or modify it
00006  * under the terms of the GNU Lesser General Public License as published by
00007  * the Free Software Foundation; either version 3 of the License, or (at
00008  * your option) any later version.
00009  *
00010  * This program is distributed in the hope that it will be useful,
00011  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00012  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013  * Lesser General Public License for more details.
00014  *
00015  * You should have received a copy of the GNU Lesser General Public License
00016  * along with this program. If not, see <http://www.gnu.org/licenses/>.
00017  */
00018 
00019 #include <libexplain/ac/errno.h>
00020 #include <libexplain/ac/unistd.h>
00021 
00022 #include <libexplain/gethostname.h>
00023 #include <libexplain/output.h>
00024 
00025 
00026 void
00027 explain_gethostname_or_die(char *data, size_t data_size)
00028 {
00029     if (explain_gethostname_on_error(data, data_size) < 0)
00030     {
00031         explain_output_exit_failure();
00032     }
00033 }
00034 
00035 
00036 int
00037 explain_gethostname_on_error(char *data, size_t data_size)
00038 {
00039     int             result;
00040 
00041 #ifdef HAVE_GETHOSTNAME
00042     result = gethostname(data, data_size);
00043     if (result >= 0 && data_size > 0)
00044     {
00045         /*
00046          * Use data_size-1 here rather than SIZE to work around the bug
00047          * in SunOS 5.5's gethostname whereby it NUL-terminates HOSTNAME
00048          * even when the name is as long as the supplied buffer.
00049          *
00050          * provenance: coreutils::xgethostname
00051          *
00052          * POSIX.1-2001 says that if such truncation occurs, then
00053          * it is unspecified whether the returned buffer includes a
00054          * terminating NUL byte.
00055          */
00056         data[data_size - 1] = '\0';
00057     }
00058 #else
00059     errno = ENOSYS;
00060     result = -1;
00061 #endif
00062     if (result < 0)
00063     {
00064         int             hold_errno;
00065 
00066         hold_errno = errno;
00067         explain_output_error("%s", explain_errno_gethostname(hold_errno,
00068             data, data_size));
00069         errno = hold_errno;
00070     }
00071     return result;
00072 }
00073 
00074 
00075 /* vim: set ts=8 sw=4 et : */