2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
28 #include <sys/types.h>
31 #include "alloc-util.h"
37 #include "hexdecoct.h"
41 #include "parse-util.h"
42 #include "path-util.h"
43 #include "process-util.h"
44 #include "random-util.h"
45 #include "stdio-util.h"
46 #include "string-util.h"
48 //#include "time-util.h"
49 #include "umask-util.h"
52 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
54 int write_string_stream_ts(FILE *f, const char *line, bool enforce_newline, struct timespec *ts) {
60 if (enforce_newline && !endswith(line, "\n"))
64 struct timespec twice[2] = {*ts, *ts};
66 if (futimens(fileno(f), twice) < 0)
70 return fflush_and_check(f);
73 static int write_string_file_atomic(const char *fn, const char *line, bool enforce_newline, bool sync) {
74 _cleanup_fclose_ FILE *f = NULL;
75 _cleanup_free_ char *p = NULL;
81 r = fopen_temporary(fn, &f, &p);
85 (void) fchmod_umask(fileno(f), 0644);
87 r = write_string_stream(f, line, enforce_newline);
89 r = fflush_sync_and_check(f);
92 if (rename(p, fn) < 0)
102 int write_string_file_ts(const char *fn, const char *line, WriteStringFileFlags flags, struct timespec *ts) {
103 _cleanup_fclose_ FILE *f = NULL;
109 /* We don't know how to verify whether the file contents is on-disk. */
110 assert(!((flags & WRITE_STRING_FILE_SYNC) && (flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE)));
112 if (flags & WRITE_STRING_FILE_ATOMIC) {
113 assert(flags & WRITE_STRING_FILE_CREATE);
115 r = write_string_file_atomic(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE),
116 flags & WRITE_STRING_FILE_SYNC);
124 if (flags & WRITE_STRING_FILE_CREATE) {
133 /* We manually build our own version of fopen(..., "we") that
134 * works without O_CREAT */
135 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY);
141 f = fdopen(fd, "we");
149 r = write_string_stream_ts(f, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE), ts);
153 if (flags & WRITE_STRING_FILE_SYNC) {
154 r = fflush_sync_and_check(f);
162 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
167 /* OK, the operation failed, but let's see if the right
168 * contents in place already. If so, eat up the error. */
170 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
177 int read_one_line_file(const char *fn, char **line) {
178 _cleanup_fclose_ FILE *f = NULL;
179 char t[LINE_MAX], *c;
188 if (!fgets(t, sizeof(t), f)) {
191 return errno > 0 ? -errno : -EIO;
205 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
206 _cleanup_fclose_ FILE *f = NULL;
207 _cleanup_free_ char *buf = NULL;
215 if (accept_extra_nl && endswith(blob, "\n"))
216 accept_extra_nl = false;
218 buf = malloc(l + accept_extra_nl + 1);
226 /* We try to read one byte more than we need, so that we know whether we hit eof */
228 k = fread(buf, 1, l + accept_extra_nl + 1, f);
230 return errno > 0 ? -errno : -EIO;
232 if (k != l && k != l + accept_extra_nl)
234 if (memcmp(buf, blob, l) != 0)
236 if (k > l && buf[l] != '\n')
242 int read_full_stream(FILE *f, char **contents, size_t *size) {
244 _cleanup_free_ char *buf = NULL;
250 if (fstat(fileno(f), &st) < 0)
255 if (S_ISREG(st.st_mode)) {
258 if (st.st_size > READ_FULL_BYTES_MAX)
261 /* Start with the right file size, but be prepared for
262 * files from /proc which generally report a file size
273 t = realloc(buf, n + 1);
278 k = fread(buf + l, 1, n - l, f);
288 /* We aren't expecting fread() to return a short read outside
289 * of (error && eof), assert buffer is full and enlarge buffer.
294 if (n >= READ_FULL_BYTES_MAX)
297 n = MIN(n * 2, READ_FULL_BYTES_MAX);
302 buf = NULL; /* do not free */
310 int read_full_file(const char *fn, char **contents, size_t *size) {
311 _cleanup_fclose_ FILE *f = NULL;
320 return read_full_stream(f, contents, size);
323 static int parse_env_file_internal(
327 int (*push) (const char *filename, unsigned line,
328 const char *key, char *value, void *userdata, int *n_pushed),
332 _cleanup_free_ char *contents = NULL, *key = NULL;
333 size_t key_alloc = 0, n_key = 0, value_alloc = 0, n_value = 0, last_value_whitespace = (size_t) -1, last_key_whitespace = (size_t) -1;
334 char *p, *value = NULL;
345 SINGLE_QUOTE_VALUE_ESCAPE,
347 DOUBLE_QUOTE_VALUE_ESCAPE,
355 r = read_full_stream(f, &contents, NULL);
357 r = read_full_file(fname, &contents, NULL);
361 for (p = contents; *p; p++) {
367 if (strchr(COMMENTS, c))
369 else if (!strchr(WHITESPACE, c)) {
371 last_key_whitespace = (size_t) -1;
373 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
383 if (strchr(newline, c)) {
387 } else if (c == '=') {
389 last_value_whitespace = (size_t) -1;
391 if (!strchr(WHITESPACE, c))
392 last_key_whitespace = (size_t) -1;
393 else if (last_key_whitespace == (size_t) -1)
394 last_key_whitespace = n_key;
396 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
407 if (strchr(newline, c)) {
415 /* strip trailing whitespace from key */
416 if (last_key_whitespace != (size_t) -1)
417 key[last_key_whitespace] = 0;
419 r = push(fname, line, key, value, userdata, n_pushed);
425 value_alloc = n_value = 0;
427 } else if (c == '\'')
428 state = SINGLE_QUOTE_VALUE;
430 state = DOUBLE_QUOTE_VALUE;
432 state = VALUE_ESCAPE;
433 else if (!strchr(WHITESPACE, c)) {
436 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
441 value[n_value++] = c;
447 if (strchr(newline, c)) {
456 /* Chomp off trailing whitespace from value */
457 if (last_value_whitespace != (size_t) -1)
458 value[last_value_whitespace] = 0;
460 /* strip trailing whitespace from key */
461 if (last_key_whitespace != (size_t) -1)
462 key[last_key_whitespace] = 0;
464 r = push(fname, line, key, value, userdata, n_pushed);
470 value_alloc = n_value = 0;
472 } else if (c == '\\') {
473 state = VALUE_ESCAPE;
474 last_value_whitespace = (size_t) -1;
476 if (!strchr(WHITESPACE, c))
477 last_value_whitespace = (size_t) -1;
478 else if (last_value_whitespace == (size_t) -1)
479 last_value_whitespace = n_value;
481 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
486 value[n_value++] = c;
494 if (!strchr(newline, c)) {
495 /* Escaped newlines we eat up entirely */
496 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
501 value[n_value++] = c;
505 case SINGLE_QUOTE_VALUE:
509 state = SINGLE_QUOTE_VALUE_ESCAPE;
511 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
516 value[n_value++] = c;
521 case SINGLE_QUOTE_VALUE_ESCAPE:
522 state = SINGLE_QUOTE_VALUE;
524 if (!strchr(newline, c)) {
525 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
530 value[n_value++] = c;
534 case DOUBLE_QUOTE_VALUE:
538 state = DOUBLE_QUOTE_VALUE_ESCAPE;
540 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
545 value[n_value++] = c;
550 case DOUBLE_QUOTE_VALUE_ESCAPE:
551 state = DOUBLE_QUOTE_VALUE;
553 if (!strchr(newline, c)) {
554 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
559 value[n_value++] = c;
565 state = COMMENT_ESCAPE;
566 else if (strchr(newline, c)) {
583 SINGLE_QUOTE_VALUE_ESCAPE,
585 DOUBLE_QUOTE_VALUE_ESCAPE)) {
593 if (last_value_whitespace != (size_t) -1)
594 value[last_value_whitespace] = 0;
596 /* strip trailing whitespace from key */
597 if (last_key_whitespace != (size_t) -1)
598 key[last_key_whitespace] = 0;
600 r = push(fname, line, key, value, userdata, n_pushed);
612 static int check_utf8ness_and_warn(
613 const char *filename, unsigned line,
614 const char *key, char *value) {
616 if (!utf8_is_valid(key)) {
617 _cleanup_free_ char *p = NULL;
619 p = utf8_escape_invalid(key);
620 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
624 if (value && !utf8_is_valid(value)) {
625 _cleanup_free_ char *p = NULL;
627 p = utf8_escape_invalid(value);
628 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
635 static int parse_env_file_push(
636 const char *filename, unsigned line,
637 const char *key, char *value,
642 va_list aq, *ap = userdata;
645 r = check_utf8ness_and_warn(filename, line, key, value);
651 while ((k = va_arg(aq, const char *))) {
654 v = va_arg(aq, char **);
676 const char *newline, ...) {
684 va_start(ap, newline);
685 r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
688 return r < 0 ? r : n_pushed;
691 #if 0 /// UNNEEDED by elogind
692 static int load_env_file_push(
693 const char *filename, unsigned line,
694 const char *key, char *value,
697 char ***m = userdata;
701 r = check_utf8ness_and_warn(filename, line, key, value);
705 p = strjoin(key, "=", value);
709 r = strv_env_replace(m, p);
722 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
729 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
740 static int load_env_file_push_pairs(
741 const char *filename, unsigned line,
742 const char *key, char *value,
745 char ***m = userdata;
748 r = check_utf8ness_and_warn(filename, line, key, value);
752 r = strv_extend(m, key);
757 r = strv_extend(m, "");
761 r = strv_push(m, value);
772 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
779 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
788 #if 0 /// UNNEEDED by elogind
790 static int merge_env_file_push(
791 const char *filename, unsigned line,
792 const char *key, char *value,
796 char ***env = userdata;
797 char *expanded_value;
802 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key);
806 if (!env_name_is_valid(key)) {
807 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key);
812 expanded_value = replace_env(value, *env,
813 REPLACE_ENV_USE_ENVIRONMENT|
814 REPLACE_ENV_ALLOW_BRACELESS|
815 REPLACE_ENV_ALLOW_EXTENDED);
819 free_and_replace(value, expanded_value);
821 return load_env_file_push(filename, line, key, value, env, n_pushed);
829 /* NOTE: this function supports braceful and braceless variable expansions,
830 * plus "extended" substitutions, unlike other exported parsing functions.
833 return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
836 static void write_env_var(FILE *f, const char *v) {
842 fputs_unlocked(v, f);
843 fputc_unlocked('\n', f);
848 fwrite_unlocked(v, 1, p-v, f);
850 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
851 fputc_unlocked('\"', f);
854 if (strchr(SHELL_NEED_ESCAPE, *p))
855 fputc_unlocked('\\', f);
857 fputc_unlocked(*p, f);
860 fputc_unlocked('\"', f);
862 fputs_unlocked(p, f);
864 fputc_unlocked('\n', f);
867 int write_env_file(const char *fname, char **l) {
868 _cleanup_fclose_ FILE *f = NULL;
869 _cleanup_free_ char *p = NULL;
875 r = fopen_temporary(fname, &f, &p);
879 fchmod_umask(fileno(f), 0644);
882 write_env_var(f, *i);
884 r = fflush_and_check(f);
886 if (rename(p, fname) >= 0)
896 int executable_is_script(const char *path, char **interpreter) {
898 _cleanup_free_ char *line = NULL;
904 r = read_one_line_file(path, &line);
908 if (!startswith(line, "#!"))
911 ans = strstrip(line + 2);
912 len = strcspn(ans, " \t");
917 ans = strndup(ans, len);
927 * Retrieve one field from a file like /proc/self/status. pattern
928 * should not include whitespace or the delimiter (':'). pattern matches only
929 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
930 * zeros after the ':' will be skipped. field must be freed afterwards.
931 * terminator specifies the terminating characters of the field value (not
932 * included in the value).
934 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
935 _cleanup_free_ char *status = NULL;
945 r = read_full_file(filename, &status, NULL);
955 t = strstr(t, pattern);
959 /* Check that pattern occurs in beginning of line. */
960 pattern_ok = (t == status || t[-1] == '\n');
962 t += strlen(pattern);
964 } while (!pattern_ok);
966 t += strspn(t, " \t");
975 t += strspn(t, " \t");
977 /* Also skip zeros, because when this is used for
978 * capabilities, we don't want the zeros. This way the
979 * same capability set always maps to the same string,
980 * irrespective of the total capability set size. For
981 * other numbers it shouldn't matter. */
983 /* Back off one char if there's nothing but whitespace
985 if (!*t || isspace(*t))
989 len = strcspn(t, terminator);
999 DIR *xopendirat(int fd, const char *name, int flags) {
1003 assert(!(flags & O_CREAT));
1005 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
1018 #if 0 /// UNNEEDED by elogind
1019 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
1026 if (!path_strv_resolve_uniq(search, root))
1029 STRV_FOREACH(i, search) {
1030 _cleanup_free_ char *p = NULL;
1034 p = strjoin(root, *i, "/", path);
1036 p = strjoin(*i, "/", path);
1046 if (errno != ENOENT)
1053 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1054 _cleanup_strv_free_ char **copy = NULL;
1060 if (path_is_absolute(path)) {
1063 f = fopen(path, mode);
1072 copy = strv_copy((char**) search);
1076 return search_and_fopen_internal(path, mode, root, copy, _f);
1079 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1080 _cleanup_strv_free_ char **s = NULL;
1082 if (path_is_absolute(path)) {
1085 f = fopen(path, mode);
1094 s = strv_split_nulstr(search);
1098 return search_and_fopen_internal(path, mode, root, s, _f);
1102 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1111 r = tempfn_xxxxxx(path, NULL, &t);
1115 fd = mkostemp_safe(t);
1121 f = fdopen(fd, "we");
1135 int fflush_and_check(FILE *f) {
1142 return errno > 0 ? -errno : -EIO;
1147 int fflush_sync_and_check(FILE *f) {
1152 r = fflush_and_check(f);
1156 if (fsync(fileno(f)) < 0)
1162 /* This is much like mkostemp() but is subject to umask(). */
1163 int mkostemp_safe(char *pattern) {
1164 _cleanup_umask_ mode_t u = 0;
1171 fd = mkostemp(pattern, O_CLOEXEC);
1178 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1190 * /foo/bar/.#<extra>waldoXXXXXX
1194 if (!filename_is_valid(fn))
1200 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1204 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1206 *ret = path_kill_slashes(t);
1210 int tempfn_random(const char *p, const char *extra, char **ret) {
1224 * /foo/bar/.#<extra>waldobaa2a261115984a9
1228 if (!filename_is_valid(fn))
1234 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1238 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1241 for (i = 0; i < 16; i++) {
1242 *(x++) = hexchar(u & 0xF);
1248 *ret = path_kill_slashes(t);
1252 #if 0 /// UNNEEDED by elogind
1253 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1264 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1276 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1280 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1283 for (i = 0; i < 16; i++) {
1284 *(x++) = hexchar(u & 0xF);
1290 *ret = path_kill_slashes(t);
1294 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1295 char ln[DECIMAL_STR_MAX(n)+2];
1297 /* Creates a "timestamp" file, that contains nothing but a
1298 * usec_t timestamp, formatted in ASCII. */
1300 if (n <= 0 || n >= USEC_INFINITY)
1303 xsprintf(ln, USEC_FMT "\n", n);
1305 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1308 int read_timestamp_file(const char *fn, usec_t *ret) {
1309 _cleanup_free_ char *ln = NULL;
1313 r = read_one_line_file(fn, &ln);
1317 r = safe_atou64(ln, &t);
1321 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1328 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1333 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1334 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1335 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1336 * element, but not before the first one. */
1346 r = fputs(separator, f);
1358 int open_tmpfile_unlinkable(const char *directory, int flags) {
1363 r = tmp_dir(&directory);
1368 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1370 /* Try O_TMPFILE first, if it is supported */
1371 fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1375 /* Fall back to unguessable name + unlinking */
1376 p = strjoina(directory, "/systemd-tmp-XXXXXX");
1378 fd = mkostemp_safe(p);
1387 #if 0 /// UNNEEDED by elogind
1388 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1389 _cleanup_free_ char *tmp = NULL;
1395 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1396 assert((flags & O_EXCL) == 0);
1398 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1399 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1400 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1403 _cleanup_free_ char *dn = NULL;
1405 dn = dirname_malloc(target);
1409 fd = open(dn, O_TMPFILE|flags, 0640);
1415 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1418 r = tempfn_random(target, NULL, &tmp);
1422 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1433 int open_serialization_fd(const char *ident) {
1436 fd = memfd_create(ident, MFD_CLOEXEC);
1440 path = getpid_cached() == 1 ? "/run/systemd" : "/tmp";
1441 fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC);
1445 log_debug("Serializing %s to %s.", ident, path);
1447 log_debug("Serializing %s to memfd.", ident);
1452 #if 0 /// UNNEEDED by elogind
1453 int link_tmpfile(int fd, const char *path, const char *target) {
1458 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1459 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1460 * on the directory, and renameat2() is used instead.
1462 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1463 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1466 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1469 char proc_fd_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1471 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1473 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1480 int read_nul_string(FILE *f, char **ret) {
1481 _cleanup_free_ char *x = NULL;
1482 size_t allocated = 0, n = 0;
1487 /* Reads a NUL-terminated string from the specified file. */
1492 if (!GREEDY_REALLOC(x, allocated, n+2))
1496 if (c == 0) /* Terminate at NUL byte */
1501 break; /* Terminate at EOF */
1521 int mkdtemp_malloc(const char *template, char **ret) {
1527 p = strdup(template);