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"
40 #include "parse-util.h"
41 #include "path-util.h"
42 #include "random-util.h"
43 #include "stdio-util.h"
44 #include "string-util.h"
46 //#include "time-util.h"
47 #include "umask-util.h"
50 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
52 int write_string_stream(FILE *f, const char *line, bool enforce_newline) {
58 if (enforce_newline && !endswith(line, "\n"))
61 return fflush_and_check(f);
64 static int write_string_file_atomic(const char *fn, const char *line, bool enforce_newline) {
65 _cleanup_fclose_ FILE *f = NULL;
66 _cleanup_free_ char *p = NULL;
72 r = fopen_temporary(fn, &f, &p);
76 (void) fchmod_umask(fileno(f), 0644);
78 r = write_string_stream(f, line, enforce_newline);
80 if (rename(p, fn) < 0)
90 int write_string_file(const char *fn, const char *line, WriteStringFileFlags flags) {
91 _cleanup_fclose_ FILE *f = NULL;
97 if (flags & WRITE_STRING_FILE_ATOMIC) {
98 assert(flags & WRITE_STRING_FILE_CREATE);
100 r = write_string_file_atomic(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
107 if (flags & WRITE_STRING_FILE_CREATE) {
116 /* We manually build our own version of fopen(..., "we") that
117 * works without O_CREAT */
118 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY);
124 f = fdopen(fd, "we");
132 r = write_string_stream(f, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
139 if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
144 /* OK, the operation failed, but let's see if the right
145 * contents in place already. If so, eat up the error. */
147 q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
154 int read_one_line_file(const char *fn, char **line) {
155 _cleanup_fclose_ FILE *f = NULL;
156 char t[LINE_MAX], *c;
165 if (!fgets(t, sizeof(t), f)) {
168 return errno > 0 ? -errno : -EIO;
182 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
183 _cleanup_fclose_ FILE *f = NULL;
184 _cleanup_free_ char *buf = NULL;
192 if (accept_extra_nl && endswith(blob, "\n"))
193 accept_extra_nl = false;
195 buf = malloc(l + accept_extra_nl + 1);
203 /* We try to read one byte more than we need, so that we know whether we hit eof */
205 k = fread(buf, 1, l + accept_extra_nl + 1, f);
207 return errno > 0 ? -errno : -EIO;
209 if (k != l && k != l + accept_extra_nl)
211 if (memcmp(buf, blob, l) != 0)
213 if (k > l && buf[l] != '\n')
219 int read_full_stream(FILE *f, char **contents, size_t *size) {
221 _cleanup_free_ char *buf = NULL;
227 if (fstat(fileno(f), &st) < 0)
232 if (S_ISREG(st.st_mode)) {
235 if (st.st_size > READ_FULL_BYTES_MAX)
238 /* Start with the right file size, but be prepared for
239 * files from /proc which generally report a file size
250 t = realloc(buf, n + 1);
255 k = fread(buf + l, 1, n - l, f);
265 /* We aren't expecting fread() to return a short read outside
266 * of (error && eof), assert buffer is full and enlarge buffer.
271 if (n >= READ_FULL_BYTES_MAX)
274 n = MIN(n * 2, READ_FULL_BYTES_MAX);
279 buf = NULL; /* do not free */
287 int read_full_file(const char *fn, char **contents, size_t *size) {
288 _cleanup_fclose_ FILE *f = NULL;
297 return read_full_stream(f, contents, size);
300 static int parse_env_file_internal(
304 int (*push) (const char *filename, unsigned line,
305 const char *key, char *value, void *userdata, int *n_pushed),
309 _cleanup_free_ char *contents = NULL, *key = NULL;
310 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;
311 char *p, *value = NULL;
322 SINGLE_QUOTE_VALUE_ESCAPE,
324 DOUBLE_QUOTE_VALUE_ESCAPE,
332 r = read_full_stream(f, &contents, NULL);
334 r = read_full_file(fname, &contents, NULL);
338 for (p = contents; *p; p++) {
344 if (strchr(COMMENTS, c))
346 else if (!strchr(WHITESPACE, c)) {
348 last_key_whitespace = (size_t) -1;
350 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
360 if (strchr(newline, c)) {
364 } else if (c == '=') {
366 last_value_whitespace = (size_t) -1;
368 if (!strchr(WHITESPACE, c))
369 last_key_whitespace = (size_t) -1;
370 else if (last_key_whitespace == (size_t) -1)
371 last_key_whitespace = n_key;
373 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
384 if (strchr(newline, c)) {
392 /* strip trailing whitespace from key */
393 if (last_key_whitespace != (size_t) -1)
394 key[last_key_whitespace] = 0;
396 r = push(fname, line, key, value, userdata, n_pushed);
402 value_alloc = n_value = 0;
404 } else if (c == '\'')
405 state = SINGLE_QUOTE_VALUE;
407 state = DOUBLE_QUOTE_VALUE;
409 state = VALUE_ESCAPE;
410 else if (!strchr(WHITESPACE, c)) {
413 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
418 value[n_value++] = c;
424 if (strchr(newline, c)) {
433 /* Chomp off trailing whitespace from value */
434 if (last_value_whitespace != (size_t) -1)
435 value[last_value_whitespace] = 0;
437 /* strip trailing whitespace from key */
438 if (last_key_whitespace != (size_t) -1)
439 key[last_key_whitespace] = 0;
441 r = push(fname, line, key, value, userdata, n_pushed);
447 value_alloc = n_value = 0;
449 } else if (c == '\\') {
450 state = VALUE_ESCAPE;
451 last_value_whitespace = (size_t) -1;
453 if (!strchr(WHITESPACE, c))
454 last_value_whitespace = (size_t) -1;
455 else if (last_value_whitespace == (size_t) -1)
456 last_value_whitespace = n_value;
458 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
463 value[n_value++] = c;
471 if (!strchr(newline, c)) {
472 /* Escaped newlines we eat up entirely */
473 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
478 value[n_value++] = c;
482 case SINGLE_QUOTE_VALUE:
486 state = SINGLE_QUOTE_VALUE_ESCAPE;
488 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
493 value[n_value++] = c;
498 case SINGLE_QUOTE_VALUE_ESCAPE:
499 state = SINGLE_QUOTE_VALUE;
501 if (!strchr(newline, c)) {
502 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
507 value[n_value++] = c;
511 case DOUBLE_QUOTE_VALUE:
515 state = DOUBLE_QUOTE_VALUE_ESCAPE;
517 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
522 value[n_value++] = c;
527 case DOUBLE_QUOTE_VALUE_ESCAPE:
528 state = DOUBLE_QUOTE_VALUE;
530 if (!strchr(newline, c)) {
531 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
536 value[n_value++] = c;
542 state = COMMENT_ESCAPE;
543 else if (strchr(newline, c)) {
555 if (state == PRE_VALUE ||
557 state == VALUE_ESCAPE ||
558 state == SINGLE_QUOTE_VALUE ||
559 state == SINGLE_QUOTE_VALUE_ESCAPE ||
560 state == DOUBLE_QUOTE_VALUE ||
561 state == DOUBLE_QUOTE_VALUE_ESCAPE) {
569 if (last_value_whitespace != (size_t) -1)
570 value[last_value_whitespace] = 0;
572 /* strip trailing whitespace from key */
573 if (last_key_whitespace != (size_t) -1)
574 key[last_key_whitespace] = 0;
576 r = push(fname, line, key, value, userdata, n_pushed);
588 static int check_utf8ness_and_warn(
589 const char *filename, unsigned line,
590 const char *key, char *value) {
592 if (!utf8_is_valid(key)) {
593 _cleanup_free_ char *p = NULL;
595 p = utf8_escape_invalid(key);
596 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
600 if (value && !utf8_is_valid(value)) {
601 _cleanup_free_ char *p = NULL;
603 p = utf8_escape_invalid(value);
604 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
611 static int parse_env_file_push(
612 const char *filename, unsigned line,
613 const char *key, char *value,
618 va_list aq, *ap = userdata;
621 r = check_utf8ness_and_warn(filename, line, key, value);
627 while ((k = va_arg(aq, const char *))) {
630 v = va_arg(aq, char **);
652 const char *newline, ...) {
660 va_start(ap, newline);
661 r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
664 return r < 0 ? r : n_pushed;
667 #if 0 /// UNNEEDED by elogind
668 static int load_env_file_push(
669 const char *filename, unsigned line,
670 const char *key, char *value,
673 char ***m = userdata;
677 r = check_utf8ness_and_warn(filename, line, key, value);
681 p = strjoin(key, "=", strempty(value));
685 r = strv_consume(m, p);
696 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
703 r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
713 static int load_env_file_push_pairs(
714 const char *filename, unsigned line,
715 const char *key, char *value,
718 char ***m = userdata;
721 r = check_utf8ness_and_warn(filename, line, key, value);
725 r = strv_extend(m, key);
730 r = strv_extend(m, "");
734 r = strv_push(m, value);
745 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
752 r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
762 static void write_env_var(FILE *f, const char *v) {
774 fwrite(v, 1, p-v, f);
776 if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
780 if (strchr(SHELL_NEED_ESCAPE, *p))
793 int write_env_file(const char *fname, char **l) {
794 _cleanup_fclose_ FILE *f = NULL;
795 _cleanup_free_ char *p = NULL;
801 r = fopen_temporary(fname, &f, &p);
805 fchmod_umask(fileno(f), 0644);
808 write_env_var(f, *i);
810 r = fflush_and_check(f);
812 if (rename(p, fname) >= 0)
822 int executable_is_script(const char *path, char **interpreter) {
824 _cleanup_free_ char *line = NULL;
830 r = read_one_line_file(path, &line);
834 if (!startswith(line, "#!"))
837 ans = strstrip(line + 2);
838 len = strcspn(ans, " \t");
843 ans = strndup(ans, len);
853 * Retrieve one field from a file like /proc/self/status. pattern
854 * should not include whitespace or the delimiter (':'). pattern matches only
855 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
856 * zeros after the ':' will be skipped. field must be freed afterwards.
857 * terminator specifies the terminating characters of the field value (not
858 * included in the value).
860 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
861 _cleanup_free_ char *status = NULL;
871 r = read_full_file(filename, &status, NULL);
881 t = strstr(t, pattern);
885 /* Check that pattern occurs in beginning of line. */
886 pattern_ok = (t == status || t[-1] == '\n');
888 t += strlen(pattern);
890 } while (!pattern_ok);
892 t += strspn(t, " \t");
901 t += strspn(t, " \t");
903 /* Also skip zeros, because when this is used for
904 * capabilities, we don't want the zeros. This way the
905 * same capability set always maps to the same string,
906 * irrespective of the total capability set size. For
907 * other numbers it shouldn't matter. */
909 /* Back off one char if there's nothing but whitespace
911 if (!*t || isspace(*t))
915 len = strcspn(t, terminator);
925 DIR *xopendirat(int fd, const char *name, int flags) {
929 assert(!(flags & O_CREAT));
931 nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
944 #if 0 /// UNNEEDED by elogind
945 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
952 if (!path_strv_resolve_uniq(search, root))
955 STRV_FOREACH(i, search) {
956 _cleanup_free_ char *p = NULL;
960 p = strjoin(root, *i, "/", path);
962 p = strjoin(*i, "/", path);
979 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
980 _cleanup_strv_free_ char **copy = NULL;
986 if (path_is_absolute(path)) {
989 f = fopen(path, mode);
998 copy = strv_copy((char**) search);
1002 return search_and_fopen_internal(path, mode, root, copy, _f);
1005 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1006 _cleanup_strv_free_ char **s = NULL;
1008 if (path_is_absolute(path)) {
1011 f = fopen(path, mode);
1020 s = strv_split_nulstr(search);
1024 return search_and_fopen_internal(path, mode, root, s, _f);
1028 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1037 r = tempfn_xxxxxx(path, NULL, &t);
1041 fd = mkostemp_safe(t);
1047 f = fdopen(fd, "we");
1061 int fflush_and_check(FILE *f) {
1068 return errno > 0 ? -errno : -EIO;
1073 /* This is much like mkostemp() but is subject to umask(). */
1074 int mkostemp_safe(char *pattern) {
1075 _cleanup_umask_ mode_t u = 0;
1082 fd = mkostemp(pattern, O_CLOEXEC);
1089 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1101 * /foo/bar/.#<extra>waldoXXXXXX
1105 if (!filename_is_valid(fn))
1111 t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1115 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1117 *ret = path_kill_slashes(t);
1121 int tempfn_random(const char *p, const char *extra, char **ret) {
1135 * /foo/bar/.#<extra>waldobaa2a261115984a9
1139 if (!filename_is_valid(fn))
1145 t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1149 x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1152 for (i = 0; i < 16; i++) {
1153 *(x++) = hexchar(u & 0xF);
1159 *ret = path_kill_slashes(t);
1163 #if 0 /// UNNEEDED by elogind
1164 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1175 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1187 t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1191 x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1194 for (i = 0; i < 16; i++) {
1195 *(x++) = hexchar(u & 0xF);
1201 *ret = path_kill_slashes(t);
1205 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1206 char ln[DECIMAL_STR_MAX(n)+2];
1208 /* Creates a "timestamp" file, that contains nothing but a
1209 * usec_t timestamp, formatted in ASCII. */
1211 if (n <= 0 || n >= USEC_INFINITY)
1214 xsprintf(ln, USEC_FMT "\n", n);
1216 return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1219 int read_timestamp_file(const char *fn, usec_t *ret) {
1220 _cleanup_free_ char *ln = NULL;
1224 r = read_one_line_file(fn, &ln);
1228 r = safe_atou64(ln, &t);
1232 if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1239 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1244 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1245 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1246 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1247 * element, but not before the first one. */
1257 r = fputs(separator, f);
1268 int open_tmpfile_unlinkable(const char *directory, int flags) {
1273 r = tmp_dir(&directory);
1278 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1280 /* Try O_TMPFILE first, if it is supported */
1281 fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1285 /* Fall back to unguessable name + unlinking */
1286 p = strjoina(directory, "/systemd-tmp-XXXXXX");
1288 fd = mkostemp_safe(p);
1297 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1298 _cleanup_free_ char *tmp = NULL;
1304 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1305 assert((flags & O_EXCL) == 0);
1307 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1308 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1309 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1312 _cleanup_free_ char *dn = NULL;
1314 dn = dirname_malloc(target);
1318 fd = open(dn, O_TMPFILE|flags, 0640);
1324 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1327 r = tempfn_random(target, NULL, &tmp);
1331 fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1341 int link_tmpfile(int fd, const char *path, const char *target) {
1346 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1347 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1348 * on the directory, and renameat2() is used instead.
1350 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1351 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1354 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1357 char proc_fd_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1359 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1361 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1369 int read_nul_string(FILE *f, char **ret) {
1370 _cleanup_free_ char *x = NULL;
1371 size_t allocated = 0, n = 0;
1376 /* Reads a NUL-terminated string from the specified file. */
1381 if (!GREEDY_REALLOC(x, allocated, n+2))
1385 if (c == 0) /* Terminate at NUL byte */
1390 break; /* Terminate at EOF */
1410 int mkdtemp_malloc(const char *template, char **ret) {
1416 p = strdup(template);