f35cb39ed6
First of all, let's rename it to read_etc_hostname(), to make clearer what kind of configuration it actually reads: the file format defined in /etc/hostname and nothing else. Secondly: let's port this to use read_line(), i.e. the new way to read lines from a file in a safe, bounded way. Thirdly: let's strip leading/trailing whitespace from what we are reading. Given that we are already pretty lenient what we read (comments and empty lines), let's be permissive regarding whitespace too. Fourthly: let's actually validate the hostname when reading it. So far we tried to make it valid, but that's not always possible (for example, we can't make an empty hostname valid, ever).
70 lines
2 KiB
C
70 lines
2 KiB
C
/* SPDX-License-Identifier: LGPL-2.1+ */
|
|
/***
|
|
This file is part of systemd.
|
|
|
|
Copyright 2010 Lennart Poettering
|
|
|
|
systemd is free software; you can redistribute it and/or modify it
|
|
under the terms of the GNU Lesser General Public License as published by
|
|
the Free Software Foundation; either version 2.1 of the License, or
|
|
(at your option) any later version.
|
|
|
|
systemd is distributed in the hope that it will be useful, but
|
|
WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
|
Lesser General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Lesser General Public License
|
|
along with systemd; If not, see <http://www.gnu.org/licenses/>.
|
|
***/
|
|
|
|
#include <errno.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
#include "alloc-util.h"
|
|
#include "fileio.h"
|
|
#include "hostname-setup.h"
|
|
#include "hostname-util.h"
|
|
#include "log.h"
|
|
#include "macro.h"
|
|
#include "string-util.h"
|
|
#include "util.h"
|
|
|
|
int hostname_setup(void) {
|
|
_cleanup_free_ char *b = NULL;
|
|
bool enoent = false;
|
|
const char *hn;
|
|
int r;
|
|
|
|
r = read_etc_hostname(NULL, &b);
|
|
if (r < 0) {
|
|
if (r == -ENOENT)
|
|
enoent = true;
|
|
else
|
|
log_warning_errno(r, "Failed to read configured hostname: %m");
|
|
|
|
hn = NULL;
|
|
} else
|
|
hn = b;
|
|
|
|
if (isempty(hn)) {
|
|
/* Don't override the hostname if it is already set
|
|
* and not explicitly configured */
|
|
if (hostname_is_set())
|
|
return 0;
|
|
|
|
if (enoent)
|
|
log_info("No hostname configured.");
|
|
|
|
hn = FALLBACK_HOSTNAME;
|
|
}
|
|
|
|
r = sethostname_idempotent(hn);
|
|
if (r < 0)
|
|
return log_warning_errno(r, "Failed to set hostname to <%s>: %m", hn);
|
|
|
|
log_info("Set hostname to <%s>.", hn);
|
|
return 0;
|
|
}
|