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