]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/trackfds.h
Update copyright year.
[coloredstderr/coloredstderr.git] / src / trackfds.h
1 /*
2  * Utility functions to track file descriptors.
3  *
4  * Copyright (C) 2013-2014  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 /* Load tracked file descriptors from the environment. The environment is used
103  * to pass the information to child processes.
104  *
105  * ENV_NAME_FDS and ENV_NAME_PRIVATE_FDS have the following format: Each
106  * descriptor as string followed by a comma; there's a trailing comma.
107  * Example: "2,4,". */
108 static void init_from_environment(void) {
109 #ifdef DEBUG
110     debug("init_from_environment()\t\t[%d]\n", getpid());
111 #endif
112     char const *env;
113
114     int saved_errno = errno;
115
116     assert(!initialized);
117
118     initialized = 1;
119     tracked_fds_list_count = 0;
120
121     /* Don't color writes to stderr for this binary (and its children) if it's
122      * contained in the comma-separated list in ENV_NAME_IGNORED_BINARIES. */
123     env = getenv(ENV_NAME_IGNORED_BINARIES);
124     if (env) {
125         char path[512];
126
127         /* TODO: Don't require /proc/. */
128         ssize_t written = readlink("/proc/self/exe", path, sizeof(path) - 1);
129         if (written > 0) {
130             path[written] = 0; /* readlink() does not null-terminate! */
131             if (is_program_ignored(path, env)) {
132                 return;
133             }
134         }
135     }
136
137     /* If ENV_NAME_FORCE_WRITE is set and not empty, allow writes to a non-tty
138      * device. Use with care! Mainly used for the test suite. */
139     env = getenv(ENV_NAME_FORCE_WRITE);
140     if (env && env[0] != '\0') {
141         force_write_to_non_tty = 1;
142     }
143
144     /* Prefer user defined list of file descriptors, fall back to file
145      * descriptors passed through the environment from the parent process. */
146     env = getenv(ENV_NAME_FDS);
147     if (env) {
148         used_fds_set_by_user = 1;
149     } else {
150         env = getenv(ENV_NAME_PRIVATE_FDS);
151     }
152     if (!env) {
153         errno = saved_errno;
154         return;
155     }
156 #ifdef DEBUG
157     debug("  getenv(\"%s\"): \"%s\"\n", ENV_NAME_FDS, env);
158     debug("  getenv(\"%s\"): \"%s\"\n", ENV_NAME_PRIVATE_FDS, env);
159 #endif
160
161     /* Environment must be treated read-only. */
162     char env_copy[strlen(env) + 1];
163     strcpy(env_copy, env);
164
165     char *x;
166
167     size_t count = 0;
168     for (x = env_copy; *x; x++) {
169         if (*x == ',') {
170             count++;
171         }
172     }
173
174     size_t i = 0;
175
176     /* Parse file descriptor numbers from environment string and store them as
177      * integers in tracked_fds and tracked_fds_list. */
178     char *last;
179     for (x = env_copy, last = env_copy; *x; x++) {
180         if (*x != ',') {
181             continue;
182         }
183         /* ',' at the beginning or double ',' - ignore. */
184         if (x == last) {
185             goto next;
186         }
187
188         /* Replace ',' to null-terminate number for atoi(). */
189         *x = 0;
190
191         int fd = atoi(last);
192         if (fd < 0) {
193             goto next;
194
195         } else if (fd < TRACKFDS_STATIC_COUNT) {
196             tracked_fds[fd] = 1;
197         } else {
198             if (!tracked_fds_list) {
199                 /* Pessimistic count estimate, but allocating a few more
200                  * elements doesn't hurt. */
201                 if (!init_tracked_fds_list(count)) {
202                     /* Couldn't allocate memory, skip this entry. */
203                     goto next;
204                 }
205             }
206             tracked_fds_list[i++] = fd;
207 #ifdef DEBUG
208             debug("  large fd: %d\n", fd);
209 #endif
210         }
211
212 next:
213         last = x + 1;
214     }
215
216     tracked_fds_list_count = i;
217
218 #ifdef DEBUG
219     tracked_fds_debug();
220 #endif
221
222     errno = saved_errno;
223 }
224
225 static char *update_environment_buffer_entry(char *x, int fd) {
226     assert(fd >= 0);
227
228     int length = snprintf(x, 10 + 1, "%d", fd);
229     if (length >= 10 + 1 || length <= 0 /* shouldn't happen */) {
230         /* Integer too big to fit the buffer, skip it. */
231 #ifdef WARNING
232         warning("update_environment_buffer_entry(): truncated fd: %d [%d]\n",
233                 fd, getpid());
234 #endif
235         return x;
236     }
237
238     /* Write comma after number. */
239     x += length;
240     *x++ = ',';
241     /* Make sure the string is always null-terminated. */
242     *x = 0;
243
244     return x;
245 }
246 static void update_environment_buffer(char *x) {
247     assert(initialized);
248
249     size_t i;
250     for (i = 0; i < TRACKFDS_STATIC_COUNT; i++) {
251         if (tracked_fds[i]) {
252             x = update_environment_buffer_entry(x, (int)i);
253         }
254     }
255     for (i = 0; i < tracked_fds_list_count; i++) {
256         x = update_environment_buffer_entry(x, tracked_fds_list[i]);
257     }
258 }
259 inline static size_t update_environment_buffer_size(void) {
260     assert(initialized);
261
262     /* Use the maximum count (TRACKFDS_STATIC_COUNT) of used descriptors
263      * because it's simple and small enough not to be a problem.
264      *
265      * An integer (32-bit) has at most 10 digits, + 1 for the comma after each
266      * number. Bigger file descriptors (which shouldn't occur in reality) are
267      * skipped. */
268     return (TRACKFDS_STATIC_COUNT + tracked_fds_list_count)
269                * (10 + 1) + 1 /* to fit '\0' */;
270 }
271 static void update_environment(void) {
272 #ifdef DEBUG
273     debug("update_environment()\t\t[%d]\n", getpid());
274 #endif
275
276     /* If we haven't parsed the environment we also haven't modified it - so
277      * nothing to do. */
278     if (!initialized) {
279         return;
280     }
281
282     int saved_errno = errno;
283
284     char env[update_environment_buffer_size()];
285     env[0] = 0;
286
287     update_environment_buffer(env);
288
289 #if 0
290     debug("    setenv(\"%s\", \"%s\", 1)\n", ENV_NAME_PRIVATE_FDS, env);
291 #endif
292     setenv(ENV_NAME_PRIVATE_FDS, env, 1 /* overwrite */);
293
294     /* Child processes must use ENV_NAME_PRIVATE_FDS to get the updated list
295      * of tracked file descriptors, not the static list provided by the user
296      * in ENV_NAME_FDS.
297      *
298      * But only remove it if the static list in ENV_NAME_FDS was loaded by
299      * init_from_environment() and merged into ENV_NAME_PRIVATE_FDS. */
300     if (used_fds_set_by_user) {
301         unsetenv(ENV_NAME_FDS);
302     }
303
304     errno = saved_errno;
305 }
306
307
308
309 static void tracked_fds_add(int fd) {
310     assert(fd >= 0);
311
312     if (fd < TRACKFDS_STATIC_COUNT) {
313         tracked_fds[fd] = 1;
314 #if 0
315         debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
316         tracked_fds_debug();
317 #endif
318         return;
319     }
320
321     if (tracked_fds_list_count >= tracked_fds_list_space) {
322         int saved_errno = errno;
323
324         size_t new_space = tracked_fds_list_space + TRACKFDS_REALLOC_STEP;
325         int *tmp = realloc(tracked_fds_list,
326                            sizeof(*tracked_fds_list) * new_space);
327         if (!tmp) {
328             /* We can do nothing, just ignore the error. We made sure not to
329              * destroy our state, so the new descriptor is ignored without any
330              * other consequences. */
331 #ifdef WARNING
332             warning("realloc(tracked_fds_list, %zu) failed! [%d]\n",
333                     sizeof(*tracked_fds_list) * new_space, getpid());
334 #endif
335             errno = saved_errno;
336             return;
337         }
338         errno = saved_errno;
339
340         tracked_fds_list = tmp;
341         tracked_fds_list_space = new_space;
342     }
343
344     tracked_fds_list[tracked_fds_list_count++] = fd;
345
346 #ifdef DEBUG
347     debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
348     tracked_fds_debug();
349 #endif
350 }
351 static int tracked_fds_remove(int fd) {
352     assert(fd >= 0);
353
354     if (fd < TRACKFDS_STATIC_COUNT) {
355         int old_value = tracked_fds[fd];
356         tracked_fds[fd] = 0;
357
358 #if 0
359         debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
360         tracked_fds_debug();
361 #endif
362         return old_value; /* Found vs. not found. */
363     }
364
365     size_t i;
366     for (i = 0; i < tracked_fds_list_count; i++) {
367         if (fd != tracked_fds_list[i]) {
368             continue;
369         }
370
371         memmove(tracked_fds_list + i, tracked_fds_list + i + 1,
372                 sizeof(*tracked_fds_list) * (tracked_fds_list_count - i - 1));
373         tracked_fds_list_count--;
374
375 #ifdef DEBUG
376         debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
377         tracked_fds_debug();
378 #endif
379
380         /* Found. */
381         return 1;
382     }
383
384     /* Not found. */
385     return 0;
386 }
387
388 static int tracked_fds_find_slow(int fd) noinline;
389 /*
390  * tracked_fds_find() is called for each hook call and should be as fast as
391  * possible. As most file descriptors are < TRACKFDS_STATIC_COUNT, force the
392  * compiler to inline that part which is almost exclusively used.
393  *
394  * Inlining tracked_fds_add()/tracked_fds_remove() isn't worth the effort as
395  * they are not called often enough.
396  */
397 inline static int tracked_fds_find(int fd) always_inline;
398 inline static int tracked_fds_find(int fd) {
399     /* Invalid file descriptor. No assert() as we're called from the hooked
400      * macro. */
401     if (unlikely(fd < 0)) {
402         return 0;
403     }
404
405     if (likely(fd < TRACKFDS_STATIC_COUNT)) {
406         return tracked_fds[fd];
407     }
408
409     return tracked_fds_find_slow(fd);
410 }
411 static int tracked_fds_find_slow(int fd) {
412     assert(initialized);
413     assert(fd >= 0);
414
415     if (tracked_fds_list_count == 0) {
416         return 0;
417     }
418
419     size_t i;
420     for (i = 0; i < tracked_fds_list_count; i++) {
421         if (fd == tracked_fds_list[i]) {
422             return 1;
423         }
424     }
425     return 0;
426 }
427
428 #endif