]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/trackfds.h
Prevent crash in execve() if env is NULL
[coloredstderr/coloredstderr.git] / src / trackfds.h
1 /*
2  * Utility functions to track file descriptors.
3  *
4  * Copyright (C) 2013-2018  Simon Ruderich
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 #ifndef TRACKFDS_H
21 #define TRACKFDS_H 1
22
23 /* Array of tracked file descriptors. Used for fast lookups for the normally
24  * used file descriptors (0 <= fd < TRACKFDS_STATIC_COUNT). */
25 static int tracked_fds[TRACKFDS_STATIC_COUNT];
26
27 /* List of tracked file descriptors >= TRACKFDS_STATIC_COUNT. */
28 static int *tracked_fds_list;
29 /* Current number of items in the list. */
30 static size_t tracked_fds_list_count;
31 /* Allocated items, used to reduce realloc()s. */
32 static size_t tracked_fds_list_space;
33
34
35 #ifdef DEBUG
36 static void tracked_fds_debug(void) {
37     size_t i;
38
39     for (i = 0; i < TRACKFDS_STATIC_COUNT; i++) {
40         if (tracked_fds[i]) {
41             debug("    tracked_fds[%d]: %d\n", i, tracked_fds[i]);
42         }
43     }
44     debug("    tracked_fds_list: %d/%d\t[%d]\n", tracked_fds_list_count,
45                                                  tracked_fds_list_space,
46                                                  getpid());
47     for (i = 0; i < tracked_fds_list_count; i++) {
48         debug("    tracked_fds_list[%d]: %d\n", i, tracked_fds_list[i]);
49     }
50 }
51 #endif
52
53 /* Check if filename occurs in the comma-separated list ignore. */
54 static int is_program_ignored(char const *filename, char const *ignore) {
55     size_t length;
56     size_t filename_length = strlen(filename);
57
58 #ifdef DEBUG
59     debug("  is_program_ignored(\"%s\", \"%s\")\n", filename, ignore);
60 #endif
61
62     for (; *ignore; ignore += length) {
63         while (*ignore == ',') {
64             ignore++;
65         }
66
67         length = strcspn(ignore, ",");
68         if (length == 0) {
69             break;
70         }
71
72         if (length != filename_length) {
73             continue;
74         }
75         if (!strncmp(filename, ignore, length)) {
76             return 1;
77         }
78     }
79
80     return 0;
81 }
82
83 static int init_tracked_fds_list(size_t count) {
84     assert(count > 0);
85
86     /* Reduce reallocs. */
87     count += TRACKFDS_REALLOC_STEP;
88
89     tracked_fds_list = malloc(count * sizeof(*tracked_fds_list));
90     if (!tracked_fds_list) {
91 #ifdef WARNING
92         warning("malloc(tracked_fds_list, %d) failed [%d]\n",
93                 count * sizeof(*tracked_fds_list), getpid());
94 #endif
95         return 0;
96     }
97
98     tracked_fds_list_space = count;
99     return 1;
100 }
101
102 /*
103  * Load tracked file descriptors from the environment. The environment is used
104  * to pass the information to child processes.
105  *
106  * ENV_NAME_FDS and ENV_NAME_PRIVATE_FDS have the following format: Each
107  * descriptor as string followed by a comma; there's a trailing comma.
108  * Example: "2,4,".
109  */
110 static void init_from_environment(void) {
111 #ifdef DEBUG
112     debug("init_from_environment()\t\t[%d]\n", getpid());
113 #endif
114     char const *env;
115
116     int saved_errno = errno;
117
118     assert(!initialized);
119
120     initialized = 1;
121     tracked_fds_list_count = 0;
122
123     /* Don't color writes to stderr for this binary (and its children) if it's
124      * contained in the comma-separated list in ENV_NAME_IGNORED_BINARIES. */
125     env = getenv(ENV_NAME_IGNORED_BINARIES);
126     if (env) {
127         char path[512];
128
129         /* TODO: Don't require /proc/. */
130         ssize_t written = readlink("/proc/self/exe", path, sizeof(path) - 1);
131         if (written > 0) {
132             path[written] = 0; /* readlink() does not null-terminate! */
133             if (is_program_ignored(path, env)) {
134                 return;
135             }
136         }
137     }
138
139     /* If ENV_NAME_FORCE_WRITE is set and not empty, allow writes to a non-tty
140      * device. Use with care! Mainly used for the test suite. */
141     env = getenv(ENV_NAME_FORCE_WRITE);
142     if (env && env[0] != '\0') {
143         force_write_to_non_tty = 1;
144     }
145
146     /* Prefer user defined list of file descriptors, fall back to file
147      * descriptors passed through the environment from the parent process. */
148     env = getenv(ENV_NAME_FDS);
149     if (env) {
150         used_fds_set_by_user = 1;
151     } else {
152         env = getenv(ENV_NAME_PRIVATE_FDS);
153     }
154     if (!env) {
155         errno = saved_errno;
156         return;
157     }
158 #ifdef DEBUG
159     debug("  getenv(\"%s\"): \"%s\"\n", ENV_NAME_FDS, env);
160     debug("  getenv(\"%s\"): \"%s\"\n", ENV_NAME_PRIVATE_FDS, env);
161 #endif
162
163     /* Environment must be treated read-only. */
164     char env_copy[strlen(env) + 1];
165     strcpy(env_copy, env);
166
167     char *x;
168
169     size_t count = 0;
170     for (x = env_copy; *x; x++) {
171         if (*x == ',') {
172             count++;
173         }
174     }
175
176     size_t i = 0;
177
178     /* Parse file descriptor numbers from environment string and store them as
179      * integers in tracked_fds and tracked_fds_list. */
180     char *last;
181     for (x = env_copy, last = env_copy; *x; x++) {
182         if (*x != ',') {
183             continue;
184         }
185         /* ',' at the beginning or double ',' - ignore. */
186         if (x == last) {
187             goto next;
188         }
189
190         /* Replace ',' to null-terminate number for atoi(). */
191         *x = 0;
192
193         int fd = atoi(last);
194         if (fd < 0) {
195             goto next;
196
197         } else if (fd < TRACKFDS_STATIC_COUNT) {
198             tracked_fds[fd] = 1;
199         } else {
200             if (!tracked_fds_list) {
201                 /* Pessimistic count estimate, but allocating a few more
202                  * elements doesn't hurt. */
203                 if (!init_tracked_fds_list(count)) {
204                     /* Couldn't allocate memory, skip this entry. */
205                     goto next;
206                 }
207             }
208             tracked_fds_list[i++] = fd;
209 #ifdef DEBUG
210             debug("  large fd: %d\n", fd);
211 #endif
212         }
213
214 next:
215         last = x + 1;
216     }
217
218     tracked_fds_list_count = i;
219
220 #ifdef DEBUG
221     tracked_fds_debug();
222 #endif
223
224     errno = saved_errno;
225 }
226
227 static char *update_environment_buffer_entry(char *x, int fd) {
228     assert(fd >= 0);
229
230     int length = snprintf(x, 10 + 1, "%d", fd);
231     if (length >= 10 + 1 || length <= 0 /* shouldn't happen */) {
232         /* Integer too big to fit the buffer, skip it. */
233 #ifdef WARNING
234         warning("update_environment_buffer_entry(): truncated fd: %d [%d]\n",
235                 fd, getpid());
236 #endif
237         return x;
238     }
239
240     /* Write comma after number. */
241     x += length;
242     *x++ = ',';
243     /* Make sure the string is always null-terminated. */
244     *x = 0;
245
246     return x;
247 }
248 static void update_environment_buffer(char *x) {
249     assert(initialized);
250
251     size_t i;
252     for (i = 0; i < TRACKFDS_STATIC_COUNT; i++) {
253         if (tracked_fds[i]) {
254             x = update_environment_buffer_entry(x, (int)i);
255         }
256     }
257     for (i = 0; i < tracked_fds_list_count; i++) {
258         x = update_environment_buffer_entry(x, tracked_fds_list[i]);
259     }
260 }
261 inline static size_t update_environment_buffer_size(void) {
262     assert(initialized);
263
264     /* Use the maximum count (TRACKFDS_STATIC_COUNT) of used descriptors
265      * because it's simple and small enough not to be a problem.
266      *
267      * An integer (32-bit) has at most 10 digits, + 1 for the comma after each
268      * number. Bigger file descriptors (which shouldn't occur in reality) are
269      * skipped. */
270     return (TRACKFDS_STATIC_COUNT + tracked_fds_list_count)
271                * (10 + 1) + 1 /* to fit '\0' */;
272 }
273 static void update_environment(void) {
274 #ifdef DEBUG
275     debug("update_environment()\t\t[%d]\n", getpid());
276 #endif
277
278     /* If we haven't parsed the environment we also haven't modified it - so
279      * nothing to do. */
280     if (!initialized) {
281         return;
282     }
283
284     int saved_errno = errno;
285
286     char env[update_environment_buffer_size()];
287     env[0] = 0;
288
289     update_environment_buffer(env);
290
291 #if 0
292     debug("    setenv(\"%s\", \"%s\", 1)\n", ENV_NAME_PRIVATE_FDS, env);
293 #endif
294     setenv(ENV_NAME_PRIVATE_FDS, env, 1 /* overwrite */);
295
296     /* Child processes must use ENV_NAME_PRIVATE_FDS to get the updated list
297      * of tracked file descriptors, not the static list provided by the user
298      * in ENV_NAME_FDS.
299      *
300      * But only remove it if the static list in ENV_NAME_FDS was loaded by
301      * init_from_environment() and merged into ENV_NAME_PRIVATE_FDS. */
302     if (used_fds_set_by_user) {
303         unsetenv(ENV_NAME_FDS);
304     }
305
306     errno = saved_errno;
307 }
308
309
310
311 static void tracked_fds_add(int fd) {
312     assert(fd >= 0);
313
314     if (fd < TRACKFDS_STATIC_COUNT) {
315         tracked_fds[fd] = 1;
316 #if 0
317         debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
318         tracked_fds_debug();
319 #endif
320         return;
321     }
322
323     if (tracked_fds_list_count >= tracked_fds_list_space) {
324         int saved_errno = errno;
325
326         size_t new_space = tracked_fds_list_space + TRACKFDS_REALLOC_STEP;
327         int *tmp = realloc(tracked_fds_list,
328                            sizeof(*tracked_fds_list) * new_space);
329         if (!tmp) {
330             /* We can do nothing, just ignore the error. We made sure not to
331              * destroy our state, so the new descriptor is ignored without any
332              * other consequences. */
333 #ifdef WARNING
334             warning("realloc(tracked_fds_list, %zu) failed! [%d]\n",
335                     sizeof(*tracked_fds_list) * new_space, getpid());
336 #endif
337             errno = saved_errno;
338             return;
339         }
340         errno = saved_errno;
341
342         tracked_fds_list = tmp;
343         tracked_fds_list_space = new_space;
344     }
345
346     tracked_fds_list[tracked_fds_list_count++] = fd;
347
348 #ifdef DEBUG
349     debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
350     tracked_fds_debug();
351 #endif
352 }
353 static int tracked_fds_remove(int fd) {
354     assert(fd >= 0);
355
356     if (fd < TRACKFDS_STATIC_COUNT) {
357         int old_value = tracked_fds[fd];
358         tracked_fds[fd] = 0;
359
360 #if 0
361         debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
362         tracked_fds_debug();
363 #endif
364         return old_value; /* Found vs. not found. */
365     }
366
367     size_t i;
368     for (i = 0; i < tracked_fds_list_count; i++) {
369         if (fd != tracked_fds_list[i]) {
370             continue;
371         }
372
373         memmove(tracked_fds_list + i, tracked_fds_list + i + 1,
374                 sizeof(*tracked_fds_list) * (tracked_fds_list_count - i - 1));
375         tracked_fds_list_count--;
376
377 #ifdef DEBUG
378         debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
379         tracked_fds_debug();
380 #endif
381
382         /* Found. */
383         return 1;
384     }
385
386     /* Not found. */
387     return 0;
388 }
389
390 static int tracked_fds_find_slow(int fd) noinline;
391 /*
392  * tracked_fds_find() is called for each hook call and should be as fast as
393  * possible. As most file descriptors are < TRACKFDS_STATIC_COUNT, force the
394  * compiler to inline that part which is almost exclusively used.
395  *
396  * Inlining tracked_fds_add()/tracked_fds_remove() isn't worth the effort as
397  * they are not called often enough.
398  */
399 inline static int tracked_fds_find(int fd) always_inline;
400 inline static int tracked_fds_find(int fd) {
401     /* Invalid file descriptor. No assert() as we're called from the hooked
402      * macro. */
403     if (unlikely(fd < 0)) {
404         return 0;
405     }
406
407     if (likely(fd < TRACKFDS_STATIC_COUNT)) {
408         return tracked_fds[fd];
409     }
410
411     return tracked_fds_find_slow(fd);
412 }
413 static int tracked_fds_find_slow(int fd) {
414     assert(initialized);
415     assert(fd >= 0);
416
417     if (tracked_fds_list_count == 0) {
418         return 0;
419     }
420
421     size_t i;
422     for (i = 0; i < tracked_fds_list_count; i++) {
423         if (fd == tracked_fds_list[i]) {
424             return 1;
425         }
426     }
427     return 0;
428 }
429
430 #endif