chiark / gitweb /
util-lib: add easy helpers for temporary directories that rmdir()ed via _cleanup_
[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));
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 void write_env_var(FILE *f, const char *v) {
771         const char *p;
772
773         p = strchr(v, '=');
774         if (!p) {
775                 /* Fallback */
776                 fputs(v, f);
777                 fputc('\n', f);
778                 return;
779         }
780
781         p++;
782         fwrite(v, 1, p-v, f);
783
784         if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
785                 fputc('\"', f);
786
787                 for (; *p; p++) {
788                         if (strchr(SHELL_NEED_ESCAPE, *p))
789                                 fputc('\\', f);
790
791                         fputc(*p, f);
792                 }
793
794                 fputc('\"', f);
795         } else
796                 fputs(p, f);
797
798         fputc('\n', f);
799 }
800
801 int write_env_file(const char *fname, char **l) {
802         _cleanup_fclose_ FILE *f = NULL;
803         _cleanup_free_ char *p = NULL;
804         char **i;
805         int r;
806
807         assert(fname);
808
809         r = fopen_temporary(fname, &f, &p);
810         if (r < 0)
811                 return r;
812
813         fchmod_umask(fileno(f), 0644);
814
815         STRV_FOREACH(i, l)
816                 write_env_var(f, *i);
817
818         r = fflush_and_check(f);
819         if (r >= 0) {
820                 if (rename(p, fname) >= 0)
821                         return 0;
822
823                 r = -errno;
824         }
825
826         unlink(p);
827         return r;
828 }
829
830 int executable_is_script(const char *path, char **interpreter) {
831         int r;
832         _cleanup_free_ char *line = NULL;
833         int len;
834         char *ans;
835
836         assert(path);
837
838         r = read_one_line_file(path, &line);
839         if (r < 0)
840                 return r;
841
842         if (!startswith(line, "#!"))
843                 return 0;
844
845         ans = strstrip(line + 2);
846         len = strcspn(ans, " \t");
847
848         if (len == 0)
849                 return 0;
850
851         ans = strndup(ans, len);
852         if (!ans)
853                 return -ENOMEM;
854
855         *interpreter = ans;
856         return 1;
857 }
858 #endif // 0
859
860 /**
861  * Retrieve one field from a file like /proc/self/status.  pattern
862  * should not include whitespace or the delimiter (':'). pattern matches only
863  * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
864  * zeros after the ':' will be skipped. field must be freed afterwards.
865  * terminator specifies the terminating characters of the field value (not
866  * included in the value).
867  */
868 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
869         _cleanup_free_ char *status = NULL;
870         char *t, *f;
871         size_t len;
872         int r;
873
874         assert(terminator);
875         assert(filename);
876         assert(pattern);
877         assert(field);
878
879         r = read_full_file(filename, &status, NULL);
880         if (r < 0)
881                 return r;
882
883         t = status;
884
885         do {
886                 bool pattern_ok;
887
888                 do {
889                         t = strstr(t, pattern);
890                         if (!t)
891                                 return -ENOENT;
892
893                         /* Check that pattern occurs in beginning of line. */
894                         pattern_ok = (t == status || t[-1] == '\n');
895
896                         t += strlen(pattern);
897
898                 } while (!pattern_ok);
899
900                 t += strspn(t, " \t");
901                 if (!*t)
902                         return -ENOENT;
903
904         } while (*t != ':');
905
906         t++;
907
908         if (*t) {
909                 t += strspn(t, " \t");
910
911                 /* Also skip zeros, because when this is used for
912                  * capabilities, we don't want the zeros. This way the
913                  * same capability set always maps to the same string,
914                  * irrespective of the total capability set size. For
915                  * other numbers it shouldn't matter. */
916                 t += strspn(t, "0");
917                 /* Back off one char if there's nothing but whitespace
918                    and zeros */
919                 if (!*t || isspace(*t))
920                         t--;
921         }
922
923         len = strcspn(t, terminator);
924
925         f = strndup(t, len);
926         if (!f)
927                 return -ENOMEM;
928
929         *field = f;
930         return 0;
931 }
932
933 DIR *xopendirat(int fd, const char *name, int flags) {
934         int nfd;
935         DIR *d;
936
937         assert(!(flags & O_CREAT));
938
939         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
940         if (nfd < 0)
941                 return NULL;
942
943         d = fdopendir(nfd);
944         if (!d) {
945                 safe_close(nfd);
946                 return NULL;
947         }
948
949         return d;
950 }
951
952 #if 0 /// UNNEEDED by elogind
953 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
954         char **i;
955
956         assert(path);
957         assert(mode);
958         assert(_f);
959
960         if (!path_strv_resolve_uniq(search, root))
961                 return -ENOMEM;
962
963         STRV_FOREACH(i, search) {
964                 _cleanup_free_ char *p = NULL;
965                 FILE *f;
966
967                 if (root)
968                         p = strjoin(root, *i, "/", path);
969                 else
970                         p = strjoin(*i, "/", path);
971                 if (!p)
972                         return -ENOMEM;
973
974                 f = fopen(p, mode);
975                 if (f) {
976                         *_f = f;
977                         return 0;
978                 }
979
980                 if (errno != ENOENT)
981                         return -errno;
982         }
983
984         return -ENOENT;
985 }
986
987 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
988         _cleanup_strv_free_ char **copy = NULL;
989
990         assert(path);
991         assert(mode);
992         assert(_f);
993
994         if (path_is_absolute(path)) {
995                 FILE *f;
996
997                 f = fopen(path, mode);
998                 if (f) {
999                         *_f = f;
1000                         return 0;
1001                 }
1002
1003                 return -errno;
1004         }
1005
1006         copy = strv_copy((char**) search);
1007         if (!copy)
1008                 return -ENOMEM;
1009
1010         return search_and_fopen_internal(path, mode, root, copy, _f);
1011 }
1012
1013 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1014         _cleanup_strv_free_ char **s = NULL;
1015
1016         if (path_is_absolute(path)) {
1017                 FILE *f;
1018
1019                 f = fopen(path, mode);
1020                 if (f) {
1021                         *_f = f;
1022                         return 0;
1023                 }
1024
1025                 return -errno;
1026         }
1027
1028         s = strv_split_nulstr(search);
1029         if (!s)
1030                 return -ENOMEM;
1031
1032         return search_and_fopen_internal(path, mode, root, s, _f);
1033 }
1034 #endif // 0
1035
1036 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1037         FILE *f;
1038         char *t;
1039         int r, fd;
1040
1041         assert(path);
1042         assert(_f);
1043         assert(_temp_path);
1044
1045         r = tempfn_xxxxxx(path, NULL, &t);
1046         if (r < 0)
1047                 return r;
1048
1049         fd = mkostemp_safe(t);
1050         if (fd < 0) {
1051                 free(t);
1052                 return -errno;
1053         }
1054
1055         f = fdopen(fd, "we");
1056         if (!f) {
1057                 unlink_noerrno(t);
1058                 free(t);
1059                 safe_close(fd);
1060                 return -errno;
1061         }
1062
1063         *_f = f;
1064         *_temp_path = t;
1065
1066         return 0;
1067 }
1068
1069 int fflush_and_check(FILE *f) {
1070         assert(f);
1071
1072         errno = 0;
1073         fflush(f);
1074
1075         if (ferror(f))
1076                 return errno > 0 ? -errno : -EIO;
1077
1078         return 0;
1079 }
1080
1081 /* This is much like mkostemp() but is subject to umask(). */
1082 int mkostemp_safe(char *pattern) {
1083         _cleanup_umask_ mode_t u = 0;
1084         int fd;
1085
1086         assert(pattern);
1087
1088         u = umask(077);
1089
1090         fd = mkostemp(pattern, O_CLOEXEC);
1091         if (fd < 0)
1092                 return -errno;
1093
1094         return fd;
1095 }
1096
1097 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1098         const char *fn;
1099         char *t;
1100
1101         assert(p);
1102         assert(ret);
1103
1104         /*
1105          * Turns this:
1106          *         /foo/bar/waldo
1107          *
1108          * Into this:
1109          *         /foo/bar/.#<extra>waldoXXXXXX
1110          */
1111
1112         fn = basename(p);
1113         if (!filename_is_valid(fn))
1114                 return -EINVAL;
1115
1116         if (extra == NULL)
1117                 extra = "";
1118
1119         t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1120         if (!t)
1121                 return -ENOMEM;
1122
1123         strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1124
1125         *ret = path_kill_slashes(t);
1126         return 0;
1127 }
1128
1129 int tempfn_random(const char *p, const char *extra, char **ret) {
1130         const char *fn;
1131         char *t, *x;
1132         uint64_t u;
1133         unsigned i;
1134
1135         assert(p);
1136         assert(ret);
1137
1138         /*
1139          * Turns this:
1140          *         /foo/bar/waldo
1141          *
1142          * Into this:
1143          *         /foo/bar/.#<extra>waldobaa2a261115984a9
1144          */
1145
1146         fn = basename(p);
1147         if (!filename_is_valid(fn))
1148                 return -EINVAL;
1149
1150         if (!extra)
1151                 extra = "";
1152
1153         t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1154         if (!t)
1155                 return -ENOMEM;
1156
1157         x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1158
1159         u = random_u64();
1160         for (i = 0; i < 16; i++) {
1161                 *(x++) = hexchar(u & 0xF);
1162                 u >>= 4;
1163         }
1164
1165         *x = 0;
1166
1167         *ret = path_kill_slashes(t);
1168         return 0;
1169 }
1170
1171 #if 0 /// UNNEEDED by elogind
1172 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1173         char *t, *x;
1174         uint64_t u;
1175         unsigned i;
1176         int r;
1177
1178         assert(ret);
1179
1180         /* Turns this:
1181          *         /foo/bar/waldo
1182          * Into this:
1183          *         /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1184          */
1185
1186         if (!p) {
1187                 r = tmp_dir(&p);
1188                 if (r < 0)
1189                         return r;
1190         }
1191
1192         if (!extra)
1193                 extra = "";
1194
1195         t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1196         if (!t)
1197                 return -ENOMEM;
1198
1199         x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1200
1201         u = random_u64();
1202         for (i = 0; i < 16; i++) {
1203                 *(x++) = hexchar(u & 0xF);
1204                 u >>= 4;
1205         }
1206
1207         *x = 0;
1208
1209         *ret = path_kill_slashes(t);
1210         return 0;
1211 }
1212
1213 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1214         char ln[DECIMAL_STR_MAX(n)+2];
1215
1216         /* Creates a "timestamp" file, that contains nothing but a
1217          * usec_t timestamp, formatted in ASCII. */
1218
1219         if (n <= 0 || n >= USEC_INFINITY)
1220                 return -ERANGE;
1221
1222         xsprintf(ln, USEC_FMT "\n", n);
1223
1224         return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1225 }
1226
1227 int read_timestamp_file(const char *fn, usec_t *ret) {
1228         _cleanup_free_ char *ln = NULL;
1229         uint64_t t;
1230         int r;
1231
1232         r = read_one_line_file(fn, &ln);
1233         if (r < 0)
1234                 return r;
1235
1236         r = safe_atou64(ln, &t);
1237         if (r < 0)
1238                 return r;
1239
1240         if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1241                 return -ERANGE;
1242
1243         *ret = (usec_t) t;
1244         return 0;
1245 }
1246
1247 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1248         int r;
1249
1250         assert(s);
1251
1252         /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1253          * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1254          * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1255          * element, but not before the first one. */
1256
1257         if (!f)
1258                 f = stdout;
1259
1260         if (space) {
1261                 if (!separator)
1262                         separator = " ";
1263
1264                 if (*space) {
1265                         r = fputs(separator, f);
1266                         if (r < 0)
1267                                 return r;
1268                 }
1269
1270                 *space = true;
1271         }
1272
1273         return fputs(s, f);
1274 }
1275
1276 int open_tmpfile_unlinkable(const char *directory, int flags) {
1277         char *p;
1278         int fd, r;
1279
1280         if (!directory) {
1281                 r = tmp_dir(&directory);
1282                 if (r < 0)
1283                         return r;
1284         }
1285
1286         /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1287
1288         /* Try O_TMPFILE first, if it is supported */
1289         fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1290         if (fd >= 0)
1291                 return fd;
1292
1293         /* Fall back to unguessable name + unlinking */
1294         p = strjoina(directory, "/systemd-tmp-XXXXXX");
1295
1296         fd = mkostemp_safe(p);
1297         if (fd < 0)
1298                 return fd;
1299
1300         (void) unlink(p);
1301
1302         return fd;
1303 }
1304
1305 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1306         _cleanup_free_ char *tmp = NULL;
1307         int r, fd;
1308
1309         assert(target);
1310         assert(ret_path);
1311
1312         /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1313         assert((flags & O_EXCL) == 0);
1314
1315         /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1316          * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1317          * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1318
1319         {
1320                 _cleanup_free_ char *dn = NULL;
1321
1322                 dn = dirname_malloc(target);
1323                 if (!dn)
1324                         return -ENOMEM;
1325
1326                 fd = open(dn, O_TMPFILE|flags, 0640);
1327                 if (fd >= 0) {
1328                         *ret_path = NULL;
1329                         return fd;
1330                 }
1331
1332                 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1333         }
1334
1335         r = tempfn_random(target, NULL, &tmp);
1336         if (r < 0)
1337                 return r;
1338
1339         fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1340         if (fd < 0)
1341                 return -errno;
1342
1343         *ret_path = tmp;
1344         tmp = NULL;
1345
1346         return fd;
1347 }
1348
1349 int link_tmpfile(int fd, const char *path, const char *target) {
1350
1351         assert(fd >= 0);
1352         assert(target);
1353
1354         /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1355          * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1356          * on the directory, and renameat2() is used instead.
1357          *
1358          * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1359          * operation currently (renameat2() does), and there is no nice way to emulate this. */
1360
1361         if (path) {
1362                 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1363                         return -errno;
1364         } else {
1365                 char proc_fd_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1366
1367                 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1368
1369                 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1370                         return -errno;
1371         }
1372
1373         return 0;
1374 }
1375 #endif // 0
1376
1377 int read_nul_string(FILE *f, char **ret) {
1378         _cleanup_free_ char *x = NULL;
1379         size_t allocated = 0, n = 0;
1380
1381         assert(f);
1382         assert(ret);
1383
1384         /* Reads a NUL-terminated string from the specified file. */
1385
1386         for (;;) {
1387                 int c;
1388
1389                 if (!GREEDY_REALLOC(x, allocated, n+2))
1390                         return -ENOMEM;
1391
1392                 c = fgetc(f);
1393                 if (c == 0) /* Terminate at NUL byte */
1394                         break;
1395                 if (c == EOF) {
1396                         if (ferror(f))
1397                                 return -errno;
1398                         break; /* Terminate at EOF */
1399                 }
1400
1401                 x[n++] = (char) c;
1402         }
1403
1404         if (x)
1405                 x[n] = 0;
1406         else {
1407                 x = new0(char, 1);
1408                 if (!x)
1409                         return -ENOMEM;
1410         }
1411
1412         *ret = x;
1413         x = NULL;
1414
1415         return 0;
1416 }
1417
1418 int mkdtemp_malloc(const char *template, char **ret) {
1419         char *p;
1420
1421         assert(template);
1422         assert(ret);
1423
1424         p = strdup(template);
1425         if (!p)
1426                 return -ENOMEM;
1427
1428         if (!mkdtemp(p)) {
1429                 free(p);
1430                 return -errno;
1431         }
1432
1433         *ret = p;
1434         return 0;
1435 }