chiark / gitweb /
13f61077167e691dab32e0c7af76f3038c9db0d5
[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 "missing.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 (IN_SET(state,
557                    PRE_VALUE,
558                    VALUE,
559                    VALUE_ESCAPE,
560                    SINGLE_QUOTE_VALUE,
561                    SINGLE_QUOTE_VALUE_ESCAPE,
562                    DOUBLE_QUOTE_VALUE,
563                    DOUBLE_QUOTE_VALUE_ESCAPE)) {
564
565                 key[n_key] = 0;
566
567                 if (value)
568                         value[n_value] = 0;
569
570                 if (state == VALUE)
571                         if (last_value_whitespace != (size_t) -1)
572                                 value[last_value_whitespace] = 0;
573
574                 /* strip trailing whitespace from key */
575                 if (last_key_whitespace != (size_t) -1)
576                         key[last_key_whitespace] = 0;
577
578                 r = push(fname, line, key, value, userdata, n_pushed);
579                 if (r < 0)
580                         goto fail;
581         }
582
583         return 0;
584
585 fail:
586         free(value);
587         return r;
588 }
589
590 static int check_utf8ness_and_warn(
591                 const char *filename, unsigned line,
592                 const char *key, char *value) {
593
594         if (!utf8_is_valid(key)) {
595                 _cleanup_free_ char *p = NULL;
596
597                 p = utf8_escape_invalid(key);
598                 log_error("%s:%u: invalid UTF-8 in key '%s', ignoring.", strna(filename), line, p);
599                 return -EINVAL;
600         }
601
602         if (value && !utf8_is_valid(value)) {
603                 _cleanup_free_ char *p = NULL;
604
605                 p = utf8_escape_invalid(value);
606                 log_error("%s:%u: invalid UTF-8 value for key %s: '%s', ignoring.", strna(filename), line, key, p);
607                 return -EINVAL;
608         }
609
610         return 0;
611 }
612
613 static int parse_env_file_push(
614                 const char *filename, unsigned line,
615                 const char *key, char *value,
616                 void *userdata,
617                 int *n_pushed) {
618
619         const char *k;
620         va_list aq, *ap = userdata;
621         int r;
622
623         r = check_utf8ness_and_warn(filename, line, key, value);
624         if (r < 0)
625                 return r;
626
627         va_copy(aq, *ap);
628
629         while ((k = va_arg(aq, const char *))) {
630                 char **v;
631
632                 v = va_arg(aq, char **);
633
634                 if (streq(key, k)) {
635                         va_end(aq);
636                         free(*v);
637                         *v = value;
638
639                         if (n_pushed)
640                                 (*n_pushed)++;
641
642                         return 1;
643                 }
644         }
645
646         va_end(aq);
647         free(value);
648
649         return 0;
650 }
651
652 int parse_env_file(
653                 const char *fname,
654                 const char *newline, ...) {
655
656         va_list ap;
657         int r, n_pushed = 0;
658
659         if (!newline)
660                 newline = NEWLINE;
661
662         va_start(ap, newline);
663         r = parse_env_file_internal(NULL, fname, newline, parse_env_file_push, &ap, &n_pushed);
664         va_end(ap);
665
666         return r < 0 ? r : n_pushed;
667 }
668
669 #if 0 /// UNNEEDED by elogind
670 static int load_env_file_push(
671                 const char *filename, unsigned line,
672                 const char *key, char *value,
673                 void *userdata,
674                 int *n_pushed) {
675         char ***m = userdata;
676         char *p;
677         int r;
678
679         r = check_utf8ness_and_warn(filename, line, key, value);
680         if (r < 0)
681                 return r;
682
683         p = strjoin(key, "=", value);
684         if (!p)
685                 return -ENOMEM;
686
687         r = strv_env_replace(m, p);
688         if (r < 0) {
689                 free(p);
690                 return r;
691         }
692
693         if (n_pushed)
694                 (*n_pushed)++;
695
696         free(value);
697         return 0;
698 }
699
700 int load_env_file(FILE *f, const char *fname, const char *newline, char ***rl) {
701         char **m = NULL;
702         int r;
703
704         if (!newline)
705                 newline = NEWLINE;
706
707         r = parse_env_file_internal(f, fname, newline, load_env_file_push, &m, NULL);
708         if (r < 0) {
709                 strv_free(m);
710                 return r;
711         }
712
713         *rl = m;
714         return 0;
715 }
716 #endif // 0
717
718 static int load_env_file_push_pairs(
719                 const char *filename, unsigned line,
720                 const char *key, char *value,
721                 void *userdata,
722                 int *n_pushed) {
723         char ***m = userdata;
724         int r;
725
726         r = check_utf8ness_and_warn(filename, line, key, value);
727         if (r < 0)
728                 return r;
729
730         r = strv_extend(m, key);
731         if (r < 0)
732                 return -ENOMEM;
733
734         if (!value) {
735                 r = strv_extend(m, "");
736                 if (r < 0)
737                         return -ENOMEM;
738         } else {
739                 r = strv_push(m, value);
740                 if (r < 0)
741                         return r;
742         }
743
744         if (n_pushed)
745                 (*n_pushed)++;
746
747         return 0;
748 }
749
750 int load_env_file_pairs(FILE *f, const char *fname, const char *newline, char ***rl) {
751         char **m = NULL;
752         int r;
753
754         if (!newline)
755                 newline = NEWLINE;
756
757         r = parse_env_file_internal(f, fname, newline, load_env_file_push_pairs, &m, NULL);
758         if (r < 0) {
759                 strv_free(m);
760                 return r;
761         }
762
763         *rl = m;
764         return 0;
765 }
766 #if 0 /// UNNEEDED by elogind
767
768 static int merge_env_file_push(
769                 const char *filename, unsigned line,
770                 const char *key, char *value,
771                 void *userdata,
772                 int *n_pushed) {
773
774         char ***env = userdata;
775         char *expanded_value;
776
777         assert(env);
778
779         if (!value) {
780                 log_error("%s:%u: invalid syntax (around \"%s\"), ignoring.", strna(filename), line, key);
781                 return 0;
782         }
783
784         if (!env_name_is_valid(key)) {
785                 log_error("%s:%u: invalid variable name \"%s\", ignoring.", strna(filename), line, key);
786                 free(value);
787                 return 0;
788         }
789
790         expanded_value = replace_env(value, *env,
791                                      REPLACE_ENV_USE_ENVIRONMENT|
792                                      REPLACE_ENV_ALLOW_BRACELESS|
793                                      REPLACE_ENV_ALLOW_EXTENDED);
794         if (!expanded_value)
795                 return -ENOMEM;
796
797         free_and_replace(value, expanded_value);
798
799         return load_env_file_push(filename, line, key, value, env, n_pushed);
800 }
801
802 int merge_env_file(
803                 char ***env,
804                 FILE *f,
805                 const char *fname) {
806
807         /* NOTE: this function supports braceful and braceless variable expansions,
808          * plus "extended" substitutions, unlike other exported parsing functions.
809          */
810
811         return parse_env_file_internal(f, fname, NEWLINE, merge_env_file_push, env, NULL);
812 }
813
814 static void write_env_var(FILE *f, const char *v) {
815         const char *p;
816
817         p = strchr(v, '=');
818         if (!p) {
819                 /* Fallback */
820                 fputs(v, f);
821                 fputc('\n', f);
822                 return;
823         }
824
825         p++;
826         fwrite(v, 1, p-v, f);
827
828         if (string_has_cc(p, NULL) || chars_intersect(p, WHITESPACE SHELL_NEED_QUOTES)) {
829                 fputc('\"', f);
830
831                 for (; *p; p++) {
832                         if (strchr(SHELL_NEED_ESCAPE, *p))
833                                 fputc('\\', f);
834
835                         fputc(*p, f);
836                 }
837
838                 fputc('\"', f);
839         } else
840                 fputs(p, f);
841
842         fputc('\n', f);
843 }
844
845 int write_env_file(const char *fname, char **l) {
846         _cleanup_fclose_ FILE *f = NULL;
847         _cleanup_free_ char *p = NULL;
848         char **i;
849         int r;
850
851         assert(fname);
852
853         r = fopen_temporary(fname, &f, &p);
854         if (r < 0)
855                 return r;
856
857         fchmod_umask(fileno(f), 0644);
858
859         STRV_FOREACH(i, l)
860                 write_env_var(f, *i);
861
862         r = fflush_and_check(f);
863         if (r >= 0) {
864                 if (rename(p, fname) >= 0)
865                         return 0;
866
867                 r = -errno;
868         }
869
870         unlink(p);
871         return r;
872 }
873
874 int executable_is_script(const char *path, char **interpreter) {
875         int r;
876         _cleanup_free_ char *line = NULL;
877         int len;
878         char *ans;
879
880         assert(path);
881
882         r = read_one_line_file(path, &line);
883         if (r < 0)
884                 return r;
885
886         if (!startswith(line, "#!"))
887                 return 0;
888
889         ans = strstrip(line + 2);
890         len = strcspn(ans, " \t");
891
892         if (len == 0)
893                 return 0;
894
895         ans = strndup(ans, len);
896         if (!ans)
897                 return -ENOMEM;
898
899         *interpreter = ans;
900         return 1;
901 }
902 #endif // 0
903
904 /**
905  * Retrieve one field from a file like /proc/self/status.  pattern
906  * should not include whitespace or the delimiter (':'). pattern matches only
907  * the beginning of a line. Whitespace before ':' is skipped. Whitespace and
908  * zeros after the ':' will be skipped. field must be freed afterwards.
909  * terminator specifies the terminating characters of the field value (not
910  * included in the value).
911  */
912 int get_proc_field(const char *filename, const char *pattern, const char *terminator, char **field) {
913         _cleanup_free_ char *status = NULL;
914         char *t, *f;
915         size_t len;
916         int r;
917
918         assert(terminator);
919         assert(filename);
920         assert(pattern);
921         assert(field);
922
923         r = read_full_file(filename, &status, NULL);
924         if (r < 0)
925                 return r;
926
927         t = status;
928
929         do {
930                 bool pattern_ok;
931
932                 do {
933                         t = strstr(t, pattern);
934                         if (!t)
935                                 return -ENOENT;
936
937                         /* Check that pattern occurs in beginning of line. */
938                         pattern_ok = (t == status || t[-1] == '\n');
939
940                         t += strlen(pattern);
941
942                 } while (!pattern_ok);
943
944                 t += strspn(t, " \t");
945                 if (!*t)
946                         return -ENOENT;
947
948         } while (*t != ':');
949
950         t++;
951
952         if (*t) {
953                 t += strspn(t, " \t");
954
955                 /* Also skip zeros, because when this is used for
956                  * capabilities, we don't want the zeros. This way the
957                  * same capability set always maps to the same string,
958                  * irrespective of the total capability set size. For
959                  * other numbers it shouldn't matter. */
960                 t += strspn(t, "0");
961                 /* Back off one char if there's nothing but whitespace
962                    and zeros */
963                 if (!*t || isspace(*t))
964                         t--;
965         }
966
967         len = strcspn(t, terminator);
968
969         f = strndup(t, len);
970         if (!f)
971                 return -ENOMEM;
972
973         *field = f;
974         return 0;
975 }
976
977 DIR *xopendirat(int fd, const char *name, int flags) {
978         int nfd;
979         DIR *d;
980
981         assert(!(flags & O_CREAT));
982
983         nfd = openat(fd, name, O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC|flags, 0);
984         if (nfd < 0)
985                 return NULL;
986
987         d = fdopendir(nfd);
988         if (!d) {
989                 safe_close(nfd);
990                 return NULL;
991         }
992
993         return d;
994 }
995
996 #if 0 /// UNNEEDED by elogind
997 static int search_and_fopen_internal(const char *path, const char *mode, const char *root, char **search, FILE **_f) {
998         char **i;
999
1000         assert(path);
1001         assert(mode);
1002         assert(_f);
1003
1004         if (!path_strv_resolve_uniq(search, root))
1005                 return -ENOMEM;
1006
1007         STRV_FOREACH(i, search) {
1008                 _cleanup_free_ char *p = NULL;
1009                 FILE *f;
1010
1011                 if (root)
1012                         p = strjoin(root, *i, "/", path);
1013                 else
1014                         p = strjoin(*i, "/", path);
1015                 if (!p)
1016                         return -ENOMEM;
1017
1018                 f = fopen(p, mode);
1019                 if (f) {
1020                         *_f = f;
1021                         return 0;
1022                 }
1023
1024                 if (errno != ENOENT)
1025                         return -errno;
1026         }
1027
1028         return -ENOENT;
1029 }
1030
1031 int search_and_fopen(const char *path, const char *mode, const char *root, const char **search, FILE **_f) {
1032         _cleanup_strv_free_ char **copy = NULL;
1033
1034         assert(path);
1035         assert(mode);
1036         assert(_f);
1037
1038         if (path_is_absolute(path)) {
1039                 FILE *f;
1040
1041                 f = fopen(path, mode);
1042                 if (f) {
1043                         *_f = f;
1044                         return 0;
1045                 }
1046
1047                 return -errno;
1048         }
1049
1050         copy = strv_copy((char**) search);
1051         if (!copy)
1052                 return -ENOMEM;
1053
1054         return search_and_fopen_internal(path, mode, root, copy, _f);
1055 }
1056
1057 int search_and_fopen_nulstr(const char *path, const char *mode, const char *root, const char *search, FILE **_f) {
1058         _cleanup_strv_free_ char **s = NULL;
1059
1060         if (path_is_absolute(path)) {
1061                 FILE *f;
1062
1063                 f = fopen(path, mode);
1064                 if (f) {
1065                         *_f = f;
1066                         return 0;
1067                 }
1068
1069                 return -errno;
1070         }
1071
1072         s = strv_split_nulstr(search);
1073         if (!s)
1074                 return -ENOMEM;
1075
1076         return search_and_fopen_internal(path, mode, root, s, _f);
1077 }
1078 #endif // 0
1079
1080 int fopen_temporary(const char *path, FILE **_f, char **_temp_path) {
1081         FILE *f;
1082         char *t;
1083         int r, fd;
1084
1085         assert(path);
1086         assert(_f);
1087         assert(_temp_path);
1088
1089         r = tempfn_xxxxxx(path, NULL, &t);
1090         if (r < 0)
1091                 return r;
1092
1093         fd = mkostemp_safe(t);
1094         if (fd < 0) {
1095                 free(t);
1096                 return -errno;
1097         }
1098
1099         f = fdopen(fd, "we");
1100         if (!f) {
1101                 unlink_noerrno(t);
1102                 free(t);
1103                 safe_close(fd);
1104                 return -errno;
1105         }
1106
1107         *_f = f;
1108         *_temp_path = t;
1109
1110         return 0;
1111 }
1112
1113 int fflush_and_check(FILE *f) {
1114         assert(f);
1115
1116         errno = 0;
1117         fflush(f);
1118
1119         if (ferror(f))
1120                 return errno > 0 ? -errno : -EIO;
1121
1122         return 0;
1123 }
1124
1125 /* This is much like mkostemp() but is subject to umask(). */
1126 int mkostemp_safe(char *pattern) {
1127         _cleanup_umask_ mode_t u = 0;
1128         int fd;
1129
1130         assert(pattern);
1131
1132         u = umask(077);
1133
1134         fd = mkostemp(pattern, O_CLOEXEC);
1135         if (fd < 0)
1136                 return -errno;
1137
1138         return fd;
1139 }
1140
1141 int tempfn_xxxxxx(const char *p, const char *extra, char **ret) {
1142         const char *fn;
1143         char *t;
1144
1145         assert(p);
1146         assert(ret);
1147
1148         /*
1149          * Turns this:
1150          *         /foo/bar/waldo
1151          *
1152          * Into this:
1153          *         /foo/bar/.#<extra>waldoXXXXXX
1154          */
1155
1156         fn = basename(p);
1157         if (!filename_is_valid(fn))
1158                 return -EINVAL;
1159
1160         if (extra == NULL)
1161                 extra = "";
1162
1163         t = new(char, strlen(p) + 2 + strlen(extra) + 6 + 1);
1164         if (!t)
1165                 return -ENOMEM;
1166
1167         strcpy(stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn), "XXXXXX");
1168
1169         *ret = path_kill_slashes(t);
1170         return 0;
1171 }
1172
1173 int tempfn_random(const char *p, const char *extra, char **ret) {
1174         const char *fn;
1175         char *t, *x;
1176         uint64_t u;
1177         unsigned i;
1178
1179         assert(p);
1180         assert(ret);
1181
1182         /*
1183          * Turns this:
1184          *         /foo/bar/waldo
1185          *
1186          * Into this:
1187          *         /foo/bar/.#<extra>waldobaa2a261115984a9
1188          */
1189
1190         fn = basename(p);
1191         if (!filename_is_valid(fn))
1192                 return -EINVAL;
1193
1194         if (!extra)
1195                 extra = "";
1196
1197         t = new(char, strlen(p) + 2 + strlen(extra) + 16 + 1);
1198         if (!t)
1199                 return -ENOMEM;
1200
1201         x = stpcpy(stpcpy(stpcpy(mempcpy(t, p, fn - p), ".#"), extra), fn);
1202
1203         u = random_u64();
1204         for (i = 0; i < 16; i++) {
1205                 *(x++) = hexchar(u & 0xF);
1206                 u >>= 4;
1207         }
1208
1209         *x = 0;
1210
1211         *ret = path_kill_slashes(t);
1212         return 0;
1213 }
1214
1215 #if 0 /// UNNEEDED by elogind
1216 int tempfn_random_child(const char *p, const char *extra, char **ret) {
1217         char *t, *x;
1218         uint64_t u;
1219         unsigned i;
1220         int r;
1221
1222         assert(ret);
1223
1224         /* Turns this:
1225          *         /foo/bar/waldo
1226          * Into this:
1227          *         /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0
1228          */
1229
1230         if (!p) {
1231                 r = tmp_dir(&p);
1232                 if (r < 0)
1233                         return r;
1234         }
1235
1236         if (!extra)
1237                 extra = "";
1238
1239         t = new(char, strlen(p) + 3 + strlen(extra) + 16 + 1);
1240         if (!t)
1241                 return -ENOMEM;
1242
1243         x = stpcpy(stpcpy(stpcpy(t, p), "/.#"), extra);
1244
1245         u = random_u64();
1246         for (i = 0; i < 16; i++) {
1247                 *(x++) = hexchar(u & 0xF);
1248                 u >>= 4;
1249         }
1250
1251         *x = 0;
1252
1253         *ret = path_kill_slashes(t);
1254         return 0;
1255 }
1256
1257 int write_timestamp_file_atomic(const char *fn, usec_t n) {
1258         char ln[DECIMAL_STR_MAX(n)+2];
1259
1260         /* Creates a "timestamp" file, that contains nothing but a
1261          * usec_t timestamp, formatted in ASCII. */
1262
1263         if (n <= 0 || n >= USEC_INFINITY)
1264                 return -ERANGE;
1265
1266         xsprintf(ln, USEC_FMT "\n", n);
1267
1268         return write_string_file(fn, ln, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC);
1269 }
1270
1271 int read_timestamp_file(const char *fn, usec_t *ret) {
1272         _cleanup_free_ char *ln = NULL;
1273         uint64_t t;
1274         int r;
1275
1276         r = read_one_line_file(fn, &ln);
1277         if (r < 0)
1278                 return r;
1279
1280         r = safe_atou64(ln, &t);
1281         if (r < 0)
1282                 return r;
1283
1284         if (t <= 0 || t >= (uint64_t) USEC_INFINITY)
1285                 return -ERANGE;
1286
1287         *ret = (usec_t) t;
1288         return 0;
1289 }
1290
1291 int fputs_with_space(FILE *f, const char *s, const char *separator, bool *space) {
1292         int r;
1293
1294         assert(s);
1295
1296         /* Outputs the specified string with fputs(), but optionally prefixes it with a separator. The *space parameter
1297          * when specified shall initially point to a boolean variable initialized to false. It is set to true after the
1298          * first invocation. This call is supposed to be use in loops, where a separator shall be inserted between each
1299          * element, but not before the first one. */
1300
1301         if (!f)
1302                 f = stdout;
1303
1304         if (space) {
1305                 if (!separator)
1306                         separator = " ";
1307
1308                 if (*space) {
1309                         r = fputs(separator, f);
1310                         if (r < 0)
1311                                 return r;
1312                 }
1313
1314                 *space = true;
1315         }
1316
1317         return fputs(s, f);
1318 }
1319 #endif // 0
1320
1321 int open_tmpfile_unlinkable(const char *directory, int flags) {
1322         char *p;
1323         int fd, r;
1324
1325         if (!directory) {
1326                 r = tmp_dir(&directory);
1327                 if (r < 0)
1328                         return r;
1329         }
1330
1331         /* Returns an unlinked temporary file that cannot be linked into the file system anymore */
1332
1333         /* Try O_TMPFILE first, if it is supported */
1334         fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR);
1335         if (fd >= 0)
1336                 return fd;
1337
1338         /* Fall back to unguessable name + unlinking */
1339         p = strjoina(directory, "/systemd-tmp-XXXXXX");
1340
1341         fd = mkostemp_safe(p);
1342         if (fd < 0)
1343                 return fd;
1344
1345         (void) unlink(p);
1346
1347         return fd;
1348 }
1349
1350 #if 0 /// UNNEEDED by elogind
1351 int open_tmpfile_linkable(const char *target, int flags, char **ret_path) {
1352         _cleanup_free_ char *tmp = NULL;
1353         int r, fd;
1354
1355         assert(target);
1356         assert(ret_path);
1357
1358         /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */
1359         assert((flags & O_EXCL) == 0);
1360
1361         /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in
1362          * which case "ret_path" will be returned as NULL. If not possible a the tempoary path name used is returned in
1363          * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */
1364
1365         {
1366                 _cleanup_free_ char *dn = NULL;
1367
1368                 dn = dirname_malloc(target);
1369                 if (!dn)
1370                         return -ENOMEM;
1371
1372                 fd = open(dn, O_TMPFILE|flags, 0640);
1373                 if (fd >= 0) {
1374                         *ret_path = NULL;
1375                         return fd;
1376                 }
1377
1378                 log_debug_errno(errno, "Failed to use O_TMPFILE on %s: %m", dn);
1379         }
1380
1381         r = tempfn_random(target, NULL, &tmp);
1382         if (r < 0)
1383                 return r;
1384
1385         fd = open(tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640);
1386         if (fd < 0)
1387                 return -errno;
1388
1389         *ret_path = tmp;
1390         tmp = NULL;
1391
1392         return fd;
1393 }
1394 #endif // 0
1395
1396 int open_serialization_fd(const char *ident) {
1397         int fd = -1;
1398
1399         fd = memfd_create(ident, MFD_CLOEXEC);
1400         if (fd < 0) {
1401                 const char *path;
1402
1403                 path = getpid() == 1 ? "/run/systemd" : "/tmp";
1404                 fd = open_tmpfile_unlinkable(path, O_RDWR|O_CLOEXEC);
1405                 if (fd < 0)
1406                         return fd;
1407
1408                 log_debug("Serializing %s to %s.", ident, path);
1409         } else
1410                 log_debug("Serializing %s to memfd.", ident);
1411
1412         return fd;
1413 }
1414
1415 #if 0 /// UNNEEDED by elogind
1416 int link_tmpfile(int fd, const char *path, const char *target) {
1417
1418         assert(fd >= 0);
1419         assert(target);
1420
1421         /* Moves a temporary file created with open_tmpfile() above into its final place. if "path" is NULL an fd
1422          * created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE is not supported
1423          * on the directory, and renameat2() is used instead.
1424          *
1425          * Note that in both cases we will not replace existing files. This is because linkat() does not support this
1426          * operation currently (renameat2() does), and there is no nice way to emulate this. */
1427
1428         if (path) {
1429                 if (rename_noreplace(AT_FDCWD, path, AT_FDCWD, target) < 0)
1430                         return -errno;
1431         } else {
1432                 char proc_fd_path[strlen("/proc/self/fd/") + DECIMAL_STR_MAX(fd) + 1];
1433
1434                 xsprintf(proc_fd_path, "/proc/self/fd/%i", fd);
1435
1436                 if (linkat(AT_FDCWD, proc_fd_path, AT_FDCWD, target, AT_SYMLINK_FOLLOW) < 0)
1437                         return -errno;
1438         }
1439
1440         return 0;
1441 }
1442
1443 int read_nul_string(FILE *f, char **ret) {
1444         _cleanup_free_ char *x = NULL;
1445         size_t allocated = 0, n = 0;
1446
1447         assert(f);
1448         assert(ret);
1449
1450         /* Reads a NUL-terminated string from the specified file. */
1451
1452         for (;;) {
1453                 int c;
1454
1455                 if (!GREEDY_REALLOC(x, allocated, n+2))
1456                         return -ENOMEM;
1457
1458                 c = fgetc(f);
1459                 if (c == 0) /* Terminate at NUL byte */
1460                         break;
1461                 if (c == EOF) {
1462                         if (ferror(f))
1463                                 return -errno;
1464                         break; /* Terminate at EOF */
1465                 }
1466
1467                 x[n++] = (char) c;
1468         }
1469
1470         if (x)
1471                 x[n] = 0;
1472         else {
1473                 x = new0(char, 1);
1474                 if (!x)
1475                         return -ENOMEM;
1476         }
1477
1478         *ret = x;
1479         x = NULL;
1480
1481         return 0;
1482 }
1483
1484 int mkdtemp_malloc(const char *template, char **ret) {
1485         char *p;
1486
1487         assert(template);
1488         assert(ret);
1489
1490         p = strdup(template);
1491         if (!p)
1492                 return -ENOMEM;
1493
1494         if (!mkdtemp(p)) {
1495                 free(p);
1496                 return -errno;
1497         }
1498
1499         *ret = p;
1500         return 0;
1501 }
1502 #endif // 0