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