chiark / gitweb /
5e7b63dbff1dc120a3cb4a7de62b889e26e8334c
[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 "env-util.h"
34 #include "escape.h"
35 #include "fd-util.h"
36 #include "fileio.h"
37 #include "fs-util.h"
38 #include "hexdecoct.h"
39 //#include "log.h"
40 //#include "macro.h"
41 #include "parse-util.h"
42 #include "path-util.h"
43 #include "random-util.h"
44 #include "stdio-util.h"
45 #include "string-util.h"
46 #include "strv.h"
47 //#include "time-util.h"
48 #include "umask-util.h"
49 #include "utf8.h"
50
51 #define READ_FULL_BYTES_MAX (4U*1024U*1024U)
52
53 int write_string_stream(FILE *f, const char *line, bool enforce_newline) {
54
55         assert(f);
56         assert(line);
57
58         fputs(line, f);
59         if (enforce_newline && !endswith(line, "\n"))
60                 fputc('\n', f);
61
62         return fflush_and_check(f);
63 }
64
65 static int write_string_file_atomic(const char *fn, const char *line, bool enforce_newline) {
66         _cleanup_fclose_ FILE *f = NULL;
67         _cleanup_free_ char *p = NULL;
68         int r;
69
70         assert(fn);
71         assert(line);
72
73         r = fopen_temporary(fn, &f, &p);
74         if (r < 0)
75                 return r;
76
77         (void) fchmod_umask(fileno(f), 0644);
78
79         r = write_string_stream(f, line, enforce_newline);
80         if (r >= 0) {
81                 if (rename(p, fn) < 0)
82                         r = -errno;
83         }
84
85         if (r < 0)
86                 (void) unlink(p);
87
88         return r;
89 }
90
91 int write_string_file(const char *fn, const char *line, WriteStringFileFlags flags) {
92         _cleanup_fclose_ FILE *f = NULL;
93         int q, r;
94
95         assert(fn);
96         assert(line);
97
98         if (flags & WRITE_STRING_FILE_ATOMIC) {
99                 assert(flags & WRITE_STRING_FILE_CREATE);
100
101                 r = write_string_file_atomic(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
102                 if (r < 0)
103                         goto fail;
104
105                 return r;
106         }
107
108         if (flags & WRITE_STRING_FILE_CREATE) {
109                 f = fopen(fn, "we");
110                 if (!f) {
111                         r = -errno;
112                         goto fail;
113                 }
114         } else {
115                 int fd;
116
117                 /* We manually build our own version of fopen(..., "we") that
118                  * works without O_CREAT */
119                 fd = open(fn, O_WRONLY|O_CLOEXEC|O_NOCTTY);
120                 if (fd < 0) {
121                         r = -errno;
122                         goto fail;
123                 }
124
125                 f = fdopen(fd, "we");
126                 if (!f) {
127                         r = -errno;
128                         safe_close(fd);
129                         goto fail;
130                 }
131         }
132
133         r = write_string_stream(f, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
134         if (r < 0)
135                 goto fail;
136
137         return 0;
138
139 fail:
140         if (!(flags & WRITE_STRING_FILE_VERIFY_ON_FAILURE))
141                 return r;
142
143         f = safe_fclose(f);
144
145         /* OK, the operation failed, but let's see if the right
146          * contents in place already. If so, eat up the error. */
147
148         q = verify_file(fn, line, !(flags & WRITE_STRING_FILE_AVOID_NEWLINE));
149         if (q <= 0)
150                 return r;
151
152         return 0;
153 }
154
155 int read_one_line_file(const char *fn, char **line) {
156         _cleanup_fclose_ FILE *f = NULL;
157         char t[LINE_MAX], *c;
158
159         assert(fn);
160         assert(line);
161
162         f = fopen(fn, "re");
163         if (!f)
164                 return -errno;
165
166         if (!fgets(t, sizeof(t), f)) {
167
168                 if (ferror(f))
169                         return errno > 0 ? -errno : -EIO;
170
171                 t[0] = 0;
172         }
173
174         c = strdup(t);
175         if (!c)
176                 return -ENOMEM;
177         truncate_nl(c);
178
179         *line = c;
180         return 0;
181 }
182
183 int verify_file(const char *fn, const char *blob, bool accept_extra_nl) {
184         _cleanup_fclose_ FILE *f = NULL;
185         _cleanup_free_ char *buf = NULL;
186         size_t l, k;
187
188         assert(fn);
189         assert(blob);
190
191         l = strlen(blob);
192
193         if (accept_extra_nl && endswith(blob, "\n"))
194                 accept_extra_nl = false;
195
196         buf = malloc(l + accept_extra_nl + 1);
197         if (!buf)
198                 return -ENOMEM;
199
200         f = fopen(fn, "re");
201         if (!f)
202                 return -errno;
203
204         /* We try to read one byte more than we need, so that we know whether we hit eof */
205         errno = 0;
206         k = fread(buf, 1, l + accept_extra_nl + 1, f);
207         if (ferror(f))
208                 return errno > 0 ? -errno : -EIO;
209
210         if (k != l && k != l + accept_extra_nl)
211                 return 0;
212         if (memcmp(buf, blob, l) != 0)
213                 return 0;
214         if (k > l && buf[l] != '\n')
215                 return 0;
216
217         return 1;
218 }
219
220 int read_full_stream(FILE *f, char **contents, size_t *size) {
221         size_t n, l;
222         _cleanup_free_ char *buf = NULL;
223         struct stat st;
224
225         assert(f);
226         assert(contents);
227
228         if (fstat(fileno(f), &st) < 0)
229                 return -errno;
230
231         n = LINE_MAX;
232
233         if (S_ISREG(st.st_mode)) {
234
235                 /* Safety check */
236                 if (st.st_size > READ_FULL_BYTES_MAX)
237                         return -E2BIG;
238
239                 /* Start with the right file size, but be prepared for
240                  * files from /proc which generally report a file size
241                  * of 0 */
242                 if (st.st_size > 0)
243                         n = st.st_size;
244         }
245
246         l = 0;
247         for (;;) {
248                 char *t;
249                 size_t k;
250
251                 t = realloc(buf, n + 1);
252                 if (!t)
253                         return -ENOMEM;
254
255                 buf = t;
256                 k = fread(buf + l, 1, n - l, f);
257                 if (k > 0)
258                         l += k;
259
260                 if (ferror(f))
261                         return -errno;
262
263                 if (feof(f))
264                         break;
265
266                 /* We aren't expecting fread() to return a short read outside
267                  * of (error && eof), assert buffer is full and enlarge buffer.
268                  */
269                 assert(l == n);
270
271                 /* Safety check */
272                 if (n >= READ_FULL_BYTES_MAX)
273                         return -E2BIG;
274
275                 n = MIN(n * 2, READ_FULL_BYTES_MAX);
276         }
277
278         buf[l] = 0;
279         *contents = buf;
280         buf = NULL; /* do not free */
281
282         if (size)
283                 *size = l;
284
285         return 0;
286 }
287
288 int read_full_file(const char *fn, char **contents, size_t *size) {
289         _cleanup_fclose_ FILE *f = NULL;
290
291         assert(fn);
292         assert(contents);
293
294         f = fopen(fn, "re");
295         if (!f)
296                 return -errno;
297
298         return read_full_stream(f, contents, size);
299 }
300
301 static int parse_env_file_internal(
302                 FILE *f,
303                 const char *fname,
304                 const char *newline,
305                 int (*push) (const char *filename, unsigned line,
306                              const char *key, char *value, void *userdata, int *n_pushed),
307                 void *userdata,
308                 int *n_pushed) {
309
310         _cleanup_free_ char *contents = NULL, *key = NULL;
311         size_t key_alloc = 0, n_key = 0, value_alloc = 0, n_value = 0, last_value_whitespace = (size_t) -1, last_key_whitespace = (size_t) -1;
312         char *p, *value = NULL;
313         int r;
314         unsigned line = 1;
315
316         enum {
317                 PRE_KEY,
318                 KEY,
319                 PRE_VALUE,
320                 VALUE,
321                 VALUE_ESCAPE,
322                 SINGLE_QUOTE_VALUE,
323                 SINGLE_QUOTE_VALUE_ESCAPE,
324                 DOUBLE_QUOTE_VALUE,
325                 DOUBLE_QUOTE_VALUE_ESCAPE,
326                 COMMENT,
327                 COMMENT_ESCAPE
328         } state = PRE_KEY;
329
330         assert(newline);
331
332         if (f)
333                 r = read_full_stream(f, &contents, NULL);
334         else
335                 r = read_full_file(fname, &contents, NULL);
336         if (r < 0)
337                 return r;
338
339         for (p = contents; *p; p++) {
340                 char c = *p;
341
342                 switch (state) {
343
344                 case PRE_KEY:
345                         if (strchr(COMMENTS, c))
346                                 state = COMMENT;
347                         else if (!strchr(WHITESPACE, c)) {
348                                 state = KEY;
349                                 last_key_whitespace = (size_t) -1;
350
351                                 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
352                                         r = -ENOMEM;
353                                         goto fail;
354                                 }
355
356                                 key[n_key++] = c;
357                         }
358                         break;
359
360                 case KEY:
361                         if (strchr(newline, c)) {
362                                 state = PRE_KEY;
363                                 line++;
364                                 n_key = 0;
365                         } else if (c == '=') {
366                                 state = PRE_VALUE;
367                                 last_value_whitespace = (size_t) -1;
368                         } else {
369                                 if (!strchr(WHITESPACE, c))
370                                         last_key_whitespace = (size_t) -1;
371                                 else if (last_key_whitespace == (size_t) -1)
372                                          last_key_whitespace = n_key;
373
374                                 if (!GREEDY_REALLOC(key, key_alloc, n_key+2)) {
375                                         r = -ENOMEM;
376                                         goto fail;
377                                 }
378
379                                 key[n_key++] = c;
380                         }
381
382                         break;
383
384                 case PRE_VALUE:
385                         if (strchr(newline, c)) {
386                                 state = PRE_KEY;
387                                 line++;
388                                 key[n_key] = 0;
389
390                                 if (value)
391                                         value[n_value] = 0;
392
393                                 /* strip trailing whitespace from key */
394                                 if (last_key_whitespace != (size_t) -1)
395                                         key[last_key_whitespace] = 0;
396
397                                 r = push(fname, line, key, value, userdata, n_pushed);
398                                 if (r < 0)
399                                         goto fail;
400
401                                 n_key = 0;
402                                 value = NULL;
403                                 value_alloc = n_value = 0;
404
405                         } else if (c == '\'')
406                                 state = SINGLE_QUOTE_VALUE;
407                         else if (c == '\"')
408                                 state = DOUBLE_QUOTE_VALUE;
409                         else if (c == '\\')
410                                 state = VALUE_ESCAPE;
411                         else if (!strchr(WHITESPACE, c)) {
412                                 state = VALUE;
413
414                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
415                                         r = -ENOMEM;
416                                         goto fail;
417                                 }
418
419                                 value[n_value++] = c;
420                         }
421
422                         break;
423
424                 case VALUE:
425                         if (strchr(newline, c)) {
426                                 state = PRE_KEY;
427                                 line++;
428
429                                 key[n_key] = 0;
430
431                                 if (value)
432                                         value[n_value] = 0;
433
434                                 /* Chomp off trailing whitespace from value */
435                                 if (last_value_whitespace != (size_t) -1)
436                                         value[last_value_whitespace] = 0;
437
438                                 /* strip trailing whitespace from key */
439                                 if (last_key_whitespace != (size_t) -1)
440                                         key[last_key_whitespace] = 0;
441
442                                 r = push(fname, line, key, value, userdata, n_pushed);
443                                 if (r < 0)
444                                         goto fail;
445
446                                 n_key = 0;
447                                 value = NULL;
448                                 value_alloc = n_value = 0;
449
450                         } else if (c == '\\') {
451                                 state = VALUE_ESCAPE;
452                                 last_value_whitespace = (size_t) -1;
453                         } else {
454                                 if (!strchr(WHITESPACE, c))
455                                         last_value_whitespace = (size_t) -1;
456                                 else if (last_value_whitespace == (size_t) -1)
457                                         last_value_whitespace = n_value;
458
459                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
460                                         r = -ENOMEM;
461                                         goto fail;
462                                 }
463
464                                 value[n_value++] = c;
465                         }
466
467                         break;
468
469                 case VALUE_ESCAPE:
470                         state = VALUE;
471
472                         if (!strchr(newline, c)) {
473                                 /* Escaped newlines we eat up entirely */
474                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
475                                         r = -ENOMEM;
476                                         goto fail;
477                                 }
478
479                                 value[n_value++] = c;
480                         }
481                         break;
482
483                 case SINGLE_QUOTE_VALUE:
484                         if (c == '\'')
485                                 state = PRE_VALUE;
486                         else if (c == '\\')
487                                 state = SINGLE_QUOTE_VALUE_ESCAPE;
488                         else {
489                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
490                                         r = -ENOMEM;
491                                         goto fail;
492                                 }
493
494                                 value[n_value++] = c;
495                         }
496
497                         break;
498
499                 case SINGLE_QUOTE_VALUE_ESCAPE:
500                         state = SINGLE_QUOTE_VALUE;
501
502                         if (!strchr(newline, c)) {
503                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
504                                         r = -ENOMEM;
505                                         goto fail;
506                                 }
507
508                                 value[n_value++] = c;
509                         }
510                         break;
511
512                 case DOUBLE_QUOTE_VALUE:
513                         if (c == '\"')
514                                 state = PRE_VALUE;
515                         else if (c == '\\')
516                                 state = DOUBLE_QUOTE_VALUE_ESCAPE;
517                         else {
518                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
519                                         r = -ENOMEM;
520                                         goto fail;
521                                 }
522
523                                 value[n_value++] = c;
524                         }
525
526                         break;
527
528                 case DOUBLE_QUOTE_VALUE_ESCAPE:
529                         state = DOUBLE_QUOTE_VALUE;
530
531                         if (!strchr(newline, c)) {
532                                 if (!GREEDY_REALLOC(value, value_alloc, n_value+2)) {
533                                         r = -ENOMEM;
534                                         goto fail;
535                                 }
536
537                                 value[n_value++] = c;
538                         }
539                         break;
540
541                 case COMMENT:
542                         if (c == '\\')
543                                 state = COMMENT_ESCAPE;
544                         else if (strchr(newline, c)) {
545                                 state = PRE_KEY;
546                                 line++;
547                         }
548                         break;
549
550                 case COMMENT_ESCAPE:
551                         state = COMMENT;
552                         break;
553                 }
554         }
555
556         if (state == PRE_VALUE ||
557             state == VALUE ||
558             state == VALUE_ESCAPE ||
559             state == SINGLE_QUOTE_VALUE ||
560             state == SINGLE_QUOTE_VALUE_ESCAPE ||
561             state == DOUBLE_QUOTE_VALUE ||
562             state == DOUBLE_QUOTE_VALUE_ESCAPE) {
563
564                 key[n_key] = 0;
565
566                 if (value)
567                         value[n_value] = 0;
568
569                 if (state == VALUE)
570                         if (last_value_whitespace != (size_t) -1)
571                                 value[last_value_whitespace] = 0;
572
573                 /* strip trailing whitespace from key */
574                 if (last_key_whitespace != (size_t) -1)
575                         key[last_key_whitespace] = 0;
576
577                 r = push(fname, line, key, value, userdata, n_pushed);
578                 if (r < 0)
579                         goto fail;
580         }
581
582         return 0;
583
584 fail:
585         free(value);
586         return r;
587 }
588
589 static int check_utf8ness_and_warn(
590                 const char *filename, unsigned line,
591                 const char *key, char *value) {
592
593         if (!utf8_is_valid(key)) {
594                 _cleanup_free_ char *p = NULL;
595
596                 p = utf8_escape_invalid(key);
597                 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
598                 return -EINVAL;
599         }
600
601         if (value && !utf8_is_valid(value)) {
602                 _cleanup_free_ char *p = NULL;
603
604                 p = utf8_escape_invalid(value);
605                 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
606                 return -EINVAL;
607         }
608
609         return 0;
610 }
611
612 static int parse_env_file_push(
613                 const char *filename, unsigned line,
614                 const char *key, char *value,
615                 void *userdata,
616                 int *n_pushed) {
617
618         const char *k;
619         va_list aq, *ap = userdata;
620         int r;
621
622         r = check_utf8ness_and_warn(filename, line, key, value);
623         if (r < 0)
624                 return r;
625
626         va_copy(aq, *ap);
627
628         while ((k = va_arg(aq, const char *))) {
629                 char **v;
630
631                 v = va_arg(aq, char **);
632
633                 if (streq(key, k)) {
634                         va_end(aq);
635                         free(*v);
636                         *v = value;
637
638                         if (n_pushed)
639                                 (*n_pushed)++;
640
641                         return 1;
642                 }
643         }
644
645         va_end(aq);
646         free(value);
647
648         return 0;
649 }
650
651 int parse_env_file(
652                 const char *fname,
653                 const char *newline, ...) {
654
655         va_list ap;
656         int r, n_pushed = 0;
657
658         if (!newline)
659                 newline = NEWLINE;
660
661         va_start(ap, newline);
662         r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
663         va_end(ap);
664
665         return r < 0 ? r : n_pushed;
666 }
667
668 #if 0 /// UNNEEDED by elogind
669 static int load_env_file_push(
670                 const char *filename, unsigned line,
671                 const char *key, char *value,
672                 void *userdata,
673                 int *n_pushed) {
674         char ***m = userdata;
675         char *p;
676         int r;
677
678         r = check_utf8ness_and_warn(filename, line, key, value);
679         if (r < 0)
680                 return r;
681
682         p = strjoin(key, "=", value);
683         if (!p)
684                 return -ENOMEM;
685
686         r = strv_env_replace(m, p);
687         if (r < 0) {
688                 free(p);
689                 return r;
690         }
691
692         if (n_pushed)
693                 (*n_pushed)++;
694
695         free(value);
696         return 0;
697 }
698
699 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
700         char **m = NULL;
701         int r;
702
703         if (!newline)
704                 newline = NEWLINE;
705
706         r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
707         if (r < 0) {
708                 strv_free(m);
709                 return r;
710         }
711
712         *rl = m;
713         return 0;
714 }
715
716 static int load_env_file_push_pairs(
717                 const char *filename, unsigned line,
718                 const char *key, char *value,
719                 void *userdata,
720                 int *n_pushed) {
721         char ***m = userdata;
722         int r;
723
724         r = check_utf8ness_and_warn(filename, line, key, value);
725         if (r < 0)
726                 return r;
727
728         r = strv_extend(m, key);
729         if (r < 0)
730                 return -ENOMEM;
731
732         if (!value) {
733                 r = strv_extend(m, "");
734                 if (r < 0)
735                         return -ENOMEM;
736         } else {
737                 r = strv_push(m, value);
738                 if (r < 0)
739                         return r;
740         }
741
742         if (n_pushed)
743                 (*n_pushed)++;
744
745         return 0;
746 }
747
748 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
749         char **m = NULL;
750         int r;
751
752         if (!newline)
753                 newline = NEWLINE;
754
755         r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
756         if (r < 0) {
757                 strv_free(m);
758                 return r;
759         }
760
761         *rl = m;
762         return 0;
763 }
764
765 static void write_env_var(FILE *f, const char *v) {
766         const char *p;
767
768         p = strchr(v, '=');
769         if (!p) {
770                 /* Fallback */
771                 fputs(v, f);
772                 fputc('\n', f);
773                 return;
774         }
775
776         p++;
777         fwrite(v, 1, p-v, f);
778
779         if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
780                 fputc('\"', f);
781
782                 for (; *p; p++) {
783                         if (strchr(SHELL_NEED_ESCAPE, *p))
784                                 fputc('\\', f);
785
786                         fputc(*p, f);
787                 }
788
789                 fputc('\"', f);
790         } else
791                 fputs(p, f);
792
793         fputc('\n', f);
794 }
795
796 int write_env_file(const char *fname, char **l) {
797         _cleanup_fclose_ FILE *f = NULL;
798         _cleanup_free_ char *p = NULL;
799         char **i;
800         int r;
801
802         assert(fname);
803
804         r = fopen_temporary(fname, &f, &p);
805         if (r < 0)
806                 return r;
807
808         fchmod_umask(fileno(f), 0644);
809
810         STRV_FOREACH(i, l)
811                 write_env_var(f, *i);
812
813         r = fflush_and_check(f);
814         if (r >= 0) {
815                 if (rename(p, fname) >= 0)
816                         return 0;
817
818                 r = -errno;
819         }
820
821         unlink(p);
822         return r;
823 }
824
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);
964                 else
965                         p = strjoin(*i, "/", path);
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);
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 mkostemp() but is subject to umask(). */
1077 int mkostemp_safe(char *pattern) {
1078         _cleanup_umask_ mode_t u = 0;
1079         int fd;
1080
1081         assert(pattern);
1082
1083         u = umask(077);
1084
1085         fd = mkostemp(pattern, O_CLOEXEC);
1086         if (fd < 0)
1087                 return -errno;
1088
1089         return fd;
1090 }
1091
1092 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1093         const char *fn;
1094         char *t;
1095
1096         assert(p);
1097         assert(ret);
1098
1099         /*
1100          * Turns this:
1101          *         /foo/bar/waldo
1102          *
1103          * Into this:
1104          *         /foo/bar/.#<extra>waldoXXXXXX
1105          */
1106
1107         fn = basename(p);
1108         if (!filename_is_valid(fn))
1109                 return -EINVAL;
1110
1111         if (extra == NULL)
1112                 extra = "";
1113
1114         t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1115         if (!t)
1116                 return -ENOMEM;
1117
1118         strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1119
1120         *ret = path_kill_slashes(t);
1121         return 0;
1122 }
1123
1124 int tempfn_random(const char *p, const char *extra, char **ret) {
1125         const char *fn;
1126         char *t, *x;
1127         uint64_t u;
1128         unsigned i;
1129
1130         assert(p);
1131         assert(ret);
1132
1133         /*
1134          * Turns this:
1135          *         /foo/bar/waldo
1136          *
1137          * Into this:
1138          *         /foo/bar/.#<extra>waldobaa2a261115984a9
1139          */
1140
1141         fn = basename(p);
1142         if (!filename_is_valid(fn))
1143                 return -EINVAL;
1144
1145         if (!extra)
1146                 extra = "";
1147
1148         t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1149         if (!t)
1150                 return -ENOMEM;
1151
1152         x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1153
1154         u = random_u64();
1155         for (i = 0; i < 16; i++) {
1156                 *(x++) = hexchar(u & 0xF);
1157                 u >>= 4;
1158         }
1159
1160         *x = 0;
1161
1162         *ret = path_kill_slashes(t);
1163         return 0;
1164 }
1165
1166 #if 0 /// UNNEEDED by elogind
1167 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1168         char *t, *x;
1169         uint64_t u;
1170         unsigned i;
1171         int r;
1172
1173         assert(ret);
1174
1175         /* Turns this:
1176          *         /foo/bar/waldo
1177          * Into this:
1178          *         /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1179          */
1180
1181         if (!p) {
1182                 r = tmp_dir(&p);
1183                 if (r < 0)
1184                         return r;
1185         }
1186
1187         if (!extra)
1188                 extra = "";
1189
1190         t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1191         if (!t)
1192                 return -ENOMEM;
1193
1194         x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1195
1196         u = random_u64();
1197         for (i = 0; i < 16; i++) {
1198                 *(x++) = hexchar(u & 0xF);
1199                 u >>= 4;
1200         }
1201
1202         *x = 0;
1203
1204         *ret = path_kill_slashes(t);
1205         return 0;
1206 }
1207
1208 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1209         char ln[DECIMAL_STR_MAX(n)+2];
1210
1211         /* Creates a "timestamp" file, that contains nothing but a
1212          * usec_t timestamp, formatted in ASCII. */
1213
1214         if (n <= 0 || n >= USEC_INFINITY)
1215                 return -ERANGE;
1216
1217         xsprintf(ln, USEC_FMT "\n", n);
1218
1219         return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1220 }
1221
1222 int read_timestamp_file(const char *fn, usec_t *ret) {
1223         _cleanup_free_ char *ln = NULL;
1224         uint64_t t;
1225         int r;
1226
1227         r = read_one_line_file(fn, &ln);
1228         if (r < 0)
1229                 return r;
1230
1231         r = safe_atou64(ln, &t);
1232         if (r < 0)
1233                 return r;
1234
1235         if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1236                 return -ERANGE;
1237
1238         *ret = (usec_t) t;
1239         return 0;
1240 }
1241
1242 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1243         int r;
1244
1245         assert(s);
1246
1247         /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1248          * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1249          * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1250          * element, but not before the first one. */
1251
1252         if (!f)
1253                 f = stdout;
1254
1255         if (space) {
1256                 if (!separator)
1257                         separator = " ";
1258
1259                 if (*space) {
1260                         r = fputs(separator, f);
1261                         if (r < 0)
1262                                 return r;
1263                 }
1264
1265                 *space = true;
1266         }
1267
1268         return fputs(s, f);
1269 }
1270
1271 int open_tmpfile_unlinkable(const char *directory, int flags) {
1272         char *p;
1273         int fd, r;
1274
1275         if (!directory) {
1276                 r = tmp_dir(&directory);
1277                 if (r < 0)
1278                         return r;
1279         }
1280
1281         /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1282
1283         /* Try O_TMPFILE first, if it is supported */
1284         fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1285         if (fd >= 0)
1286                 return fd;
1287
1288         /* Fall back to unguessable name + unlinking */
1289         p = strjoina(directory, "/systemd-tmp-XXXXXX");
1290
1291         fd = mkostemp_safe(p);
1292         if (fd < 0)
1293                 return fd;
1294
1295         (void) unlink(p);
1296
1297         return fd;
1298 }
1299
1300 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1301         _cleanup_free_ char *tmp = NULL;
1302         int r, fd;
1303
1304         assert(target);
1305         assert(ret_path);
1306
1307         /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1308         assert((flags & O_EXCL) == 0);
1309
1310         /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1311          * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1312          * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1313
1314         {
1315                 _cleanup_free_ char *dn = NULL;
1316
1317                 dn = dirname_malloc(target);
1318                 if (!dn)
1319                         return -ENOMEM;
1320
1321                 fd = open(dn, O_TMPFILE|flags, 0640);
1322                 if (fd >= 0) {
1323                         *ret_path = NULL;
1324                         return fd;
1325                 }
1326
1327                 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1328         }
1329
1330         r = tempfn_random(target, NULL, &tmp);
1331         if (r < 0)
1332                 return r;
1333
1334         fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1335         if (fd < 0)
1336                 return -errno;
1337
1338         *ret_path = tmp;
1339         tmp = NULL;
1340
1341         return fd;
1342 }
1343
1344 int link_tmpfile(int fd, const char *path, const char *target) {
1345
1346         assert(fd >= 0);
1347         assert(target);
1348
1349         /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1350          * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1351          * on the directory, and renameat2() is used instead.
1352          *
1353          * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1354          * operation currently (renameat2() does), and there is no nice way to emulate this. */
1355
1356         if (path) {
1357                 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1358                         return -errno;
1359         } else {
1360                 char proc_fd_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1361
1362                 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1363
1364                 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1365                         return -errno;
1366         }
1367
1368         return 0;
1369 }
1370 #endif // 0
1371
1372 int read_nul_string(FILE *f, char **ret) {
1373         _cleanup_free_ char *x = NULL;
1374         size_t allocated = 0, n = 0;
1375
1376         assert(f);
1377         assert(ret);
1378
1379         /* Reads a NUL-terminated string from the specified file. */
1380
1381         for (;;) {
1382                 int c;
1383
1384                 if (!GREEDY_REALLOC(x, allocated, n+2))
1385                         return -ENOMEM;
1386
1387                 c = fgetc(f);
1388                 if (c == 0) /* Terminate at NUL byte */
1389                         break;
1390                 if (c == EOF) {
1391                         if (ferror(f))
1392                                 return -errno;
1393                         break; /* Terminate at EOF */
1394                 }
1395
1396                 x[n++] = (char) c;
1397         }
1398
1399         if (x)
1400                 x[n] = 0;
1401         else {
1402                 x = new0(char, 1);
1403                 if (!x)
1404                         return -ENOMEM;
1405         }
1406
1407         *ret = x;
1408         x = NULL;
1409
1410         return 0;
1411 }
1412
1413 int mkdtemp_malloc(const char *template, char **ret) {
1414         char *p;
1415
1416         assert(template);
1417         assert(ret);
1418
1419         p = strdup(template);
1420         if (!p)
1421                 return -ENOMEM;
1422
1423         if (!mkdtemp(p)) {
1424                 free(p);
1425                 return -errno;
1426         }
1427
1428         *ret = p;
1429         return 0;
1430 }