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