1 /*
2 * Copyright (C) 2006-2007, 2010-2020 Free Software Foundation, Inc.
3 * Written by Simon Josefsson
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>. */
17
18 #include <config.h>
19
20 #include "read-file.h"
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <sys/stat.h>
25
26 #include "macros.h"
27
28 #define FILE1 "/etc/resolv.conf"
29 #define FILE2 "/dev/null"
30
31 static int
test_read_file(int flags)32 test_read_file (int flags)
33 {
34 struct stat statbuf;
35 int err = 0;
36
37 /* We can perform the test only if the file exists and is readable.
38 Test whether it exists, then assume it is world-readable. */
39 if (stat (FILE1, &statbuf) >= 0)
40 {
41 size_t len;
42 char *out = read_file (FILE1, flags, &len);
43
44 if (!out)
45 {
46 perror ("Could not read file");
47 err = 1;
48 }
49 else
50 {
51 if (out[len] != '\0')
52 {
53 perror ("BAD: out[len] not zero");
54 err = 1;
55 }
56
57 if (S_ISREG (statbuf.st_mode))
58 {
59 /* FILE1 is a regular file or a symlink to a regular file. */
60 if (len != statbuf.st_size)
61 {
62 fprintf (stderr, "Read %lu from %s...\n",
63 (unsigned long) len, FILE1);
64 err = 1;
65 }
66 }
67 else
68 {
69 /* Assume FILE1 is not empty. */
70 if (len == 0)
71 {
72 fprintf (stderr, "Read nothing from %s\n", FILE1);
73 err = 1;
74 }
75 }
76 free (out);
77 }
78 }
79
80 /* We can perform the test only if the file exists and is readable.
81 Test whether it exists, then assume it is world-readable. */
82 if (stat (FILE2, &statbuf) >= 0)
83 {
84 size_t len;
85 char *out = read_file (FILE2, flags, &len);
86
87 if (!out)
88 {
89 perror ("Could not read file");
90 err = 1;
91 }
92 else
93 {
94 if (out[len] != '\0')
95 {
96 perror ("BAD: out[len] not zero");
97 err = 1;
98 }
99
100 /* /dev/null should always be empty. Ignore statbuf.st_size, since it
101 is not a regular file. */
102 if (len != 0)
103 {
104 fprintf (stderr, "Read %lu from %s...\n",
105 (unsigned long) len, FILE2);
106 err = 1;
107 }
108 free (out);
109 }
110 }
111
112 return err;
113 }
114
115 int
main(void)116 main (void)
117 {
118 ASSERT (!test_read_file (0));
119 ASSERT (!test_read_file (RF_BINARY));
120 ASSERT (!test_read_file (RF_SENSITIVE));
121 ASSERT (!test_read_file (RF_BINARY | RF_SENSITIVE));
122
123 return 0;
124 }
125