1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 
3 #include <fcntl.h>
4 #include <limits.h>
5 #include <stdio.h>
6 #include <unistd.h>
7 
8 #include "alloc-util.h"
9 #include "ctype.h"
10 #include "env-file.h"
11 #include "env-util.h"
12 #include "errno-util.h"
13 #include "fd-util.h"
14 #include "fileio.h"
15 #include "fs-util.h"
16 #include "io-util.h"
17 #include "parse-util.h"
18 #include "path-util.h"
19 #include "process-util.h"
20 #include "random-util.h"
21 #include "rm-rf.h"
22 #include "socket-util.h"
23 #include "string-util.h"
24 #include "strv.h"
25 #include "tests.h"
26 #include "tmpfile-util.h"
27 #include "util.h"
28 
TEST(parse_env_file)29 TEST(parse_env_file) {
30         _cleanup_(unlink_tempfilep) char
31                 t[] = "/tmp/test-fileio-in-XXXXXX",
32                 p[] = "/tmp/test-fileio-out-XXXXXX";
33         FILE *f;
34         _cleanup_free_ char *one = NULL, *two = NULL, *three = NULL, *four = NULL, *five = NULL,
35                         *six = NULL, *seven = NULL, *eight = NULL, *nine = NULL, *ten = NULL,
36                         *eleven = NULL, *twelve = NULL, *thirteen = NULL;
37         _cleanup_strv_free_ char **a = NULL, **b = NULL;
38         unsigned k;
39         int r;
40 
41         assert_se(fmkostemp_safe(t, "w", &f) == 0);
42         fputs("one=BAR   \n"
43               "# comment\n"
44               " # comment \n"
45               " ; comment \n"
46               "  two   =   bar    \n"
47               "invalid line\n"
48               "invalid line #comment\n"
49               "three = \"333\n"
50               "xxxx\"\n"
51               "four = \'44\\\"44\'\n"
52               "five = \"55\\\"55\" \"FIVE\" cinco   \n"
53               "six = seis sechs\\\n"
54               " sis\n"
55               "seven=\"sevenval\" #nocomment\n"
56               "eight=eightval #nocomment\n"
57               "export nine=nineval\n"
58               "ten=ignored\n"
59               "ten=ignored\n"
60               "ten=\n"
61               "eleven=\\value\n"
62               "twelve=\"\\value\"\n"
63               "thirteen='\\value'", f);
64 
65         fflush(f);
66         fclose(f);
67 
68         r = load_env_file(NULL, t, &a);
69         assert_se(r >= 0);
70 
71         STRV_FOREACH(i, a)
72                 log_info("Got: <%s>", *i);
73 
74         assert_se(streq_ptr(a[0], "one=BAR"));
75         assert_se(streq_ptr(a[1], "two=bar"));
76         assert_se(streq_ptr(a[2], "three=333\nxxxx"));
77         assert_se(streq_ptr(a[3], "four=44\\\"44"));
78         assert_se(streq_ptr(a[4], "five=55\"55FIVEcinco"));
79         assert_se(streq_ptr(a[5], "six=seis sechs sis"));
80         assert_se(streq_ptr(a[6], "seven=sevenval#nocomment"));
81         assert_se(streq_ptr(a[7], "eight=eightval #nocomment"));
82         assert_se(streq_ptr(a[8], "export nine=nineval"));
83         assert_se(streq_ptr(a[9], "ten="));
84         assert_se(streq_ptr(a[10], "eleven=value"));
85         assert_se(streq_ptr(a[11], "twelve=\\value"));
86         assert_se(streq_ptr(a[12], "thirteen=\\value"));
87         assert_se(a[13] == NULL);
88 
89         strv_env_clean(a);
90 
91         k = 0;
92         STRV_FOREACH(i, b) {
93                 log_info("Got2: <%s>", *i);
94                 assert_se(streq(*i, a[k++]));
95         }
96 
97         r = parse_env_file(
98                         NULL, t,
99                        "one", &one,
100                        "two", &two,
101                        "three", &three,
102                        "four", &four,
103                        "five", &five,
104                        "six", &six,
105                        "seven", &seven,
106                        "eight", &eight,
107                        "export nine", &nine,
108                        "ten", &ten,
109                        "eleven", &eleven,
110                        "twelve", &twelve,
111                        "thirteen", &thirteen);
112         assert_se(r == 0);
113 
114         log_info("one=[%s]", strna(one));
115         log_info("two=[%s]", strna(two));
116         log_info("three=[%s]", strna(three));
117         log_info("four=[%s]", strna(four));
118         log_info("five=[%s]", strna(five));
119         log_info("six=[%s]", strna(six));
120         log_info("seven=[%s]", strna(seven));
121         log_info("eight=[%s]", strna(eight));
122         log_info("export nine=[%s]", strna(nine));
123         log_info("ten=[%s]", strna(nine));
124         log_info("eleven=[%s]", strna(eleven));
125         log_info("twelve=[%s]", strna(twelve));
126         log_info("thirteen=[%s]", strna(thirteen));
127 
128         assert_se(streq(one, "BAR"));
129         assert_se(streq(two, "bar"));
130         assert_se(streq(three, "333\nxxxx"));
131         assert_se(streq(four, "44\\\"44"));
132         assert_se(streq(five, "55\"55FIVEcinco"));
133         assert_se(streq(six, "seis sechs sis"));
134         assert_se(streq(seven, "sevenval#nocomment"));
135         assert_se(streq(eight, "eightval #nocomment"));
136         assert_se(streq(nine, "nineval"));
137         assert_se(ten == NULL);
138         assert_se(streq(eleven, "value"));
139         assert_se(streq(twelve, "\\value"));
140         assert_se(streq(thirteen, "\\value"));
141 
142         {
143                 /* prepare a temporary file to write the environment to */
144                 _cleanup_close_ int fd = mkostemp_safe(p);
145                 assert_se(fd >= 0);
146         }
147 
148         r = write_env_file(p, a);
149         assert_se(r >= 0);
150 
151         r = load_env_file(NULL, p, &b);
152         assert_se(r >= 0);
153 }
154 
test_one_shell_var(const char * file,const char * variable,const char * value)155 static void test_one_shell_var(const char *file, const char *variable, const char *value) {
156         _cleanup_free_ char *cmd = NULL, *from_shell = NULL;
157         _cleanup_pclose_ FILE *f = NULL;
158         size_t sz;
159 
160         assert_se(cmd = strjoin(". ", file, " && /bin/echo -n \"$", variable, "\""));
161         assert_se(f = popen(cmd, "re"));
162         assert_se(read_full_stream(f, &from_shell, &sz) >= 0);
163         assert_se(sz == strlen(value));
164         assert_se(streq(from_shell, value));
165 }
166 
TEST(parse_multiline_env_file)167 TEST(parse_multiline_env_file) {
168         _cleanup_(unlink_tempfilep) char
169                 t[] = "/tmp/test-fileio-in-XXXXXX",
170                 p[] = "/tmp/test-fileio-out-XXXXXX";
171         FILE *f;
172         _cleanup_strv_free_ char **a = NULL, **b = NULL;
173         int r;
174 
175         assert_se(fmkostemp_safe(t, "w", &f) == 0);
176         fputs("one=BAR\\\n"
177               "\\ \\ \\ \\ VAR\\\n"
178               "\\\tGAR\n"
179               "#comment\n"
180               "two=\"bar\\\n"
181               "    var\\\n"
182               "\tgar\"\n"
183               "#comment\n"
184               "tri=\"bar \\\n"
185               "    var \\\n"
186               "\tgar \"\n", f);
187 
188         assert_se(fflush_and_check(f) >= 0);
189         fclose(f);
190 
191         test_one_shell_var(t, "one", "BAR    VAR\tGAR");
192         test_one_shell_var(t, "two", "bar    var\tgar");
193         test_one_shell_var(t, "tri", "bar     var \tgar ");
194 
195         r = load_env_file(NULL, t, &a);
196         assert_se(r >= 0);
197 
198         STRV_FOREACH(i, a)
199                 log_info("Got: <%s>", *i);
200 
201         assert_se(streq_ptr(a[0], "one=BAR    VAR\tGAR"));
202         assert_se(streq_ptr(a[1], "two=bar    var\tgar"));
203         assert_se(streq_ptr(a[2], "tri=bar     var \tgar "));
204         assert_se(a[3] == NULL);
205 
206         {
207                 _cleanup_close_ int fd = mkostemp_safe(p);
208                 assert_se(fd >= 0);
209         }
210 
211         r = write_env_file(p, a);
212         assert_se(r >= 0);
213 
214         r = load_env_file(NULL, p, &b);
215         assert_se(r >= 0);
216 }
217 
TEST(merge_env_file)218 TEST(merge_env_file) {
219         _cleanup_(unlink_tempfilep) char t[] = "/tmp/test-fileio-XXXXXX";
220         _cleanup_fclose_ FILE *f = NULL;
221         _cleanup_strv_free_ char **a = NULL;
222         int r;
223 
224         assert_se(fmkostemp_safe(t, "w", &f) == 0);
225         log_info("/* %s (%s) */", __func__, t);
226 
227         r = write_string_stream(f,
228                                 "one=1   \n"
229                                 "twelve=${one}2\n"
230                                 "twentyone=2${one}\n"
231                                 "one=2\n"
232                                 "twentytwo=2${one}\n"
233                                 "xxx_minus_three=$xxx - 3\n"
234                                 "xxx=0x$one$one$one\n"
235                                 "yyy=${one:-fallback}\n"
236                                 "zzz=${one:+replacement}\n"
237                                 "zzzz=${foobar:-${nothing}}\n"
238                                 "zzzzz=${nothing:+${nothing}}\n"
239                                 , WRITE_STRING_FILE_AVOID_NEWLINE);
240         assert_se(r >= 0);
241 
242         r = merge_env_file(&a, NULL, t);
243         assert_se(r >= 0);
244         strv_sort(a);
245 
246         STRV_FOREACH(i, a)
247                 log_info("Got: <%s>", *i);
248 
249         assert_se(streq(a[0], "one=2"));
250         assert_se(streq(a[1], "twelve=12"));
251         assert_se(streq(a[2], "twentyone=21"));
252         assert_se(streq(a[3], "twentytwo=22"));
253         assert_se(streq(a[4], "xxx=0x222"));
254         assert_se(streq(a[5], "xxx_minus_three= - 3"));
255         assert_se(streq(a[6], "yyy=2"));
256         assert_se(streq(a[7], "zzz=replacement"));
257         assert_se(streq(a[8], "zzzz="));
258         assert_se(streq(a[9], "zzzzz="));
259         assert_se(a[10] == NULL);
260 
261         r = merge_env_file(&a, NULL, t);
262         assert_se(r >= 0);
263         strv_sort(a);
264 
265         STRV_FOREACH(i, a)
266                 log_info("Got2: <%s>", *i);
267 
268         assert_se(streq(a[0], "one=2"));
269         assert_se(streq(a[1], "twelve=12"));
270         assert_se(streq(a[2], "twentyone=21"));
271         assert_se(streq(a[3], "twentytwo=22"));
272         assert_se(streq(a[4], "xxx=0x222"));
273         assert_se(streq(a[5], "xxx_minus_three=0x222 - 3"));
274         assert_se(streq(a[6], "yyy=2"));
275         assert_se(streq(a[7], "zzz=replacement"));
276         assert_se(streq(a[8], "zzzz="));
277         assert_se(streq(a[9], "zzzzz="));
278         assert_se(a[10] == NULL);
279 }
280 
TEST(merge_env_file_invalid)281 TEST(merge_env_file_invalid) {
282         _cleanup_(unlink_tempfilep) char t[] = "/tmp/test-fileio-XXXXXX";
283         _cleanup_fclose_ FILE *f = NULL;
284         _cleanup_strv_free_ char **a = NULL;
285         int r;
286 
287         assert_se(fmkostemp_safe(t, "w", &f) == 0);
288         log_info("/* %s (%s) */", __func__, t);
289 
290         r = write_string_stream(f,
291                                 "unset one   \n"
292                                 "unset one=   \n"
293                                 "unset one=1   \n"
294                                 "one   \n"
295                                 "one =  \n"
296                                 "one two =\n"
297                                 "\x20two=\n"
298                                 "#comment=comment\n"
299                                 ";comment2=comment2\n"
300                                 "#\n"
301                                 "\n\n"                  /* empty line */
302                                 , WRITE_STRING_FILE_AVOID_NEWLINE);
303         assert_se(r >= 0);
304 
305         r = merge_env_file(&a, NULL, t);
306         assert_se(r >= 0);
307 
308         STRV_FOREACH(i, a)
309                 log_info("Got: <%s>", *i);
310 
311         assert_se(strv_isempty(a));
312 }
313 
TEST(executable_is_script)314 TEST(executable_is_script) {
315         _cleanup_(unlink_tempfilep) char t[] = "/tmp/test-fileio-XXXXXX";
316         _cleanup_fclose_ FILE *f = NULL;
317         char *command;
318         int r;
319 
320         assert_se(fmkostemp_safe(t, "w", &f) == 0);
321         fputs("#! /bin/script -a -b \ngoo goo", f);
322         fflush(f);
323 
324         r = executable_is_script(t, &command);
325         assert_se(r > 0);
326         assert_se(streq(command, "/bin/script"));
327         free(command);
328 
329         r = executable_is_script("/bin/sh", &command);
330         assert_se(r == 0);
331 
332         r = executable_is_script("/usr/bin/yum", &command);
333         assert_se(r > 0 || r == -ENOENT);
334         if (r > 0) {
335                 assert_se(startswith(command, "/"));
336                 free(command);
337         }
338 }
339 
TEST(status_field)340 TEST(status_field) {
341         _cleanup_free_ char *t = NULL, *p = NULL, *s = NULL, *z = NULL;
342         unsigned long long total = 0, buffers = 0;
343         int r;
344 
345         assert_se(get_proc_field("/proc/self/status", "Threads", WHITESPACE, &t) == 0);
346         puts(t);
347         assert_se(streq(t, "1"));
348 
349         r = get_proc_field("/proc/meminfo", "MemTotal", WHITESPACE, &p);
350         if (r != -ENOENT) {
351                 assert_se(r == 0);
352                 puts(p);
353                 assert_se(safe_atollu(p, &total) == 0);
354         }
355 
356         r = get_proc_field("/proc/meminfo", "Buffers", WHITESPACE, &s);
357         if (r != -ENOENT) {
358                 assert_se(r == 0);
359                 puts(s);
360                 assert_se(safe_atollu(s, &buffers) == 0);
361         }
362 
363         if (p)
364                 assert_se(buffers < total);
365 
366         /* Seccomp should be a good test for field full of zeros. */
367         r = get_proc_field("/proc/meminfo", "Seccomp", WHITESPACE, &z);
368         if (r != -ENOENT) {
369                 assert_se(r == 0);
370                 puts(z);
371                 assert_se(safe_atollu(z, &buffers) == 0);
372         }
373 }
374 
TEST(capeff)375 TEST(capeff) {
376         for (int pid = 0; pid < 2; pid++) {
377                 _cleanup_free_ char *capeff = NULL;
378                 int r, p;
379 
380                 r = get_process_capeff(0, &capeff);
381                 log_info("capeff: '%s' (r=%d)", capeff, r);
382 
383                 if (IN_SET(r, -ENOENT, -EPERM))
384                         return;
385 
386                 assert_se(r == 0);
387                 assert_se(*capeff);
388                 p = capeff[strspn(capeff, HEXDIGITS)];
389                 assert_se(!p || isspace(p));
390         }
391 }
392 
TEST(write_string_stream)393 TEST(write_string_stream) {
394         _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-write_string_stream-XXXXXX";
395         _cleanup_fclose_ FILE *f = NULL;
396         int fd;
397         char buf[64];
398 
399         fd = mkostemp_safe(fn);
400         assert_se(fd >= 0);
401 
402         f = fdopen(fd, "r");
403         assert_se(f);
404         assert_se(write_string_stream(f, "boohoo", 0) < 0);
405         f = safe_fclose(f);
406 
407         f = fopen(fn, "r+");
408         assert_se(f);
409 
410         assert_se(write_string_stream(f, "boohoo", 0) == 0);
411         rewind(f);
412 
413         assert_se(fgets(buf, sizeof(buf), f));
414         assert_se(streq(buf, "boohoo\n"));
415         f = safe_fclose(f);
416 
417         f = fopen(fn, "w+");
418         assert_se(f);
419 
420         assert_se(write_string_stream(f, "boohoo", WRITE_STRING_FILE_AVOID_NEWLINE) == 0);
421         rewind(f);
422 
423         assert_se(fgets(buf, sizeof(buf), f));
424         printf(">%s<", buf);
425         assert_se(streq(buf, "boohoo"));
426 }
427 
TEST(write_string_file)428 TEST(write_string_file) {
429         _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-write_string_file-XXXXXX";
430         char buf[64] = {};
431         _cleanup_close_ int fd;
432 
433         fd = mkostemp_safe(fn);
434         assert_se(fd >= 0);
435 
436         assert_se(write_string_file(fn, "boohoo", WRITE_STRING_FILE_CREATE) == 0);
437 
438         assert_se(read(fd, buf, sizeof(buf)) == 7);
439         assert_se(streq(buf, "boohoo\n"));
440 }
441 
TEST(write_string_file_no_create)442 TEST(write_string_file_no_create) {
443         _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-write_string_file_no_create-XXXXXX";
444         _cleanup_close_ int fd;
445         char buf[64] = {};
446 
447         fd = mkostemp_safe(fn);
448         assert_se(fd >= 0);
449 
450         assert_se(write_string_file("/a/file/which/does/not/exists/i/guess", "boohoo", 0) < 0);
451         assert_se(write_string_file(fn, "boohoo", 0) == 0);
452 
453         assert_se(read(fd, buf, sizeof buf) == (ssize_t) strlen("boohoo\n"));
454         assert_se(streq(buf, "boohoo\n"));
455 }
456 
TEST(write_string_file_verify)457 TEST(write_string_file_verify) {
458         _cleanup_free_ char *buf = NULL, *buf2 = NULL;
459         int r;
460 
461         r = read_one_line_file("/proc/version", &buf);
462         if (ERRNO_IS_PRIVILEGE(r))
463                 return;
464         assert_se(r >= 0);
465         assert_se(buf2 = strjoin(buf, "\n"));
466 
467         r = write_string_file("/proc/version", buf, 0);
468         assert_se(IN_SET(r, -EACCES, -EIO));
469         r = write_string_file("/proc/version", buf2, 0);
470         assert_se(IN_SET(r, -EACCES, -EIO));
471 
472         assert_se(write_string_file("/proc/version", buf, WRITE_STRING_FILE_VERIFY_ON_FAILURE) == 0);
473         assert_se(write_string_file("/proc/version", buf2, WRITE_STRING_FILE_VERIFY_ON_FAILURE) == 0);
474 
475         r = write_string_file("/proc/version", buf, WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_AVOID_NEWLINE);
476         assert_se(IN_SET(r, -EACCES, -EIO));
477         assert_se(write_string_file("/proc/version", buf2, WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_AVOID_NEWLINE) == 0);
478 }
479 
TEST(load_env_file_pairs)480 TEST(load_env_file_pairs) {
481         _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-load_env_file_pairs-XXXXXX";
482         int fd, r;
483         _cleanup_fclose_ FILE *f = NULL;
484         _cleanup_strv_free_ char **l = NULL;
485 
486         fd = mkostemp_safe(fn);
487         assert_se(fd >= 0);
488 
489         r = write_string_file(fn,
490                         "NAME=\"Arch Linux\"\n"
491                         "ID=arch\n"
492                         "PRETTY_NAME=\"Arch Linux\"\n"
493                         "ANSI_COLOR=\"0;36\"\n"
494                         "HOME_URL=\"https://www.archlinux.org/\"\n"
495                         "SUPPORT_URL=\"https://bbs.archlinux.org/\"\n"
496                         "BUG_REPORT_URL=\"https://bugs.archlinux.org/\"\n",
497                         WRITE_STRING_FILE_CREATE);
498         assert_se(r == 0);
499 
500         f = fdopen(fd, "r");
501         assert_se(f);
502 
503         r = load_env_file_pairs(f, fn, &l);
504         assert_se(r >= 0);
505 
506         assert_se(strv_length(l) == 14);
507         STRV_FOREACH_PAIR(k, v, l) {
508                 assert_se(STR_IN_SET(*k, "NAME", "ID", "PRETTY_NAME", "ANSI_COLOR", "HOME_URL", "SUPPORT_URL", "BUG_REPORT_URL"));
509                 printf("%s=%s\n", *k, *v);
510                 if (streq(*k, "NAME")) assert_se(streq(*v, "Arch Linux"));
511                 if (streq(*k, "ID")) assert_se(streq(*v, "arch"));
512                 if (streq(*k, "PRETTY_NAME")) assert_se(streq(*v, "Arch Linux"));
513                 if (streq(*k, "ANSI_COLOR")) assert_se(streq(*v, "0;36"));
514                 if (streq(*k, "HOME_URL")) assert_se(streq(*v, "https://www.archlinux.org/"));
515                 if (streq(*k, "SUPPORT_URL")) assert_se(streq(*v, "https://bbs.archlinux.org/"));
516                 if (streq(*k, "BUG_REPORT_URL")) assert_se(streq(*v, "https://bugs.archlinux.org/"));
517         }
518 }
519 
TEST(search_and_fopen)520 TEST(search_and_fopen) {
521         static const char* const dirs[] = {
522                 "/tmp/foo/bar",
523                 "/tmp",
524                 NULL
525         };
526         char name[] = "/tmp/test-search_and_fopen.XXXXXX";
527         _cleanup_fclose_ FILE *f = NULL;
528         _cleanup_free_ char *p = NULL;
529         _cleanup_close_ int fd = -1;
530         const char *e;
531         int r;
532 
533         fd = mkostemp_safe(name);
534         assert_se(fd >= 0);
535         fd = safe_close(fd);
536 
537         r = search_and_fopen(basename(name), "re", NULL, (const char**) dirs, &f, &p);
538         assert_se(r >= 0);
539         assert_se(e = path_startswith(p, "/tmp/"));
540         assert_se(streq(basename(name), e));
541         f = safe_fclose(f);
542         p = mfree(p);
543 
544         r = search_and_fopen(name, "re", NULL, (const char**) dirs, &f, &p);
545         assert_se(r >= 0);
546         assert_se(path_equal(name, p));
547         f = safe_fclose(f);
548         p = mfree(p);
549 
550         r = search_and_fopen(basename(name), "re", "/", (const char**) dirs, &f, &p);
551         assert_se(r >= 0);
552         assert_se(e = path_startswith(p, "/tmp/"));
553         assert_se(streq(basename(name), e));
554         f = safe_fclose(f);
555         p = mfree(p);
556 
557         r = search_and_fopen("/a/file/which/does/not/exist/i/guess", "r", NULL, (const char**) dirs, &f, &p);
558         assert_se(r == -ENOENT);
559         r = search_and_fopen("afilewhichdoesnotexistiguess", "r", NULL, (const char**) dirs, &f, &p);
560         assert_se(r == -ENOENT);
561 
562         r = unlink(name);
563         assert_se(r == 0);
564 
565         r = search_and_fopen(basename(name), "r", NULL, (const char**) dirs, &f, &p);
566         assert_se(r == -ENOENT);
567 }
568 
TEST(search_and_fopen_nulstr)569 TEST(search_and_fopen_nulstr) {
570         static const char dirs[] =
571                 "/tmp/foo/bar\0"
572                 "/tmp\0";
573 
574         _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-search_and_fopen.XXXXXX";
575         _cleanup_fclose_ FILE *f = NULL;
576         _cleanup_free_ char *p = NULL;
577         _cleanup_close_ int fd = -1;
578         const char *e;
579         int r;
580 
581         fd = mkostemp_safe(name);
582         assert_se(fd >= 0);
583         fd = safe_close(fd);
584 
585         r = search_and_fopen_nulstr(basename(name), "re", NULL, dirs, &f, &p);
586         assert_se(r >= 0);
587         assert_se(e = path_startswith(p, "/tmp/"));
588         assert_se(streq(basename(name), e));
589         f = safe_fclose(f);
590         p = mfree(p);
591 
592         r = search_and_fopen_nulstr(name, "re", NULL, dirs, &f, &p);
593         assert_se(r >= 0);
594         assert_se(path_equal(name, p));
595         f = safe_fclose(f);
596         p = mfree(p);
597 
598         r = search_and_fopen_nulstr("/a/file/which/does/not/exist/i/guess", "r", NULL, dirs, &f, &p);
599         assert_se(r == -ENOENT);
600         r = search_and_fopen_nulstr("afilewhichdoesnotexistiguess", "r", NULL, dirs, &f, &p);
601         assert_se(r == -ENOENT);
602 
603         r = unlink(name);
604         assert_se(r == 0);
605 
606         r = search_and_fopen_nulstr(basename(name), "r", NULL, dirs, &f, &p);
607         assert_se(r == -ENOENT);
608 }
609 
TEST(writing_tmpfile)610 TEST(writing_tmpfile) {
611         _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-systemd_writing_tmpfile.XXXXXX";
612         _cleanup_free_ char *contents = NULL;
613         size_t size;
614         _cleanup_close_ int fd = -1;
615         int r;
616 
617         struct iovec iov[] = {
618                 IOVEC_MAKE_STRING("abc\n"),
619                 IOVEC_MAKE_STRING(ALPHANUMERICAL "\n"),
620                 IOVEC_MAKE_STRING(""),
621         };
622 
623         fd = mkostemp_safe(name);
624         printf("tmpfile: %s", name);
625 
626         r = writev(fd, iov, 3);
627         assert_se(r >= 0);
628 
629         r = read_full_file(name, &contents, &size);
630         assert_se(r == 0);
631         printf("contents: %s", contents);
632         assert_se(streq(contents, "abc\n" ALPHANUMERICAL "\n"));
633 }
634 
TEST(tempfn)635 TEST(tempfn) {
636         char *ret = NULL, *p;
637 
638         assert_se(tempfn_xxxxxx("/foo/bar/waldo", NULL, &ret) >= 0);
639         assert_se(streq_ptr(ret, "/foo/bar/.#waldoXXXXXX"));
640         free(ret);
641 
642         assert_se(tempfn_xxxxxx("/foo/bar/waldo", "[miau]", &ret) >= 0);
643         assert_se(streq_ptr(ret, "/foo/bar/.#[miau]waldoXXXXXX"));
644         free(ret);
645 
646         assert_se(tempfn_random("/foo/bar/waldo", NULL, &ret) >= 0);
647         assert_se(p = startswith(ret, "/foo/bar/.#waldo"));
648         assert_se(strlen(p) == 16);
649         assert_se(in_charset(p, "0123456789abcdef"));
650         free(ret);
651 
652         assert_se(tempfn_random("/foo/bar/waldo", "[wuff]", &ret) >= 0);
653         assert_se(p = startswith(ret, "/foo/bar/.#[wuff]waldo"));
654         assert_se(strlen(p) == 16);
655         assert_se(in_charset(p, "0123456789abcdef"));
656         free(ret);
657 
658         assert_se(tempfn_random_child("/foo/bar/waldo", NULL, &ret) >= 0);
659         assert_se(p = startswith(ret, "/foo/bar/waldo/.#"));
660         assert_se(strlen(p) == 16);
661         assert_se(in_charset(p, "0123456789abcdef"));
662         free(ret);
663 
664         assert_se(tempfn_random_child("/foo/bar/waldo", "[kikiriki]", &ret) >= 0);
665         assert_se(p = startswith(ret, "/foo/bar/waldo/.#[kikiriki]"));
666         assert_se(strlen(p) == 16);
667         assert_se(in_charset(p, "0123456789abcdef"));
668         free(ret);
669 }
670 
671 static const char chars[] =
672         "Aąę„”\n루\377";
673 
674 DISABLE_WARNING_TYPE_LIMITS;
675 
TEST(fgetc)676 TEST(fgetc) {
677         _cleanup_fclose_ FILE *f = NULL;
678         char c;
679 
680         assert_se(f = fmemopen_unlocked((void*) chars, sizeof(chars), "re"));
681 
682         for (size_t i = 0; i < sizeof(chars); i++) {
683                 assert_se(safe_fgetc(f, &c) == 1);
684                 assert_se(c == chars[i]);
685 
686                 if (ungetc(c, f) == EOF) {
687                         /* EOF is -1, and hence we can't push value 255 in this way – if char is signed */
688                         assert_se(c == (char) EOF);
689                         assert_se(CHAR_MIN == -128); /* verify that char is signed on this platform */
690                 } else {
691                         assert_se(safe_fgetc(f, &c) == 1);
692                         assert_se(c == chars[i]);
693                 }
694 
695                 /* But it works when we push it properly cast */
696                 assert_se(ungetc((unsigned char) c, f) != EOF);
697                 assert_se(safe_fgetc(f, &c) == 1);
698                 assert_se(c == chars[i]);
699         }
700 
701         assert_se(safe_fgetc(f, &c) == 0);
702 }
703 
704 REENABLE_WARNING;
705 
706 static const char buffer[] =
707         "Some test data\n"
708         "루Non-ascii chars: ąę„”\n"
709         "terminators\r\n"
710         "and even more\n\r"
711         "now the same with a NUL\n\0"
712         "and more\r\0"
713         "and even more\r\n\0"
714         "and yet even more\n\r\0"
715         "With newlines, and a NUL byte\0"
716         "\n"
717         "an empty line\n"
718         "an ignored line\n"
719         "and a very long line that is supposed to be truncated, because it is so long\n";
720 
test_read_line_one_file(FILE * f)721 static void test_read_line_one_file(FILE *f) {
722         _cleanup_free_ char *line = NULL;
723 
724         assert_se(read_line(f, SIZE_MAX, &line) == 15 && streq(line, "Some test data"));
725         line = mfree(line);
726 
727         assert_se(read_line(f, SIZE_MAX, &line) > 0 && streq(line, "루Non-ascii chars: ąę„”"));
728         line = mfree(line);
729 
730         assert_se(read_line(f, SIZE_MAX, &line) == 13 && streq(line, "terminators"));
731         line = mfree(line);
732 
733         assert_se(read_line(f, SIZE_MAX, &line) == 15 && streq(line, "and even more"));
734         line = mfree(line);
735 
736         assert_se(read_line(f, SIZE_MAX, &line) == 25 && streq(line, "now the same with a NUL"));
737         line = mfree(line);
738 
739         assert_se(read_line(f, SIZE_MAX, &line) == 10 && streq(line, "and more"));
740         line = mfree(line);
741 
742         assert_se(read_line(f, SIZE_MAX, &line) == 16 && streq(line, "and even more"));
743         line = mfree(line);
744 
745         assert_se(read_line(f, SIZE_MAX, &line) == 20 && streq(line, "and yet even more"));
746         line = mfree(line);
747 
748         assert_se(read_line(f, 1024, &line) == 30 && streq(line, "With newlines, and a NUL byte"));
749         line = mfree(line);
750 
751         assert_se(read_line(f, 1024, &line) == 1 && streq(line, ""));
752         line = mfree(line);
753 
754         assert_se(read_line(f, 1024, &line) == 14 && streq(line, "an empty line"));
755         line = mfree(line);
756 
757         assert_se(read_line(f, SIZE_MAX, NULL) == 16);
758 
759         assert_se(read_line(f, 16, &line) == -ENOBUFS);
760         line = mfree(line);
761 
762         /* read_line() stopped when it hit the limit, that means when we continue reading we'll read at the first
763          * character after the previous limit. Let's make use of that to continue our test. */
764         assert_se(read_line(f, 1024, &line) == 62 && streq(line, "line that is supposed to be truncated, because it is so long"));
765         line = mfree(line);
766 
767         assert_se(read_line(f, 1024, &line) == 0 && streq(line, ""));
768 }
769 
TEST(read_line1)770 TEST(read_line1) {
771         _cleanup_fclose_ FILE *f = NULL;
772 
773         assert_se(f = fmemopen_unlocked((void*) buffer, sizeof(buffer), "re"));
774         test_read_line_one_file(f);
775 }
776 
TEST(read_line2)777 TEST(read_line2) {
778         _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-fileio.XXXXXX";
779         int fd;
780         _cleanup_fclose_ FILE *f = NULL;
781 
782         fd = mkostemp_safe(name);
783         assert_se(fd >= 0);
784         assert_se((size_t) write(fd, buffer, sizeof(buffer)) == sizeof(buffer));
785 
786         assert_se(lseek(fd, 0, SEEK_SET) == 0);
787         assert_se(f = fdopen(fd, "r"));
788 
789         test_read_line_one_file(f);
790 }
791 
TEST(read_line3)792 TEST(read_line3) {
793         _cleanup_fclose_ FILE *f = NULL;
794         _cleanup_free_ char *line = NULL;
795         int r;
796 
797         f = fopen("/proc/uptime", "re");
798         if (!f && IN_SET(errno, ENOENT, EPERM))
799                 return;
800         assert_se(f);
801 
802         r = read_line(f, LINE_MAX, &line);
803         assert_se(r >= 0);
804         if (r == 0)
805                 assert_se(line && isempty(line));
806         else
807                 assert_se((size_t) r == strlen(line) + 1);
808         assert_se(read_line(f, LINE_MAX, NULL) == 0);
809 }
810 
TEST(read_line4)811 TEST(read_line4) {
812         static const struct {
813                 size_t length;
814                 const char *string;
815         } eof_endings[] = {
816                 /* Each of these will be followed by EOF and should generate the one same single string */
817                 { 3, "foo" },
818                 { 4, "foo\n" },
819                 { 4, "foo\r" },
820                 { 4, "foo\0" },
821                 { 5, "foo\n\0" },
822                 { 5, "foo\r\0" },
823                 { 5, "foo\r\n" },
824                 { 5, "foo\n\r" },
825                 { 6, "foo\r\n\0" },
826                 { 6, "foo\n\r\0" },
827         };
828 
829         int r;
830 
831         for (size_t i = 0; i < ELEMENTSOF(eof_endings); i++) {
832                 _cleanup_fclose_ FILE *f = NULL;
833                 _cleanup_free_ char *s = NULL;
834 
835                 assert_se(f = fmemopen_unlocked((void*) eof_endings[i].string, eof_endings[i].length, "r"));
836 
837                 r = read_line(f, SIZE_MAX, &s);
838                 assert_se((size_t) r == eof_endings[i].length);
839                 assert_se(streq_ptr(s, "foo"));
840 
841                 assert_se(read_line(f, SIZE_MAX, NULL) == 0); /* Ensure we hit EOF */
842         }
843 }
844 
TEST(read_nul_string)845 TEST(read_nul_string) {
846         static const char test[] = "string nr. 1\0"
847                 "string nr. 2\n\0"
848                 "\377empty string follows\0"
849                 "\0"
850                 "final string\n is empty\0"
851                 "\0";
852 
853         _cleanup_fclose_ FILE *f = NULL;
854         _cleanup_free_ char *s = NULL;
855 
856         assert_se(f = fmemopen_unlocked((void*) test, sizeof(test)-1, "r"));
857 
858         assert_se(read_nul_string(f, LONG_LINE_MAX, &s) == 13 && streq_ptr(s, "string nr. 1"));
859         s = mfree(s);
860 
861         assert_se(read_nul_string(f, LONG_LINE_MAX, &s) == 14 && streq_ptr(s, "string nr. 2\n"));
862         s = mfree(s);
863 
864         assert_se(read_nul_string(f, LONG_LINE_MAX, &s) == 22 && streq_ptr(s, "\377empty string follows"));
865         s = mfree(s);
866 
867         assert_se(read_nul_string(f, LONG_LINE_MAX, &s) == 1 && streq_ptr(s, ""));
868         s = mfree(s);
869 
870         assert_se(read_nul_string(f, LONG_LINE_MAX, &s) == 23 && streq_ptr(s, "final string\n is empty"));
871         s = mfree(s);
872 
873         assert_se(read_nul_string(f, LONG_LINE_MAX, &s) == 1 && streq_ptr(s, ""));
874         s = mfree(s);
875 
876         assert_se(read_nul_string(f, LONG_LINE_MAX, &s) == 0 && streq_ptr(s, ""));
877 }
878 
TEST(read_full_file_socket)879 TEST(read_full_file_socket) {
880         _cleanup_(rm_rf_physical_and_freep) char *z = NULL;
881         _cleanup_close_ int listener = -1;
882         _cleanup_free_ char *data = NULL, *clientname = NULL;
883         union sockaddr_union sa;
884         const char *j;
885         size_t size;
886         pid_t pid;
887         int r;
888 
889         listener = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC, 0);
890         assert_se(listener >= 0);
891 
892         assert_se(mkdtemp_malloc(NULL, &z) >= 0);
893         j = strjoina(z, "/socket");
894 
895         assert_se(sockaddr_un_set_path(&sa.un, j) >= 0);
896 
897         assert_se(bind(listener, &sa.sa, SOCKADDR_UN_LEN(sa.un)) >= 0);
898         assert_se(listen(listener, 1) >= 0);
899 
900         /* Bind the *client* socket to some randomized name, to verify that this works correctly. */
901         assert_se(asprintf(&clientname, "@%" PRIx64 "/test-bindname", random_u64()) >= 0);
902 
903         r = safe_fork("(server)", FORK_DEATHSIG|FORK_LOG, &pid);
904         assert_se(r >= 0);
905         if (r == 0) {
906                 union sockaddr_union peer = {};
907                 socklen_t peerlen = sizeof(peer);
908                 _cleanup_close_ int rfd = -1;
909                 /* child */
910 
911                 rfd = accept4(listener, NULL, 0, SOCK_CLOEXEC);
912                 assert_se(rfd >= 0);
913 
914                 assert_se(getpeername(rfd, &peer.sa, &peerlen) >= 0);
915 
916                 assert_se(peer.un.sun_family == AF_UNIX);
917                 assert_se(peerlen > offsetof(struct sockaddr_un, sun_path));
918                 assert_se(peer.un.sun_path[0] == 0);
919                 assert_se(streq(peer.un.sun_path + 1, clientname + 1));
920 
921 #define TEST_STR "This is a test\nreally."
922 
923                 assert_se(write(rfd, TEST_STR, strlen(TEST_STR)) == strlen(TEST_STR));
924                 _exit(EXIT_SUCCESS);
925         }
926 
927         assert_se(read_full_file_full(AT_FDCWD, j, UINT64_MAX, SIZE_MAX, 0, NULL, &data, &size) == -ENXIO);
928         assert_se(read_full_file_full(AT_FDCWD, j, UINT64_MAX, SIZE_MAX, READ_FULL_FILE_CONNECT_SOCKET, clientname, &data, &size) >= 0);
929         assert_se(size == strlen(TEST_STR));
930         assert_se(streq(data, TEST_STR));
931 
932         assert_se(wait_for_terminate_and_check("(server)", pid, WAIT_LOG) >= 0);
933 #undef TEST_STR
934 }
935 
TEST(read_full_file_offset_size)936 TEST(read_full_file_offset_size) {
937         _cleanup_fclose_ FILE *f = NULL;
938         _cleanup_(unlink_and_freep) char *fn = NULL;
939         _cleanup_free_ char *rbuf = NULL;
940         size_t rbuf_size;
941         uint8_t buf[4711];
942 
943         random_bytes(buf, sizeof(buf));
944 
945         assert_se(tempfn_random_child(NULL, NULL, &fn) >= 0);
946         assert_se(f = fopen(fn, "we"));
947         assert_se(fwrite(buf, 1, sizeof(buf), f) == sizeof(buf));
948         assert_se(fflush_and_check(f) >= 0);
949 
950         assert_se(read_full_file_full(AT_FDCWD, fn, UINT64_MAX, SIZE_MAX, 0, NULL, &rbuf, &rbuf_size) >= 0);
951         assert_se(rbuf_size == sizeof(buf));
952         assert_se(memcmp(buf, rbuf, rbuf_size) == 0);
953         rbuf = mfree(rbuf);
954 
955         assert_se(read_full_file_full(AT_FDCWD, fn, UINT64_MAX, 128, 0, NULL, &rbuf, &rbuf_size) >= 0);
956         assert_se(rbuf_size == 128);
957         assert_se(memcmp(buf, rbuf, rbuf_size) == 0);
958         rbuf = mfree(rbuf);
959 
960         assert_se(read_full_file_full(AT_FDCWD, fn, UINT64_MAX, 128, READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, &rbuf, &rbuf_size) == -E2BIG);
961         assert_se(read_full_file_full(AT_FDCWD, fn, UINT64_MAX, sizeof(buf)-1, READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, &rbuf, &rbuf_size) == -E2BIG);
962         assert_se(read_full_file_full(AT_FDCWD, fn, UINT64_MAX, sizeof(buf), READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, &rbuf, &rbuf_size) >= 0);
963         assert_se(rbuf_size == sizeof(buf));
964         assert_se(memcmp(buf, rbuf, rbuf_size) == 0);
965         rbuf = mfree(rbuf);
966 
967         assert_se(read_full_file_full(AT_FDCWD, fn, 47, 128, READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, &rbuf, &rbuf_size) == -E2BIG);
968         assert_se(read_full_file_full(AT_FDCWD, fn, 47, sizeof(buf)-47-1, READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, &rbuf, &rbuf_size) == -E2BIG);
969         assert_se(read_full_file_full(AT_FDCWD, fn, 47, sizeof(buf)-47, READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, &rbuf, &rbuf_size) >= 0);
970         assert_se(rbuf_size == sizeof(buf)-47);
971         assert_se(memcmp(buf+47, rbuf, rbuf_size) == 0);
972         rbuf = mfree(rbuf);
973 
974         assert_se(read_full_file_full(AT_FDCWD, fn, UINT64_MAX, sizeof(buf)+1, READ_FULL_FILE_FAIL_WHEN_LARGER, NULL, &rbuf, &rbuf_size) >= 0);
975         assert_se(rbuf_size == sizeof(buf));
976         assert_se(memcmp(buf, rbuf, rbuf_size) == 0);
977         rbuf = mfree(rbuf);
978 
979         assert_se(read_full_file_full(AT_FDCWD, fn, 1234, SIZE_MAX, 0, NULL, &rbuf, &rbuf_size) >= 0);
980         assert_se(rbuf_size == sizeof(buf) - 1234);
981         assert_se(memcmp(buf + 1234, rbuf, rbuf_size) == 0);
982         rbuf = mfree(rbuf);
983 
984         assert_se(read_full_file_full(AT_FDCWD, fn, 2345, 777, 0, NULL, &rbuf, &rbuf_size) >= 0);
985         assert_se(rbuf_size == 777);
986         assert_se(memcmp(buf + 2345, rbuf, rbuf_size) == 0);
987         rbuf = mfree(rbuf);
988 
989         assert_se(read_full_file_full(AT_FDCWD, fn, 4700, 20, 0, NULL, &rbuf, &rbuf_size) >= 0);
990         assert_se(rbuf_size == 11);
991         assert_se(memcmp(buf + 4700, rbuf, rbuf_size) == 0);
992         rbuf = mfree(rbuf);
993 
994         assert_se(read_full_file_full(AT_FDCWD, fn, 10000, 99, 0, NULL, &rbuf, &rbuf_size) >= 0);
995         assert_se(rbuf_size == 0);
996         rbuf = mfree(rbuf);
997 }
998 
test_read_virtual_file_one(size_t max_size)999 static void test_read_virtual_file_one(size_t max_size) {
1000         int r;
1001 
1002         log_info("/* %s (max_size=%zu) */", __func__, max_size);
1003 
1004         FOREACH_STRING(filename,
1005                        "/proc/1/cmdline",
1006                        "/etc/nsswitch.conf",
1007                        "/sys/kernel/uevent_seqnum",
1008                        "/proc/kcore",
1009                        "/proc/kallsyms",
1010                        "/proc/self/exe",
1011                        "/proc/self/pagemap") {
1012 
1013                 _cleanup_free_ char *buf = NULL;
1014                 size_t size = 0;
1015 
1016                 r = read_virtual_file(filename, max_size, &buf, &size);
1017                 if (r < 0) {
1018                         log_info_errno(r, "read_virtual_file(\"%s\", %zu): %m", filename, max_size);
1019                         assert_se(ERRNO_IS_PRIVILEGE(r) || /* /proc/kcore is not accessible to unpriv */
1020                                   IN_SET(r,
1021                                          -ENOENT,  /* Some of the files might be absent */
1022                                          -EINVAL,  /* too small reads from /proc/self/pagemap trigger EINVAL */
1023                                          -EFBIG)); /* /proc/kcore and /proc/self/pagemap should be too large */
1024                 } else
1025                         log_info("read_virtual_file(\"%s\", %zu): %s (%zu bytes)", filename, max_size, r ? "non-truncated" : "truncated", size);
1026         }
1027 }
1028 
TEST(test_read_virtual_file)1029 TEST(test_read_virtual_file) {
1030         test_read_virtual_file_one(0);
1031         test_read_virtual_file_one(1);
1032         test_read_virtual_file_one(2);
1033         test_read_virtual_file_one(20);
1034         test_read_virtual_file_one(4096);
1035         test_read_virtual_file_one(4097);
1036         test_read_virtual_file_one(SIZE_MAX);
1037 }
1038 
1039 DEFINE_TEST_MAIN(LOG_DEBUG);
1040