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