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