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 int write_string_stream(FILE *f
, const char *line
, bool enforce_newline
) {
56 if (enforce_newline
&& !endswith(line
, "\n"))
59 return fflush_and_check(f
);
62 static int write_string_file_atomic(const char *fn
, const char *line
, bool enforce_newline
) {
63 _cleanup_fclose_
FILE *f
= NULL
;
64 _cleanup_free_
char *p
= NULL
;
70 r
= fopen_temporary(fn
, &f
, &p
);
74 (void) fchmod_umask(fileno(f
), 0644);
76 r
= write_string_stream(f
, line
, enforce_newline
);
78 if (rename(p
, fn
) < 0)
88 int write_string_file(const char *fn
, const char *line
, WriteStringFileFlags flags
) {
89 _cleanup_fclose_
FILE *f
= NULL
;
95 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
96 assert(flags
& WRITE_STRING_FILE_CREATE
);
98 r
= write_string_file_atomic(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
105 if (flags
& WRITE_STRING_FILE_CREATE
) {
114 /* We manually build our own version of fopen(..., "we") that
115 * works without O_CREAT */
116 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
);
122 f
= fdopen(fd
, "we");
130 r
= write_string_stream(f
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
137 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
142 /* OK, the operation failed, but let's see if the right
143 * contents in place already. If so, eat up the error. */
145 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
152 int read_one_line_file(const char *fn
, char **line
) {
153 _cleanup_fclose_
FILE *f
= NULL
;
154 char t
[LINE_MAX
], *c
;
163 if (!fgets(t
, sizeof(t
), f
)) {
166 return errno
> 0 ? -errno
: -EIO
;
180 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
181 _cleanup_fclose_
FILE *f
= NULL
;
182 _cleanup_free_
char *buf
= NULL
;
190 if (accept_extra_nl
&& endswith(blob
, "\n"))
191 accept_extra_nl
= false;
193 buf
= malloc(l
+ accept_extra_nl
+ 1);
201 /* We try to read one byte more than we need, so that we know whether we hit eof */
203 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
205 return errno
> 0 ? -errno
: -EIO
;
207 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
209 if (memcmp(buf
, blob
, l
) != 0)
211 if (k
> l
&& buf
[l
] != '\n')
217 int read_full_stream(FILE *f
, char **contents
, size_t *size
) {
219 _cleanup_free_
char *buf
= NULL
;
225 if (fstat(fileno(f
), &st
) < 0)
230 if (S_ISREG(st
.st_mode
)) {
233 if (st
.st_size
> 4*1024*1024)
236 /* Start with the right file size, but be prepared for
237 * files from /proc which generally report a file size
248 t
= realloc(buf
, n
+1);
253 k
= fread(buf
+ l
, 1, n
- l
, f
);
272 buf
= NULL
; /* do not free */
280 int read_full_file(const char *fn
, char **contents
, size_t *size
) {
281 _cleanup_fclose_
FILE *f
= NULL
;
290 return read_full_stream(f
, contents
, size
);
293 static int parse_env_file_internal(
297 int (*push
) (const char *filename
, unsigned line
,
298 const char *key
, char *value
, void *userdata
, int *n_pushed
),
302 _cleanup_free_
char *contents
= NULL
, *key
= NULL
;
303 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;
304 char *p
, *value
= NULL
;
315 SINGLE_QUOTE_VALUE_ESCAPE
,
317 DOUBLE_QUOTE_VALUE_ESCAPE
,
325 r
= read_full_stream(f
, &contents
, NULL
);
327 r
= read_full_file(fname
, &contents
, NULL
);
331 for (p
= contents
; *p
; p
++) {
337 if (strchr(COMMENTS
, c
))
339 else if (!strchr(WHITESPACE
, c
)) {
341 last_key_whitespace
= (size_t) -1;
343 if (!GREEDY_REALLOC(key
, key_alloc
, n_key
+2)) {
353 if (strchr(newline
, c
)) {
357 } else if (c
== '=') {
359 last_value_whitespace
= (size_t) -1;
361 if (!strchr(WHITESPACE
, c
))
362 last_key_whitespace
= (size_t) -1;
363 else if (last_key_whitespace
== (size_t) -1)
364 last_key_whitespace
= n_key
;
366 if (!GREEDY_REALLOC(key
, key_alloc
, n_key
+2)) {
377 if (strchr(newline
, c
)) {
385 /* strip trailing whitespace from key */
386 if (last_key_whitespace
!= (size_t) -1)
387 key
[last_key_whitespace
] = 0;
389 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
395 value_alloc
= n_value
= 0;
397 } else if (c
== '\'')
398 state
= SINGLE_QUOTE_VALUE
;
400 state
= DOUBLE_QUOTE_VALUE
;
402 state
= VALUE_ESCAPE
;
403 else if (!strchr(WHITESPACE
, c
)) {
406 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
411 value
[n_value
++] = c
;
417 if (strchr(newline
, c
)) {
426 /* Chomp off trailing whitespace from value */
427 if (last_value_whitespace
!= (size_t) -1)
428 value
[last_value_whitespace
] = 0;
430 /* strip trailing whitespace from key */
431 if (last_key_whitespace
!= (size_t) -1)
432 key
[last_key_whitespace
] = 0;
434 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
440 value_alloc
= n_value
= 0;
442 } else if (c
== '\\') {
443 state
= VALUE_ESCAPE
;
444 last_value_whitespace
= (size_t) -1;
446 if (!strchr(WHITESPACE
, c
))
447 last_value_whitespace
= (size_t) -1;
448 else if (last_value_whitespace
== (size_t) -1)
449 last_value_whitespace
= n_value
;
451 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
456 value
[n_value
++] = c
;
464 if (!strchr(newline
, c
)) {
465 /* Escaped newlines we eat up entirely */
466 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
471 value
[n_value
++] = c
;
475 case SINGLE_QUOTE_VALUE
:
479 state
= SINGLE_QUOTE_VALUE_ESCAPE
;
481 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
486 value
[n_value
++] = c
;
491 case SINGLE_QUOTE_VALUE_ESCAPE
:
492 state
= SINGLE_QUOTE_VALUE
;
494 if (!strchr(newline
, c
)) {
495 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
500 value
[n_value
++] = c
;
504 case DOUBLE_QUOTE_VALUE
:
508 state
= DOUBLE_QUOTE_VALUE_ESCAPE
;
510 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
515 value
[n_value
++] = c
;
520 case DOUBLE_QUOTE_VALUE_ESCAPE
:
521 state
= DOUBLE_QUOTE_VALUE
;
523 if (!strchr(newline
, c
)) {
524 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
529 value
[n_value
++] = c
;
535 state
= COMMENT_ESCAPE
;
536 else if (strchr(newline
, c
)) {
548 if (state
== PRE_VALUE
||
550 state
== VALUE_ESCAPE
||
551 state
== SINGLE_QUOTE_VALUE
||
552 state
== SINGLE_QUOTE_VALUE_ESCAPE
||
553 state
== DOUBLE_QUOTE_VALUE
||
554 state
== DOUBLE_QUOTE_VALUE_ESCAPE
) {
562 if (last_value_whitespace
!= (size_t) -1)
563 value
[last_value_whitespace
] = 0;
565 /* strip trailing whitespace from key */
566 if (last_key_whitespace
!= (size_t) -1)
567 key
[last_key_whitespace
] = 0;
569 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
581 static int parse_env_file_push(
582 const char *filename
, unsigned line
,
583 const char *key
, char *value
,
588 va_list aq
, *ap
= userdata
;
590 if (!utf8_is_valid(key
)) {
591 _cleanup_free_
char *p
= NULL
;
593 p
= utf8_escape_invalid(key
);
594 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename
), line
, p
);
598 if (value
&& !utf8_is_valid(value
)) {
599 _cleanup_free_
char *p
= NULL
;
601 p
= utf8_escape_invalid(value
);
602 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename
), line
, key
, p
);
608 while ((k
= va_arg(aq
, const char *))) {
611 v
= va_arg(aq
, char **);
633 const char *newline
, ...) {
641 va_start(ap
, newline
);
642 r
= parse_env_file_internal(NULL
, fname
, newline
, parse_env_file_push
, &ap
, &n_pushed
);
645 return r
< 0 ? r
: n_pushed
;
648 static int load_env_file_push(
649 const char *filename
, unsigned line
,
650 const char *key
, char *value
,
653 char ***m
= userdata
;
657 if (!utf8_is_valid(key
)) {
658 _cleanup_free_
char *t
= utf8_escape_invalid(key
);
660 log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename
), line
, t
);
664 if (value
&& !utf8_is_valid(value
)) {
665 _cleanup_free_
char *t
= utf8_escape_invalid(value
);
667 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename
), line
, key
, t
);
671 p
= strjoin(key
, "=", strempty(value
), NULL
);
675 r
= strv_consume(m
, p
);
686 int load_env_file(FILE *f
, const char *fname
, const char *newline
, char ***rl
) {
693 r
= parse_env_file_internal(f
, fname
, newline
, load_env_file_push
, &m
, NULL
);
703 static int load_env_file_push_pairs(
704 const char *filename
, unsigned line
,
705 const char *key
, char *value
,
708 char ***m
= userdata
;
711 if (!utf8_is_valid(key
)) {
712 _cleanup_free_
char *t
= utf8_escape_invalid(key
);
714 log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename
), line
, t
);
718 if (value
&& !utf8_is_valid(value
)) {
719 _cleanup_free_
char *t
= utf8_escape_invalid(value
);
721 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename
), line
, key
, t
);
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
);
852 * Retrieve one field from a file like /proc/self/status. pattern
853 * should not include whitespace or the delimiter (':'). pattern matches only
854 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
855 * zeros after the ':' will be skipped. field must be freed afterwards.
856 * terminator specifies the terminating characters of the field value (not
857 * included in the value).
859 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
860 _cleanup_free_
char *status
= NULL
;
870 r
= read_full_file(filename
, &status
, NULL
);
880 t
= strstr(t
, pattern
);
884 /* Check that pattern occurs in beginning of line. */
885 pattern_ok
= (t
== status
|| t
[-1] == '\n');
887 t
+= strlen(pattern
);
889 } while (!pattern_ok
);
891 t
+= strspn(t
, " \t");
900 t
+= strspn(t
, " \t");
902 /* Also skip zeros, because when this is used for
903 * capabilities, we don't want the zeros. This way the
904 * same capability set always maps to the same string,
905 * irrespective of the total capability set size. For
906 * other numbers it shouldn't matter. */
908 /* Back off one char if there's nothing but whitespace
910 if (!*t
|| isspace(*t
))
914 len
= strcspn(t
, terminator
);
924 DIR *xopendirat(int fd
, const char *name
, int flags
) {
928 assert(!(flags
& O_CREAT
));
930 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
943 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
950 if (!path_strv_resolve_uniq(search
, root
))
953 STRV_FOREACH(i
, search
) {
954 _cleanup_free_
char *p
= NULL
;
958 p
= strjoin(root
, *i
, "/", path
, NULL
);
960 p
= strjoin(*i
, "/", path
, NULL
);
977 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
978 _cleanup_strv_free_
char **copy
= NULL
;
984 if (path_is_absolute(path
)) {
987 f
= fopen(path
, mode
);
996 copy
= strv_copy((char**) search
);
1000 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
1003 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
1004 _cleanup_strv_free_
char **s
= NULL
;
1006 if (path_is_absolute(path
)) {
1009 f
= fopen(path
, mode
);
1018 s
= strv_split_nulstr(search
);
1022 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
1025 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
1034 r
= tempfn_xxxxxx(path
, NULL
, &t
);
1038 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
1044 f
= fdopen(fd
, "we");
1058 int fflush_and_check(FILE *f
) {
1065 return errno
> 0 ? -errno
: -EIO
;
1070 /* This is much like mkostemp() but is subject to umask(). */
1071 int mkostemp_safe(char *pattern
, int flags
) {
1072 _cleanup_umask_ mode_t u
= 0;
1079 fd
= mkostemp(pattern
, flags
);
1086 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
1098 * /foo/bar/.#<extra>waldoXXXXXX
1102 if (!filename_is_valid(fn
))
1108 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
1112 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
1114 *ret
= path_kill_slashes(t
);
1118 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
1132 * /foo/bar/.#<extra>waldobaa2a261115984a9
1136 if (!filename_is_valid(fn
))
1142 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
1146 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
1149 for (i
= 0; i
< 16; i
++) {
1150 *(x
++) = hexchar(u
& 0xF);
1156 *ret
= path_kill_slashes(t
);
1160 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
1171 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1177 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
1181 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
1184 for (i
= 0; i
< 16; i
++) {
1185 *(x
++) = hexchar(u
& 0xF);
1191 *ret
= path_kill_slashes(t
);
1195 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1196 char ln
[DECIMAL_STR_MAX(n
)+2];
1198 /* Creates a "timestamp" file, that contains nothing but a
1199 * usec_t timestamp, formatted in ASCII. */
1201 if (n
<= 0 || n
>= USEC_INFINITY
)
1204 xsprintf(ln
, USEC_FMT
"\n", n
);
1206 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1209 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1210 _cleanup_free_
char *ln
= NULL
;
1214 r
= read_one_line_file(fn
, &ln
);
1218 r
= safe_atou64(ln
, &t
);
1222 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1229 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1234 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1235 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1236 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1237 * element, but not before the first one. */
1247 r
= fputs(separator
, f
);
1258 int open_tmpfile_unlinkable(const char *directory
, int flags
) {
1265 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1268 /* Try O_TMPFILE first, if it is supported */
1269 fd
= open(directory
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
1274 /* Fall back to unguessable name + unlinking */
1275 p
= strjoina(directory
, "/systemd-tmp-XXXXXX");
1277 fd
= mkostemp_safe(p
, flags
);
1286 int open_tmpfile_linkable(const char *target
, int flags
, char **ret_path
) {
1287 _cleanup_free_
char *tmp
= NULL
;
1293 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1294 assert((flags
& O_EXCL
) == 0);
1296 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1297 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1298 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1302 _cleanup_free_
char *dn
= NULL
;
1304 dn
= dirname_malloc(target
);
1308 fd
= open(dn
, O_TMPFILE
|flags
, 0640);
1314 log_debug_errno(errno
, "Failed to use O_TMPFILE on %s: %m", dn
);
1318 r
= tempfn_random(target
, NULL
, &tmp
);
1322 fd
= open(tmp
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NOCTTY
|flags
, 0640);
1332 int link_tmpfile(int fd
, const char *path
, const char *target
) {
1337 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1338 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1339 * on the directory, and renameat2() is used instead.
1341 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1342 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1345 if (rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, target
) < 0)
1348 char proc_fd_path
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(fd
) + 1];
1350 xsprintf(proc_fd_path
, "/proc/self/fd/%i", fd
);
1352 if (linkat(AT_FDCWD
, proc_fd_path
, AT_FDCWD
, target
, AT_SYMLINK_FOLLOW
) < 0)
1359 int read_nul_string(FILE *f
, char **ret
) {
1360 _cleanup_free_
char *x
= NULL
;
1361 size_t allocated
= 0, n
= 0;
1366 /* Reads a NUL-terminated string from the specified file. */
1371 if (!GREEDY_REALLOC(x
, allocated
, n
+2))
1375 if (c
== 0) /* Terminate at NUL byte */
1380 break; /* Terminate at EOF */