chiark / gitweb /
basic: add new merge_env_file function
[elogind.git] / src / basic / fileio.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010 Lennart Poettering
5
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.
10
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.
15
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/>.
18 ***/
19
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <limits.h>
23 #include <stdarg.h>
24 #include <stdint.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sys/stat.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30
31 #include "alloc-util.h"
32 #include "ctype.h"
33 #include "escape.h"
34 #include "fd-util.h"
35 #include "fileio.h"
36 #include "fs-util.h"
37 #include "hexdecoct.h"
38 //#include "log.h"
39 //#include "macro.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"
45 #include "strv.h"
46 //#include "time-util.h"
47 #include "umask-util.h"
48 #include "utf8.h"
49
50 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
51
52 int write_string_stream(FILE *f, const char *line, bool enforce_newline) {
53
54         assert(f);
55         assert(line);
56
57         fputs(line, f);
58         if (enforce_newline && !endswith(line, "\n"))
59                 fputc('\n', f);
60
61         return fflush_and_check(f);
62 }
63
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;
67         int r;
68
69         assert(fn);
70         assert(line);
71
72         r = fopen_temporary(fn, &f, &p);
73         if (r < 0)
74                 return r;
75
76         (void) fchmod_umask(fileno(f), 0644);
77
78         r = write_string_stream(f, line, enforce_newline);
79         if (r >= 0) {
80                 if (rename(p, fn) < 0)
81                         r = -errno;
82         }
83
84         if (r < 0)
85                 (void) unlink(p);
86
87         return r;
88 }
89
90 int write_string_file(const char *fn, const char *line, WriteStringFileFlags flags) {
91         _cleanup_fclose_ FILE *f = NULL;
92         int q, r;
93
94         assert(fn);
95         assert(line);
96
97         if (flags & WRITE_STRING_FILE_ATOMIC) {
98                 assert(flags & WRITE_STRING_FILE_CREATE);
99
100                 r = write_string_file_atomic(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
101                 if (r < 0)
102                         goto fail;
103
104                 return r;
105         }
106
107         if (flags & WRITE_STRING_FILE_CREATE) {
108                 f = fopen(fn, "we");
109                 if (!f) {
110                         r = -errno;
111                         goto fail;
112                 }
113         } else {
114                 int fd;
115
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);
119                 if (fd < 0) {
120                         r = -errno;
121                         goto fail;
122                 }
123
124                 f = fdopen(fd, "we");
125                 if (!f) {
126                         r = -errno;
127                         safe_close(fd);
128                         goto fail;
129                 }
130         }
131
132         r = write_string_stream(f, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
133         if (r < 0)
134                 goto fail;
135
136         return 0;
137
138 fail:
139         if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
140                 return r;
141
142         f = safe_fclose(f);
143
144         /* OK, the operation failed, but let's see if the right
145          * contents in place already. If so, eat up the error. */
146
147         q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
148         if (q <= 0)
149                 return r;
150
151         return 0;
152 }
153
154 int read_one_line_file(const char *fn, char **line) {
155         _cleanup_fclose_ FILE *f = NULL;
156         char t[LINE_MAX], *c;
157
158         assert(fn);
159         assert(line);
160
161         f = fopen(fn, "re");
162         if (!f)
163                 return -errno;
164
165         if (!fgets(t, sizeof(t), f)) {
166
167                 if (ferror(f))
168                         return errno > 0 ? -errno : -EIO;
169
170                 t[0] = 0;
171         }
172
173         c = strdup(t);
174         if (!c)
175                 return -ENOMEM;
176         truncate_nl(c);
177
178         *line = c;
179         return 0;
180 }
181
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;
185         size_t l, k;
186
187         assert(fn);
188         assert(blob);
189
190         l = strlen(blob);
191
192         if (accept_extra_nl && endswith(blob, "\n"))
193                 accept_extra_nl = false;
194
195         buf = malloc(l + accept_extra_nl + 1);
196         if (!buf)
197                 return -ENOMEM;
198
199         f = fopen(fn, "re");
200         if (!f)
201                 return -errno;
202
203         /* We try to read one byte more than we need, so that we know whether we hit eof */
204         errno = 0;
205         k = fread(buf, 1, l + accept_extra_nl + 1, f);
206         if (ferror(f))
207                 return errno > 0 ? -errno : -EIO;
208
209         if (k != l && k != l + accept_extra_nl)
210                 return 0;
211         if (memcmp(buf, blob, l) != 0)
212                 return 0;
213         if (k > l && buf[l] != '\n')
214                 return 0;
215
216         return 1;
217 }
218
219 int read_full_stream(FILE *f, char **contents, size_t *size) {
220         size_t n, l;
221         _cleanup_free_ char *buf = NULL;
222         struct stat st;
223
224         assert(f);
225         assert(contents);
226
227         if (fstat(fileno(f), &st) < 0)
228                 return -errno;
229
230         n = LINE_MAX;
231
232         if (S_ISREG(st.st_mode)) {
233
234                 /* Safety check */
235                 if (st.st_size > READ_FULL_BYTES_MAX)
236                         return -E2BIG;
237
238                 /* Start with the right file size, but be prepared for
239                  * files from /proc which generally report a file size
240                  * of 0 */
241                 if (st.st_size > 0)
242                         n = st.st_size;
243         }
244
245         l = 0;
246         for (;;) {
247                 char *t;
248                 size_t k;
249
250                 t = realloc(buf, n + 1);
251                 if (!t)
252                         return -ENOMEM;
253
254                 buf = t;
255                 k = fread(buf + l, 1, n - l, f);
256                 if (k > 0)
257                         l += k;
258
259                 if (ferror(f))
260                         return -errno;
261
262                 if (feof(f))
263                         break;
264
265                 /* We aren't expecting fread() to return a short read outside
266                  * of (error && eof), assert buffer is full and enlarge buffer.
267                  */
268                 assert(l == n);
269
270                 /* Safety check */
271                 if (n >= READ_FULL_BYTES_MAX)
272                         return -E2BIG;
273
274                 n = MIN(n * 2, READ_FULL_BYTES_MAX);
275         }
276
277         buf[l] = 0;
278         *contents = buf;
279         buf = NULL; /* do not free */
280
281         if (size)
282                 *size = l;
283
284         return 0;
285 }
286
287 int read_full_file(const char *fn, char **contents, size_t *size) {
288         _cleanup_fclose_ FILE *f = NULL;
289
290         assert(fn);
291         assert(contents);
292
293         f = fopen(fn, "re");
294         if (!f)
295                 return -errno;
296
297         return read_full_stream(f, contents, size);
298 }
299
300 static int parse_env_file_internal(
301                 FILE *f,
302                 const char *fname,
303                 const char *newline,
304                 int (*push) (const char *filename, unsigned line,
305                              const char *key, char *value, void *userdata, int *n_pushed),
306                 void *userdata,
307                 int *n_pushed) {
308
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;
312         int r;
313         unsigned line = 1;
314
315         enum {
316                 PRE_KEY,
317                 KEY,
318                 PRE_VALUE,
319                 VALUE,
320                 VALUE_ESCAPE,
321                 SINGLE_QUOTE_VALUE,
322                 SINGLE_QUOTE_VALUE_ESCAPE,
323                 DOUBLE_QUOTE_VALUE,
324                 DOUBLE_QUOTE_VALUE_ESCAPE,
325                 COMMENT,
326                 COMMENT_ESCAPE
327         } state = PRE_KEY;
328
329         assert(newline);
330
331         if (f)
332                 r = read_full_stream(f, &contents, NULL);
333         else
334                 r = read_full_file(fname, &contents, NULL);
335         if (r < 0)
336                 return r;
337
338         for (p = contents; *p; p++) {
339                 char c = *p;
340
341                 switch (state) {
342
343                 case PRE_KEY:
344                         if (strchr(COMMENTS, c))
345                                 state = COMMENT;
346                         else if (!strchr(WHITESPACE, c)) {
347                                 state = KEY;
348                                 last_key_whitespace = (size_t) -1;
349
350                                 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
351                                         r = -ENOMEM;
352                                         goto fail;
353                                 }
354
355                                 key[n_key++] = c;
356                         }
357                         break;
358
359                 case KEY:
360                         if (strchr(newline, c)) {
361                                 state = PRE_KEY;
362                                 line++;
363                                 n_key = 0;
364                         } else if (c == '=') {
365                                 state = PRE_VALUE;
366                                 last_value_whitespace = (size_t) -1;
367                         } else {
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;
372
373                                 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
374                                         r = -ENOMEM;
375                                         goto fail;
376                                 }
377
378                                 key[n_key++] = c;
379                         }
380
381                         break;
382
383                 case PRE_VALUE:
384                         if (strchr(newline, c)) {
385                                 state = PRE_KEY;
386                                 line++;
387                                 key[n_key] = 0;
388
389                                 if (value)
390                                         value[n_value] = 0;
391
392                                 /* strip trailing whitespace from key */
393                                 if (last_key_whitespace != (size_t) -1)
394                                         key[last_key_whitespace] = 0;
395
396                                 r = push(fname, line, key, value, userdata, n_pushed);
397                                 if (r < 0)
398                                         goto fail;
399
400                                 n_key = 0;
401                                 value = NULL;
402                                 value_alloc = n_value = 0;
403
404                         } else if (c == '\'')
405                                 state = SINGLE_QUOTE_VALUE;
406                         else if (c == '\"')
407                                 state = DOUBLE_QUOTE_VALUE;
408                         else if (c == '\\')
409                                 state = VALUE_ESCAPE;
410                         else if (!strchr(WHITESPACE, c)) {
411                                 state = VALUE;
412
413                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
414                                         r = -ENOMEM;
415                                         goto fail;
416                                 }
417
418                                 value[n_value++] = c;
419                         }
420
421                         break;
422
423                 case VALUE:
424                         if (strchr(newline, c)) {
425                                 state = PRE_KEY;
426                                 line++;
427
428                                 key[n_key] = 0;
429
430                                 if (value)
431                                         value[n_value] = 0;
432
433                                 /* Chomp off trailing whitespace from value */
434                                 if (last_value_whitespace != (size_t) -1)
435                                         value[last_value_whitespace] = 0;
436
437                                 /* strip trailing whitespace from key */
438                                 if (last_key_whitespace != (size_t) -1)
439                                         key[last_key_whitespace] = 0;
440
441                                 r = push(fname, line, key, value, userdata, n_pushed);
442                                 if (r < 0)
443                                         goto fail;
444
445                                 n_key = 0;
446                                 value = NULL;
447                                 value_alloc = n_value = 0;
448
449                         } else if (c == '\\') {
450                                 state = VALUE_ESCAPE;
451                                 last_value_whitespace = (size_t) -1;
452                         } else {
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;
457
458                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
459                                         r = -ENOMEM;
460                                         goto fail;
461                                 }
462
463                                 value[n_value++] = c;
464                         }
465
466                         break;
467
468                 case VALUE_ESCAPE:
469                         state = VALUE;
470
471                         if (!strchr(newline, c)) {
472                                 /* Escaped newlines we eat up entirely */
473                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
474                                         r = -ENOMEM;
475                                         goto fail;
476                                 }
477
478                                 value[n_value++] = c;
479                         }
480                         break;
481
482                 case SINGLE_QUOTE_VALUE:
483                         if (c == '\'')
484                                 state = PRE_VALUE;
485                         else if (c == '\\')
486                                 state = SINGLE_QUOTE_VALUE_ESCAPE;
487                         else {
488                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
489                                         r = -ENOMEM;
490                                         goto fail;
491                                 }
492
493                                 value[n_value++] = c;
494                         }
495
496                         break;
497
498                 case SINGLE_QUOTE_VALUE_ESCAPE:
499                         state = SINGLE_QUOTE_VALUE;
500
501                         if (!strchr(newline, c)) {
502                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
503                                         r = -ENOMEM;
504                                         goto fail;
505                                 }
506
507                                 value[n_value++] = c;
508                         }
509                         break;
510
511                 case DOUBLE_QUOTE_VALUE:
512                         if (c == '\"')
513                                 state = PRE_VALUE;
514                         else if (c == '\\')
515                                 state = DOUBLE_QUOTE_VALUE_ESCAPE;
516                         else {
517                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
518                                         r = -ENOMEM;
519                                         goto fail;
520                                 }
521
522                                 value[n_value++] = c;
523                         }
524
525                         break;
526
527                 case DOUBLE_QUOTE_VALUE_ESCAPE:
528                         state = DOUBLE_QUOTE_VALUE;
529
530                         if (!strchr(newline, c)) {
531                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
532                                         r = -ENOMEM;
533                                         goto fail;
534                                 }
535
536                                 value[n_value++] = c;
537                         }
538                         break;
539
540                 case COMMENT:
541                         if (c == '\\')
542                                 state = COMMENT_ESCAPE;
543                         else if (strchr(newline, c)) {
544                                 state = PRE_KEY;
545                                 line++;
546                         }
547                         break;
548
549                 case COMMENT_ESCAPE:
550                         state = COMMENT;
551                         break;
552                 }
553         }
554
555         if (state == PRE_VALUE ||
556             state == 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) {
562
563                 key[n_key] = 0;
564
565                 if (value)
566                         value[n_value] = 0;
567
568                 if (state == VALUE)
569                         if (last_value_whitespace != (size_t) -1)
570                                 value[last_value_whitespace] = 0;
571
572                 /* strip trailing whitespace from key */
573                 if (last_key_whitespace != (size_t) -1)
574                         key[last_key_whitespace] = 0;
575
576                 r = push(fname, line, key, value, userdata, n_pushed);
577                 if (r < 0)
578                         goto fail;
579         }
580
581         return 0;
582
583 fail:
584         free(value);
585         return r;
586 }
587
588 static int parse_env_file_push(
589                 const char *filename, unsigned line,
590                 const char *key, char *value,
591                 void *userdata,
592                 int *n_pushed) {
593
594         const char *k;
595         va_list aq, *ap = userdata;
596
597         if (!utf8_is_valid(key)) {
598                 _cleanup_free_ char *p = NULL;
599
600                 p = utf8_escape_invalid(key);
601                 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
602                 return -EINVAL;
603         }
604
605         if (value && !utf8_is_valid(value)) {
606                 _cleanup_free_ char *p = NULL;
607
608                 p = utf8_escape_invalid(value);
609                 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
610                 return -EINVAL;
611         }
612
613         va_copy(aq, *ap);
614
615         while ((k = va_arg(aq, const char *))) {
616                 char **v;
617
618                 v = va_arg(aq, char **);
619
620                 if (streq(key, k)) {
621                         va_end(aq);
622                         free(*v);
623                         *v = value;
624
625                         if (n_pushed)
626                                 (*n_pushed)++;
627
628                         return 1;
629                 }
630         }
631
632         va_end(aq);
633         free(value);
634
635         return 0;
636 }
637
638 int parse_env_file(
639                 const char *fname,
640                 const char *newline, ...) {
641
642         va_list ap;
643         int r, n_pushed = 0;
644
645         if (!newline)
646                 newline = NEWLINE;
647
648         va_start(ap, newline);
649         r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
650         va_end(ap);
651
652         return r < 0 ? r : n_pushed;
653 }
654
655 #if 0 /// UNNEEDED by elogind
656 static int load_env_file_push(
657                 const char *filename, unsigned line,
658                 const char *key, char *value,
659                 void *userdata,
660                 int *n_pushed) {
661         char ***m = userdata;
662         char *p;
663         int r;
664
665         if (!utf8_is_valid(key)) {
666                 _cleanup_free_ char *t = utf8_escape_invalid(key);
667
668                 log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename), line, t);
669                 return -EINVAL;
670         }
671
672         if (value && !utf8_is_valid(value)) {
673                 _cleanup_free_ char *t = utf8_escape_invalid(value);
674
675                 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, t);
676                 return -EINVAL;
677         }
678
679         p = strjoin(key, "=", strempty(value), NULL);
680         if (!p)
681                 return -ENOMEM;
682
683         r = strv_consume(m, p);
684         if (r < 0)
685                 return r;
686
687         if (n_pushed)
688                 (*n_pushed)++;
689
690         free(value);
691         return 0;
692 }
693
694 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
695         char **m = NULL;
696         int r;
697
698         if (!newline)
699                 newline = NEWLINE;
700
701         r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
702         if (r < 0) {
703                 strv_free(m);
704                 return r;
705         }
706
707         *rl = m;
708         return 0;
709 }
710
711 static int load_env_file_push_pairs(
712                 const char *filename, unsigned line,
713                 const char *key, char *value,
714                 void *userdata,
715                 int *n_pushed) {
716         char ***m = userdata;
717         int r;
718
719         if (!utf8_is_valid(key)) {
720                 _cleanup_free_ char *t = utf8_escape_invalid(key);
721
722                 log_error("%s:%u: invalid UTF-8 for key '%s', ignoring.", strna(filename), line, t);
723                 return -EINVAL;
724         }
725
726         if (value && !utf8_is_valid(value)) {
727                 _cleanup_free_ char *t = utf8_escape_invalid(value);
728
729                 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, t);
730                 return -EINVAL;
731         }
732
733         r = strv_extend(m, key);
734         if (r < 0)
735                 return -ENOMEM;
736
737         if (!value) {
738                 r = strv_extend(m, "");
739                 if (r < 0)
740                         return -ENOMEM;
741         } else {
742                 r = strv_push(m, value);
743                 if (r < 0)
744                         return r;
745         }
746
747         if (n_pushed)
748                 (*n_pushed)++;
749
750         return 0;
751 }
752
753 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
754         char **m = NULL;
755         int r;
756
757         if (!newline)
758                 newline = NEWLINE;
759
760         r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
761         if (r < 0) {
762                 strv_free(m);
763                 return r;
764         }
765
766         *rl = m;
767         return 0;
768 }
769
770 static int merge_env_file_push(
771                 const char *filename, unsigned line,
772                 const char *key, char *value,
773                 void *userdata,
774                 int *n_pushed) {
775
776         char ***env = userdata;
777         char *expanded_value;
778
779         assert(env);
780
781         expanded_value = replace_env(value, *env, REPLACE_ENV_USE_ENVIRONMENT);
782         if (!expanded_value)
783                 return -ENOMEM;
784
785         free_and_replace(value, expanded_value);
786
787         return load_env_file_push(filename, line, key, value, env, n_pushed);
788 }
789
790 int merge_env_file(
791                 char ***env,
792                 FILE *f,
793                 const char *fname) {
794
795         return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
796 }
797
798 static void write_env_var(FILE *f, const char *v) {
799         const char *p;
800
801         p = strchr(v, '=');
802         if (!p) {
803                 /* Fallback */
804                 fputs(v, f);
805                 fputc('\n', f);
806                 return;
807         }
808
809         p++;
810         fwrite(v, 1, p-v, f);
811
812         if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
813                 fputc('\"', f);
814
815                 for (; *p; p++) {
816                         if (strchr(SHELL_NEED_ESCAPE, *p))
817                                 fputc('\\', f);
818
819                         fputc(*p, f);
820                 }
821
822                 fputc('\"', f);
823         } else
824                 fputs(p, f);
825
826         fputc('\n', f);
827 }
828
829 int write_env_file(const char *fname, char **l) {
830         _cleanup_fclose_ FILE *f = NULL;
831         _cleanup_free_ char *p = NULL;
832         char **i;
833         int r;
834
835         assert(fname);
836
837         r = fopen_temporary(fname, &f, &p);
838         if (r < 0)
839                 return r;
840
841         fchmod_umask(fileno(f), 0644);
842
843         STRV_FOREACH(i, l)
844                 write_env_var(f, *i);
845
846         r = fflush_and_check(f);
847         if (r >= 0) {
848                 if (rename(p, fname) >= 0)
849                         return 0;
850
851                 r = -errno;
852         }
853
854         unlink(p);
855         return r;
856 }
857
858 int executable_is_script(const char *path, char **interpreter) {
859         int r;
860         _cleanup_free_ char *line = NULL;
861         int len;
862         char *ans;
863
864         assert(path);
865
866         r = read_one_line_file(path, &line);
867         if (r < 0)
868                 return r;
869
870         if (!startswith(line, "#!"))
871                 return 0;
872
873         ans = strstrip(line + 2);
874         len = strcspn(ans, " \t");
875
876         if (len == 0)
877                 return 0;
878
879         ans = strndup(ans, len);
880         if (!ans)
881                 return -ENOMEM;
882
883         *interpreter = ans;
884         return 1;
885 }
886 #endif // 0
887
888 /**
889  * Retrieve one field from a file like /proc/self/status.  pattern
890  * should not include whitespace or the delimiter (':'). pattern matches only
891  * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
892  * zeros after the ':' will be skipped. field must be freed afterwards.
893  * terminator specifies the terminating characters of the field value (not
894  * included in the value).
895  */
896 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
897         _cleanup_free_ char *status = NULL;
898         char *t, *f;
899         size_t len;
900         int r;
901
902         assert(terminator);
903         assert(filename);
904         assert(pattern);
905         assert(field);
906
907         r = read_full_file(filename, &status, NULL);
908         if (r < 0)
909                 return r;
910
911         t = status;
912
913         do {
914                 bool pattern_ok;
915
916                 do {
917                         t = strstr(t, pattern);
918                         if (!t)
919                                 return -ENOENT;
920
921                         /* Check that pattern occurs in beginning of line. */
922                         pattern_ok = (t == status || t[-1] == '\n');
923
924                         t += strlen(pattern);
925
926                 } while (!pattern_ok);
927
928                 t += strspn(t, " \t");
929                 if (!*t)
930                         return -ENOENT;
931
932         } while (*t != ':');
933
934         t++;
935
936         if (*t) {
937                 t += strspn(t, " \t");
938
939                 /* Also skip zeros, because when this is used for
940                  * capabilities, we don't want the zeros. This way the
941                  * same capability set always maps to the same string,
942                  * irrespective of the total capability set size. For
943                  * other numbers it shouldn't matter. */
944                 t += strspn(t, "0");
945                 /* Back off one char if there's nothing but whitespace
946                    and zeros */
947                 if (!*t || isspace(*t))
948                         t--;
949         }
950
951         len = strcspn(t, terminator);
952
953         f = strndup(t, len);
954         if (!f)
955                 return -ENOMEM;
956
957         *field = f;
958         return 0;
959 }
960
961 DIR *xopendirat(int fd, const char *name, int flags) {
962         int nfd;
963         DIR *d;
964
965         assert(!(flags & O_CREAT));
966
967         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
968         if (nfd < 0)
969                 return NULL;
970
971         d = fdopendir(nfd);
972         if (!d) {
973                 safe_close(nfd);
974                 return NULL;
975         }
976
977         return d;
978 }
979
980 #if 0 /// UNNEEDED by elogind
981 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
982         char **i;
983
984         assert(path);
985         assert(mode);
986         assert(_f);
987
988         if (!path_strv_resolve_uniq(search, root))
989                 return -ENOMEM;
990
991         STRV_FOREACH(i, search) {
992                 _cleanup_free_ char *p = NULL;
993                 FILE *f;
994
995                 if (root)
996                         p = strjoin(root, *i, "/", path, NULL);
997                 else
998                         p = strjoin(*i, "/", path, NULL);
999                 if (!p)
1000                         return -ENOMEM;
1001
1002                 f = fopen(p, mode);
1003                 if (f) {
1004                         *_f = f;
1005                         return 0;
1006                 }
1007
1008                 if (errno != ENOENT)
1009                         return -errno;
1010         }
1011
1012         return -ENOENT;
1013 }
1014
1015 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1016         _cleanup_strv_free_ char **copy = NULL;
1017
1018         assert(path);
1019         assert(mode);
1020         assert(_f);
1021
1022         if (path_is_absolute(path)) {
1023                 FILE *f;
1024
1025                 f = fopen(path, mode);
1026                 if (f) {
1027                         *_f = f;
1028                         return 0;
1029                 }
1030
1031                 return -errno;
1032         }
1033
1034         copy = strv_copy((char**) search);
1035         if (!copy)
1036                 return -ENOMEM;
1037
1038         return search_and_fopen_internal(path, mode, root, copy, _f);
1039 }
1040
1041 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1042         _cleanup_strv_free_ char **s = NULL;
1043
1044         if (path_is_absolute(path)) {
1045                 FILE *f;
1046
1047                 f = fopen(path, mode);
1048                 if (f) {
1049                         *_f = f;
1050                         return 0;
1051                 }
1052
1053                 return -errno;
1054         }
1055
1056         s = strv_split_nulstr(search);
1057         if (!s)
1058                 return -ENOMEM;
1059
1060         return search_and_fopen_internal(path, mode, root, s, _f);
1061 }
1062 #endif // 0
1063
1064 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1065         FILE *f;
1066         char *t;
1067         int r, fd;
1068
1069         assert(path);
1070         assert(_f);
1071         assert(_temp_path);
1072
1073         r = tempfn_xxxxxx(path, NULL, &t);
1074         if (r < 0)
1075                 return r;
1076
1077         fd = mkostemp_safe(t);
1078         if (fd < 0) {
1079                 free(t);
1080                 return -errno;
1081         }
1082
1083         f = fdopen(fd, "we");
1084         if (!f) {
1085                 unlink_noerrno(t);
1086                 free(t);
1087                 safe_close(fd);
1088                 return -errno;
1089         }
1090
1091         *_f = f;
1092         *_temp_path = t;
1093
1094         return 0;
1095 }
1096
1097 int fflush_and_check(FILE *f) {
1098         assert(f);
1099
1100         errno = 0;
1101         fflush(f);
1102
1103         if (ferror(f))
1104                 return errno > 0 ? -errno : -EIO;
1105
1106         return 0;
1107 }
1108
1109 /* This is much like mkostemp() but is subject to umask(). */
1110 int mkostemp_safe(char *pattern) {
1111         _cleanup_umask_ mode_t u = 0;
1112         int fd;
1113
1114         assert(pattern);
1115
1116         u = umask(077);
1117
1118         fd = mkostemp(pattern, O_CLOEXEC);
1119         if (fd < 0)
1120                 return -errno;
1121
1122         return fd;
1123 }
1124
1125 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1126         const char *fn;
1127         char *t;
1128
1129         assert(p);
1130         assert(ret);
1131
1132         /*
1133          * Turns this:
1134          *         /foo/bar/waldo
1135          *
1136          * Into this:
1137          *         /foo/bar/.#<extra>waldoXXXXXX
1138          */
1139
1140         fn = basename(p);
1141         if (!filename_is_valid(fn))
1142                 return -EINVAL;
1143
1144         if (extra == NULL)
1145                 extra = "";
1146
1147         t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1148         if (!t)
1149                 return -ENOMEM;
1150
1151         strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1152
1153         *ret = path_kill_slashes(t);
1154         return 0;
1155 }
1156
1157 int tempfn_random(const char *p, const char *extra, char **ret) {
1158         const char *fn;
1159         char *t, *x;
1160         uint64_t u;
1161         unsigned i;
1162
1163         assert(p);
1164         assert(ret);
1165
1166         /*
1167          * Turns this:
1168          *         /foo/bar/waldo
1169          *
1170          * Into this:
1171          *         /foo/bar/.#<extra>waldobaa2a261115984a9
1172          */
1173
1174         fn = basename(p);
1175         if (!filename_is_valid(fn))
1176                 return -EINVAL;
1177
1178         if (!extra)
1179                 extra = "";
1180
1181         t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1182         if (!t)
1183                 return -ENOMEM;
1184
1185         x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1186
1187         u = random_u64();
1188         for (i = 0; i < 16; i++) {
1189                 *(x++) = hexchar(u & 0xF);
1190                 u >>= 4;
1191         }
1192
1193         *x = 0;
1194
1195         *ret = path_kill_slashes(t);
1196         return 0;
1197 }
1198
1199 #if 0 /// UNNEEDED by elogind
1200 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1201         char *t, *x;
1202         uint64_t u;
1203         unsigned i;
1204         int r;
1205
1206         assert(ret);
1207
1208         /* Turns this:
1209          *         /foo/bar/waldo
1210          * Into this:
1211          *         /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1212          */
1213
1214         if (!p) {
1215                 r = tmp_dir(&p);
1216                 if (r < 0)
1217                         return r;
1218         }
1219
1220         if (!extra)
1221                 extra = "";
1222
1223         t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1224         if (!t)
1225                 return -ENOMEM;
1226
1227         x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1228
1229         u = random_u64();
1230         for (i = 0; i < 16; i++) {
1231                 *(x++) = hexchar(u & 0xF);
1232                 u >>= 4;
1233         }
1234
1235         *x = 0;
1236
1237         *ret = path_kill_slashes(t);
1238         return 0;
1239 }
1240
1241 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1242         char ln[DECIMAL_STR_MAX(n)+2];
1243
1244         /* Creates a "timestamp" file, that contains nothing but a
1245          * usec_t timestamp, formatted in ASCII. */
1246
1247         if (n <= 0 || n >= USEC_INFINITY)
1248                 return -ERANGE;
1249
1250         xsprintf(ln, USEC_FMT "\n", n);
1251
1252         return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1253 }
1254
1255 int read_timestamp_file(const char *fn, usec_t *ret) {
1256         _cleanup_free_ char *ln = NULL;
1257         uint64_t t;
1258         int r;
1259
1260         r = read_one_line_file(fn, &ln);
1261         if (r < 0)
1262                 return r;
1263
1264         r = safe_atou64(ln, &t);
1265         if (r < 0)
1266                 return r;
1267
1268         if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1269                 return -ERANGE;
1270
1271         *ret = (usec_t) t;
1272         return 0;
1273 }
1274
1275 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1276         int r;
1277
1278         assert(s);
1279
1280         /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1281          * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1282          * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1283          * element, but not before the first one. */
1284
1285         if (!f)
1286                 f = stdout;
1287
1288         if (space) {
1289                 if (!separator)
1290                         separator = " ";
1291
1292                 if (*space) {
1293                         r = fputs(separator, f);
1294                         if (r < 0)
1295                                 return r;
1296                 }
1297
1298                 *space = true;
1299         }
1300
1301         return fputs(s, f);
1302 }
1303
1304 int open_tmpfile_unlinkable(const char *directory, int flags) {
1305         char *p;
1306         int fd, r;
1307
1308         if (!directory) {
1309                 r = tmp_dir(&directory);
1310                 if (r < 0)
1311                         return r;
1312         }
1313
1314         /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1315
1316         /* Try O_TMPFILE first, if it is supported */
1317         fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1318         if (fd >= 0)
1319                 return fd;
1320
1321         /* Fall back to unguessable name + unlinking */
1322         p = strjoina(directory, "/systemd-tmp-XXXXXX");
1323
1324         fd = mkostemp_safe(p);
1325         if (fd < 0)
1326                 return fd;
1327
1328         (void) unlink(p);
1329
1330         return fd;
1331 }
1332
1333 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1334         _cleanup_free_ char *tmp = NULL;
1335         int r, fd;
1336
1337         assert(target);
1338         assert(ret_path);
1339
1340         /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1341         assert((flags & O_EXCL) == 0);
1342
1343         /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1344          * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1345          * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1346
1347         {
1348                 _cleanup_free_ char *dn = NULL;
1349
1350                 dn = dirname_malloc(target);
1351                 if (!dn)
1352                         return -ENOMEM;
1353
1354                 fd = open(dn, O_TMPFILE|flags, 0640);
1355                 if (fd >= 0) {
1356                         *ret_path = NULL;
1357                         return fd;
1358                 }
1359
1360                 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1361         }
1362
1363         r = tempfn_random(target, NULL, &tmp);
1364         if (r < 0)
1365                 return r;
1366
1367         fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1368         if (fd < 0)
1369                 return -errno;
1370
1371         *ret_path = tmp;
1372         tmp = NULL;
1373
1374         return fd;
1375 }
1376
1377 int link_tmpfile(int fd, const char *path, const char *target) {
1378
1379         assert(fd >= 0);
1380         assert(target);
1381
1382         /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1383          * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1384          * on the directory, and renameat2() is used instead.
1385          *
1386          * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1387          * operation currently (renameat2() does), and there is no nice way to emulate this. */
1388
1389         if (path) {
1390                 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1391                         return -errno;
1392         } else {
1393                 char proc_fd_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1394
1395                 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1396
1397                 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1398                         return -errno;
1399         }
1400
1401         return 0;
1402 }
1403 #endif // 0
1404
1405 int read_nul_string(FILE *f, char **ret) {
1406         _cleanup_free_ char *x = NULL;
1407         size_t allocated = 0, n = 0;
1408
1409         assert(f);
1410         assert(ret);
1411
1412         /* Reads a NUL-terminated string from the specified file. */
1413
1414         for (;;) {
1415                 int c;
1416
1417                 if (!GREEDY_REALLOC(x, allocated, n+2))
1418                         return -ENOMEM;
1419
1420                 c = fgetc(f);
1421                 if (c == 0) /* Terminate at NUL byte */
1422                         break;
1423                 if (c == EOF) {
1424                         if (ferror(f))
1425                                 return -errno;
1426                         break; /* Terminate at EOF */
1427                 }
1428
1429                 x[n++] = (char) c;
1430         }
1431
1432         if (x)
1433                 x[n] = 0;
1434         else {
1435                 x = new0(char, 1);
1436                 if (!x)
1437                         return -ENOMEM;
1438         }
1439
1440         *ret = x;
1441         x = NULL;
1442
1443         return 0;
1444 }