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 "random-util.h"
44 #include "stdio-util.h"
45 #include "string-util.h"
47 #include "time-util.h"
48 #include "umask-util.h"
51 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
53 int write_string_stream(FILE *f
, const char *line
, bool enforce_newline
) {
59 if (enforce_newline
&& !endswith(line
, "\n"))
62 return fflush_and_check(f
);
65 static int write_string_file_atomic(const char *fn
, const char *line
, bool enforce_newline
) {
66 _cleanup_fclose_
FILE *f
= NULL
;
67 _cleanup_free_
char *p
= NULL
;
73 r
= fopen_temporary(fn
, &f
, &p
);
77 (void) fchmod_umask(fileno(f
), 0644);
79 r
= write_string_stream(f
, line
, enforce_newline
);
81 if (rename(p
, fn
) < 0)
91 int write_string_file(const char *fn
, const char *line
, WriteStringFileFlags flags
) {
92 _cleanup_fclose_
FILE *f
= NULL
;
98 if (flags
& WRITE_STRING_FILE_ATOMIC
) {
99 assert(flags
& WRITE_STRING_FILE_CREATE
);
101 r
= write_string_file_atomic(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
108 if (flags
& WRITE_STRING_FILE_CREATE
) {
117 /* We manually build our own version of fopen(..., "we") that
118 * works without O_CREAT */
119 fd
= open(fn
, O_WRONLY
|O_CLOEXEC
|O_NOCTTY
);
125 f
= fdopen(fd
, "we");
133 r
= write_string_stream(f
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
140 if (!(flags
& WRITE_STRING_FILE_VERIFY_ON_FAILURE
))
145 /* OK, the operation failed, but let's see if the right
146 * contents in place already. If so, eat up the error. */
148 q
= verify_file(fn
, line
, !(flags
& WRITE_STRING_FILE_AVOID_NEWLINE
));
155 int read_one_line_file(const char *fn
, char **line
) {
156 _cleanup_fclose_
FILE *f
= NULL
;
157 char t
[LINE_MAX
], *c
;
166 if (!fgets(t
, sizeof(t
), f
)) {
169 return errno
> 0 ? -errno
: -EIO
;
183 int verify_file(const char *fn
, const char *blob
, bool accept_extra_nl
) {
184 _cleanup_fclose_
FILE *f
= NULL
;
185 _cleanup_free_
char *buf
= NULL
;
193 if (accept_extra_nl
&& endswith(blob
, "\n"))
194 accept_extra_nl
= false;
196 buf
= malloc(l
+ accept_extra_nl
+ 1);
204 /* We try to read one byte more than we need, so that we know whether we hit eof */
206 k
= fread(buf
, 1, l
+ accept_extra_nl
+ 1, f
);
208 return errno
> 0 ? -errno
: -EIO
;
210 if (k
!= l
&& k
!= l
+ accept_extra_nl
)
212 if (memcmp(buf
, blob
, l
) != 0)
214 if (k
> l
&& buf
[l
] != '\n')
220 int read_full_stream(FILE *f
, char **contents
, size_t *size
) {
222 _cleanup_free_
char *buf
= NULL
;
228 if (fstat(fileno(f
), &st
) < 0)
233 if (S_ISREG(st
.st_mode
)) {
236 if (st
.st_size
> READ_FULL_BYTES_MAX
)
239 /* Start with the right file size, but be prepared for
240 * files from /proc which generally report a file size
251 t
= realloc(buf
, n
+ 1);
256 k
= fread(buf
+ l
, 1, n
- l
, f
);
266 /* We aren't expecting fread() to return a short read outside
267 * of (error && eof), assert buffer is full and enlarge buffer.
272 if (n
>= READ_FULL_BYTES_MAX
)
275 n
= MIN(n
* 2, READ_FULL_BYTES_MAX
);
280 buf
= NULL
; /* do not free */
288 int read_full_file(const char *fn
, char **contents
, size_t *size
) {
289 _cleanup_fclose_
FILE *f
= NULL
;
298 return read_full_stream(f
, contents
, size
);
301 static int parse_env_file_internal(
305 int (*push
) (const char *filename
, unsigned line
,
306 const char *key
, char *value
, void *userdata
, int *n_pushed
),
310 _cleanup_free_
char *contents
= NULL
, *key
= NULL
;
311 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;
312 char *p
, *value
= NULL
;
323 SINGLE_QUOTE_VALUE_ESCAPE
,
325 DOUBLE_QUOTE_VALUE_ESCAPE
,
333 r
= read_full_stream(f
, &contents
, NULL
);
335 r
= read_full_file(fname
, &contents
, NULL
);
339 for (p
= contents
; *p
; p
++) {
345 if (strchr(COMMENTS
, c
))
347 else if (!strchr(WHITESPACE
, c
)) {
349 last_key_whitespace
= (size_t) -1;
351 if (!GREEDY_REALLOC(key
, key_alloc
, n_key
+2)) {
361 if (strchr(newline
, c
)) {
365 } else if (c
== '=') {
367 last_value_whitespace
= (size_t) -1;
369 if (!strchr(WHITESPACE
, c
))
370 last_key_whitespace
= (size_t) -1;
371 else if (last_key_whitespace
== (size_t) -1)
372 last_key_whitespace
= n_key
;
374 if (!GREEDY_REALLOC(key
, key_alloc
, n_key
+2)) {
385 if (strchr(newline
, c
)) {
393 /* strip trailing whitespace from key */
394 if (last_key_whitespace
!= (size_t) -1)
395 key
[last_key_whitespace
] = 0;
397 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
403 value_alloc
= n_value
= 0;
405 } else if (c
== '\'')
406 state
= SINGLE_QUOTE_VALUE
;
408 state
= DOUBLE_QUOTE_VALUE
;
410 state
= VALUE_ESCAPE
;
411 else if (!strchr(WHITESPACE
, c
)) {
414 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
419 value
[n_value
++] = c
;
425 if (strchr(newline
, c
)) {
434 /* Chomp off trailing whitespace from value */
435 if (last_value_whitespace
!= (size_t) -1)
436 value
[last_value_whitespace
] = 0;
438 /* strip trailing whitespace from key */
439 if (last_key_whitespace
!= (size_t) -1)
440 key
[last_key_whitespace
] = 0;
442 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
448 value_alloc
= n_value
= 0;
450 } else if (c
== '\\') {
451 state
= VALUE_ESCAPE
;
452 last_value_whitespace
= (size_t) -1;
454 if (!strchr(WHITESPACE
, c
))
455 last_value_whitespace
= (size_t) -1;
456 else if (last_value_whitespace
== (size_t) -1)
457 last_value_whitespace
= n_value
;
459 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
464 value
[n_value
++] = c
;
472 if (!strchr(newline
, c
)) {
473 /* Escaped newlines we eat up entirely */
474 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
479 value
[n_value
++] = c
;
483 case SINGLE_QUOTE_VALUE
:
487 state
= SINGLE_QUOTE_VALUE_ESCAPE
;
489 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
494 value
[n_value
++] = c
;
499 case SINGLE_QUOTE_VALUE_ESCAPE
:
500 state
= SINGLE_QUOTE_VALUE
;
502 if (!strchr(newline
, c
)) {
503 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
508 value
[n_value
++] = c
;
512 case DOUBLE_QUOTE_VALUE
:
516 state
= DOUBLE_QUOTE_VALUE_ESCAPE
;
518 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
523 value
[n_value
++] = c
;
528 case DOUBLE_QUOTE_VALUE_ESCAPE
:
529 state
= DOUBLE_QUOTE_VALUE
;
531 if (!strchr(newline
, c
)) {
532 if (!GREEDY_REALLOC(value
, value_alloc
, n_value
+2)) {
537 value
[n_value
++] = c
;
543 state
= COMMENT_ESCAPE
;
544 else if (strchr(newline
, c
)) {
556 if (state
== PRE_VALUE
||
558 state
== VALUE_ESCAPE
||
559 state
== SINGLE_QUOTE_VALUE
||
560 state
== SINGLE_QUOTE_VALUE_ESCAPE
||
561 state
== DOUBLE_QUOTE_VALUE
||
562 state
== DOUBLE_QUOTE_VALUE_ESCAPE
) {
570 if (last_value_whitespace
!= (size_t) -1)
571 value
[last_value_whitespace
] = 0;
573 /* strip trailing whitespace from key */
574 if (last_key_whitespace
!= (size_t) -1)
575 key
[last_key_whitespace
] = 0;
577 r
= push(fname
, line
, key
, value
, userdata
, n_pushed
);
589 static int parse_env_file_push(
590 const char *filename
, unsigned line
,
591 const char *key
, char *value
,
596 va_list aq
, *ap
= userdata
;
598 if (!utf8_is_valid(key
)) {
599 _cleanup_free_
char *p
= NULL
;
601 p
= utf8_escape_invalid(key
);
602 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename
), line
, p
);
606 if (value
&& !utf8_is_valid(value
)) {
607 _cleanup_free_
char *p
= NULL
;
609 p
= utf8_escape_invalid(value
);
610 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename
), line
, key
, p
);
616 while ((k
= va_arg(aq
, const char *))) {
619 v
= va_arg(aq
, char **);
641 const char *newline
, ...) {
649 va_start(ap
, newline
);
650 r
= parse_env_file_internal(NULL
, fname
, newline
, parse_env_file_push
, &ap
, &n_pushed
);
653 return r
< 0 ? r
: n_pushed
;
656 static int load_env_file_push(
657 const char *filename
, unsigned line
,
658 const char *key
, char *value
,
661 char ***m
= userdata
;
665 if (!utf8_is_valid(key
)) {
666 _cleanup_free_
char *t
= utf8_escape_invalid(key
);
668 log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename
), line
, t
);
672 if (value
&& !utf8_is_valid(value
)) {
673 _cleanup_free_
char *t
= utf8_escape_invalid(value
);
675 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename
), line
, key
, t
);
679 p
= strjoin(key
, "=", strempty(value
), NULL
);
683 r
= strv_consume(m
, p
);
694 int load_env_file(FILE *f
, const char *fname
, const char *newline
, char ***rl
) {
701 r
= parse_env_file_internal(f
, fname
, newline
, load_env_file_push
, &m
, NULL
);
711 static int load_env_file_push_pairs(
712 const char *filename
, unsigned line
,
713 const char *key
, char *value
,
716 char ***m
= userdata
;
719 if (!utf8_is_valid(key
)) {
720 _cleanup_free_
char *t
= utf8_escape_invalid(key
);
722 log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename
), line
, t
);
726 if (value
&& !utf8_is_valid(value
)) {
727 _cleanup_free_
char *t
= utf8_escape_invalid(value
);
729 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename
), line
, key
, t
);
733 r
= strv_extend(m
, key
);
738 r
= strv_extend(m
, "");
742 r
= strv_push(m
, value
);
753 int load_env_file_pairs(FILE *f
, const char *fname
, const char *newline
, char ***rl
) {
760 r
= parse_env_file_internal(f
, fname
, newline
, load_env_file_push_pairs
, &m
, NULL
);
770 static void write_env_var(FILE *f
, const char *v
) {
782 fwrite(v
, 1, p
-v
, f
);
784 if (string_has_cc(p
, NULL
) || chars_intersect(p
, WHITESPACE SHELL_NEED_QUOTES
)) {
788 if (strchr(SHELL_NEED_ESCAPE
, *p
))
801 int write_env_file(const char *fname
, char **l
) {
802 _cleanup_fclose_
FILE *f
= NULL
;
803 _cleanup_free_
char *p
= NULL
;
809 r
= fopen_temporary(fname
, &f
, &p
);
813 fchmod_umask(fileno(f
), 0644);
816 write_env_var(f
, *i
);
818 r
= fflush_and_check(f
);
820 if (rename(p
, fname
) >= 0)
830 int executable_is_script(const char *path
, char **interpreter
) {
832 _cleanup_free_
char *line
= NULL
;
838 r
= read_one_line_file(path
, &line
);
842 if (!startswith(line
, "#!"))
845 ans
= strstrip(line
+ 2);
846 len
= strcspn(ans
, " \t");
851 ans
= strndup(ans
, len
);
860 * Retrieve one field from a file like /proc/self/status. pattern
861 * should not include whitespace or the delimiter (':'). pattern matches only
862 * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
863 * zeros after the ':' will be skipped. field must be freed afterwards.
864 * terminator specifies the terminating characters of the field value (not
865 * included in the value).
867 int get_proc_field(const char *filename
, const char *pattern
, const char *terminator
, char **field
) {
868 _cleanup_free_
char *status
= NULL
;
878 r
= read_full_file(filename
, &status
, NULL
);
888 t
= strstr(t
, pattern
);
892 /* Check that pattern occurs in beginning of line. */
893 pattern_ok
= (t
== status
|| t
[-1] == '\n');
895 t
+= strlen(pattern
);
897 } while (!pattern_ok
);
899 t
+= strspn(t
, " \t");
908 t
+= strspn(t
, " \t");
910 /* Also skip zeros, because when this is used for
911 * capabilities, we don't want the zeros. This way the
912 * same capability set always maps to the same string,
913 * irrespective of the total capability set size. For
914 * other numbers it shouldn't matter. */
916 /* Back off one char if there's nothing but whitespace
918 if (!*t
|| isspace(*t
))
922 len
= strcspn(t
, terminator
);
932 DIR *xopendirat(int fd
, const char *name
, int flags
) {
936 assert(!(flags
& O_CREAT
));
938 nfd
= openat(fd
, name
, O_RDONLY
|O_NONBLOCK
|O_DIRECTORY
|O_CLOEXEC
|flags
, 0);
951 static int search_and_fopen_internal(const char *path
, const char *mode
, const char *root
, char **search
, FILE **_f
) {
958 if (!path_strv_resolve_uniq(search
, root
))
961 STRV_FOREACH(i
, search
) {
962 _cleanup_free_
char *p
= NULL
;
966 p
= strjoin(root
, *i
, "/", path
, NULL
);
968 p
= strjoin(*i
, "/", path
, NULL
);
985 int search_and_fopen(const char *path
, const char *mode
, const char *root
, const char **search
, FILE **_f
) {
986 _cleanup_strv_free_
char **copy
= NULL
;
992 if (path_is_absolute(path
)) {
995 f
= fopen(path
, mode
);
1004 copy
= strv_copy((char**) search
);
1008 return search_and_fopen_internal(path
, mode
, root
, copy
, _f
);
1011 int search_and_fopen_nulstr(const char *path
, const char *mode
, const char *root
, const char *search
, FILE **_f
) {
1012 _cleanup_strv_free_
char **s
= NULL
;
1014 if (path_is_absolute(path
)) {
1017 f
= fopen(path
, mode
);
1026 s
= strv_split_nulstr(search
);
1030 return search_and_fopen_internal(path
, mode
, root
, s
, _f
);
1033 int fopen_temporary(const char *path
, FILE **_f
, char **_temp_path
) {
1042 r
= tempfn_xxxxxx(path
, NULL
, &t
);
1046 fd
= mkostemp_safe(t
, O_WRONLY
|O_CLOEXEC
);
1052 f
= fdopen(fd
, "we");
1066 int fflush_and_check(FILE *f
) {
1073 return errno
> 0 ? -errno
: -EIO
;
1078 /* This is much like mkostemp() but is subject to umask(). */
1079 int mkostemp_safe(char *pattern
, int flags
) {
1080 _cleanup_umask_ mode_t u
= 0;
1087 fd
= mkostemp(pattern
, flags
);
1094 int tempfn_xxxxxx(const char *p
, const char *extra
, char **ret
) {
1106 * /foo/bar/.#<extra>waldoXXXXXX
1110 if (!filename_is_valid(fn
))
1116 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 6 + 1);
1120 strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
), "XXXXXX");
1122 *ret
= path_kill_slashes(t
);
1126 int tempfn_random(const char *p
, const char *extra
, char **ret
) {
1140 * /foo/bar/.#<extra>waldobaa2a261115984a9
1144 if (!filename_is_valid(fn
))
1150 t
= new(char, strlen(p
) + 2 + strlen(extra
) + 16 + 1);
1154 x
= stpcpy(stpcpy(stpcpy(mempcpy(t
, p
, fn
- p
), ".#"), extra
), fn
);
1157 for (i
= 0; i
< 16; i
++) {
1158 *(x
++) = hexchar(u
& 0xF);
1164 *ret
= path_kill_slashes(t
);
1168 int tempfn_random_child(const char *p
, const char *extra
, char **ret
) {
1179 * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1191 t
= new(char, strlen(p
) + 3 + strlen(extra
) + 16 + 1);
1195 x
= stpcpy(stpcpy(stpcpy(t
, p
), "/.#"), extra
);
1198 for (i
= 0; i
< 16; i
++) {
1199 *(x
++) = hexchar(u
& 0xF);
1205 *ret
= path_kill_slashes(t
);
1209 int write_timestamp_file_atomic(const char *fn
, usec_t n
) {
1210 char ln
[DECIMAL_STR_MAX(n
)+2];
1212 /* Creates a "timestamp" file, that contains nothing but a
1213 * usec_t timestamp, formatted in ASCII. */
1215 if (n
<= 0 || n
>= USEC_INFINITY
)
1218 xsprintf(ln
, USEC_FMT
"\n", n
);
1220 return write_string_file(fn
, ln
, WRITE_STRING_FILE_CREATE
|WRITE_STRING_FILE_ATOMIC
);
1223 int read_timestamp_file(const char *fn
, usec_t
*ret
) {
1224 _cleanup_free_
char *ln
= NULL
;
1228 r
= read_one_line_file(fn
, &ln
);
1232 r
= safe_atou64(ln
, &t
);
1236 if (t
<= 0 || t
>= (uint64_t) USEC_INFINITY
)
1243 int fputs_with_space(FILE *f
, const char *s
, const char *separator
, bool *space
) {
1248 /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1249 * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1250 * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1251 * element, but not before the first one. */
1261 r
= fputs(separator
, f
);
1272 int open_tmpfile_unlinkable(const char *directory
, int flags
) {
1277 r
= tmp_dir(&directory
);
1282 /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1284 /* Try O_TMPFILE first, if it is supported */
1285 fd
= open(directory
, flags
|O_TMPFILE
|O_EXCL
, S_IRUSR
|S_IWUSR
);
1289 /* Fall back to unguessable name + unlinking */
1290 p
= strjoina(directory
, "/systemd-tmp-XXXXXX");
1292 fd
= mkostemp_safe(p
, flags
);
1301 int open_tmpfile_linkable(const char *target
, int flags
, char **ret_path
) {
1302 _cleanup_free_
char *tmp
= NULL
;
1308 /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1309 assert((flags
& O_EXCL
) == 0);
1311 /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1312 * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1313 * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1316 _cleanup_free_
char *dn
= NULL
;
1318 dn
= dirname_malloc(target
);
1322 fd
= open(dn
, O_TMPFILE
|flags
, 0640);
1328 log_debug_errno(errno
, "Failed to use O_TMPFILE on %s: %m", dn
);
1331 r
= tempfn_random(target
, NULL
, &tmp
);
1335 fd
= open(tmp
, O_CREAT
|O_EXCL
|O_NOFOLLOW
|O_NOCTTY
|flags
, 0640);
1345 int link_tmpfile(int fd
, const char *path
, const char *target
) {
1350 /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1351 * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1352 * on the directory, and renameat2() is used instead.
1354 * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1355 * operation currently (renameat2() does), and there is no nice way to emulate this. */
1358 if (rename_noreplace(AT_FDCWD
, path
, AT_FDCWD
, target
) < 0)
1361 char proc_fd_path
[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(fd
) + 1];
1363 xsprintf(proc_fd_path
, "/proc/self/fd/%i", fd
);
1365 if (linkat(AT_FDCWD
, proc_fd_path
, AT_FDCWD
, target
, AT_SYMLINK_FOLLOW
) < 0)
1372 int read_nul_string(FILE *f
, char **ret
) {
1373 _cleanup_free_
char *x
= NULL
;
1374 size_t allocated
= 0, n
= 0;
1379 /* Reads a NUL-terminated string from the specified file. */
1384 if (!GREEDY_REALLOC(x
, allocated
, n
+2))
1388 if (c
== 0) /* Terminate at NUL byte */
1393 break; /* Terminate at EOF */