2 * Utility functions to track file descriptors.
4 * Copyright (C) 2013 Simon Ruderich
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.
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.
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/>.
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];
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;
36 static void tracked_fds_debug(void) {
39 for (i = 0; i < TRACKFDS_STATIC_COUNT; i++) {
41 debug(" tracked_fds[%d]: %d\n", i, tracked_fds[i]);
44 debug(" tracked_fds_list: %d/%d\t[%d]\n", tracked_fds_list_count,
45 tracked_fds_list_space,
47 for (i = 0; i < tracked_fds_list_count; i++) {
48 debug(" tracked_fds_list[%d]: %d\n", i, tracked_fds_list[i]);
53 /* Check if filename occurs in the comma-separated list ignore. */
54 static int is_program_ignored(char const *filename, char const *ignore) {
56 size_t filename_length = strlen(filename);
59 debug(" is_program_ignored(\"%s\", \"%s\")\n", filename, ignore);
62 for (; *ignore; ignore += length) {
63 while (*ignore == ',') {
67 length = strcspn(ignore, ",");
72 if (length != filename_length) {
75 if (!strncmp(filename, ignore, length)) {
83 static int init_tracked_fds_list(size_t count) {
86 /* Reduce reallocs. */
87 count += TRACKFDS_REALLOC_STEP;
89 tracked_fds_list = malloc(count * sizeof(*tracked_fds_list));
90 if (!tracked_fds_list) {
92 warning("malloc(tracked_fds_list, %d) failed [%d]\n",
93 count * sizeof(*tracked_fds_list), getpid());
98 tracked_fds_list_space = count;
102 /* Load tracked file descriptors from the environment. The environment is used
103 * to pass the information to child processes.
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) {
110 debug("init_from_environment()\t\t[%d]\n", getpid());
114 int saved_errno = errno;
116 assert(!initialized);
119 tracked_fds_list_count = 0;
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);
127 /* TODO: Don't require /proc/. */
128 ssize_t written = readlink("/proc/self/exe", path, sizeof(path) - 1);
130 path[written] = 0; /* readlink() does not null-terminate! */
131 if (is_program_ignored(path, env)) {
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;
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);
148 used_fds_set_by_user = 1;
150 env = getenv(ENV_NAME_PRIVATE_FDS);
157 debug(" getenv(\"%s\"): \"%s\"\n", ENV_NAME_FDS, env);
158 debug(" getenv(\"%s\"): \"%s\"\n", ENV_NAME_PRIVATE_FDS, env);
161 /* Environment must be treated read-only. */
162 char env_copy[strlen(env) + 1];
163 strcpy(env_copy, env);
168 for (x = env_copy; *x; x++) {
176 /* Parse file descriptor numbers from environment string and store them as
177 * integers in tracked_fds and tracked_fds_list. */
179 for (x = env_copy, last = env_copy; *x; x++) {
183 /* ',' at the beginning or double ',' - ignore. */
188 /* Replace ',' to null-terminate number for atoi(). */
195 } else if (fd < TRACKFDS_STATIC_COUNT) {
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. */
206 tracked_fds_list[i++] = fd;
208 debug(" large fd: %d\n", fd);
216 tracked_fds_list_count = i;
225 static char *update_environment_buffer_entry(char *x, int fd) {
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. */
232 warning("update_environment_buffer_entry(): truncated fd: %d [%d]\n",
238 /* Write comma after number. */
241 /* Make sure the string is always null-terminated. */
246 static void update_environment_buffer(char *x) {
250 for (i = 0; i < TRACKFDS_STATIC_COUNT; i++) {
251 if (tracked_fds[i]) {
252 x = update_environment_buffer_entry(x, (int)i);
255 for (i = 0; i < tracked_fds_list_count; i++) {
256 x = update_environment_buffer_entry(x, tracked_fds_list[i]);
259 inline static size_t update_environment_buffer_size(void) {
262 /* Use the maximum count (TRACKFDS_STATIC_COUNT) of used descriptors
263 * because it's simple and small enough not to be a problem.
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
268 return (TRACKFDS_STATIC_COUNT + tracked_fds_list_count)
269 * (10 + 1) + 1 /* to fit '\0' */;
271 static void update_environment(void) {
273 debug("update_environment()\t\t[%d]\n", getpid());
276 /* If we haven't parsed the environment we also haven't modified it - so
282 int saved_errno = errno;
284 char env[update_environment_buffer_size()];
287 update_environment_buffer(env);
290 debug(" setenv(\"%s\", \"%s\", 1)\n", ENV_NAME_PRIVATE_FDS, env);
292 setenv(ENV_NAME_PRIVATE_FDS, env, 1 /* overwrite */);
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
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);
309 static void tracked_fds_add(int fd) {
312 if (fd < TRACKFDS_STATIC_COUNT) {
315 debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
321 if (tracked_fds_list_count >= tracked_fds_list_space) {
322 int saved_errno = errno;
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);
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. */
332 warning("realloc(tracked_fds_list, %zu) failed! [%d]\n",
333 sizeof(*tracked_fds_list) * new_space, getpid());
340 tracked_fds_list = tmp;
341 tracked_fds_list_space = new_space;
344 tracked_fds_list[tracked_fds_list_count++] = fd;
347 debug("tracked_fds_add(): %-3d\t\t[%d]\n", fd, getpid());
351 static int tracked_fds_remove(int fd) {
354 if (fd < TRACKFDS_STATIC_COUNT) {
355 int old_value = tracked_fds[fd];
359 debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
362 return old_value; /* Found vs. not found. */
366 for (i = 0; i < tracked_fds_list_count; i++) {
367 if (fd != tracked_fds_list[i]) {
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--;
376 debug("tracked_fds_remove(): %-3d\t[%d]\n", fd, getpid());
388 static int tracked_fds_find_slow(int fd) noinline;
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.
394 * Inlining tracked_fds_add()/tracked_fds_remove() isn't worth the effort as
395 * they are not called often enough.
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
401 if (unlikely(fd < 0)) {
405 if (fd < TRACKFDS_STATIC_COUNT) {
406 return tracked_fds[fd];
409 return tracked_fds_find_slow(fd);
411 static int tracked_fds_find_slow(int fd) {
415 if (tracked_fds_list_count == 0) {
420 for (i = 0; i < tracked_fds_list_count; i++) {
421 if (fd == tracked_fds_list[i]) {