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