]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/coloredstderr.c
check_handle_fd(): Reduce calls to isatty().
[coloredstderr/coloredstderr.git] / src / coloredstderr.c
1 /*
2  * Hook output functions (like printf(3)) with LD_PRELOAD to color stderr (or
3  * other file descriptors).
4  *
5  * Copyright (C) 2013  Simon Ruderich
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "config.h"
22
23 /* Must be loaded before the following headers. */
24 #include "ldpreload.h"
25
26 #include <errno.h>
27 #include <fcntl.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <unistd.h>
32
33 /* Conflicting declaration in glibc. */
34 #undef fwrite_unlocked
35
36
37 /* Used by various functions, including debug(). */
38 static ssize_t (*real_write)(int, const void *, size_t);
39 static int (*real_close)(int);
40 static size_t (*real_fwrite)(const void *, size_t, size_t, FILE *);
41
42 /* Did we already (try to) parse the environment and setup the necessary
43  * variables? */
44 static int initialized;
45 /* Force hooked writes even when not writing to a tty. Used for tests. */
46 static int force_write_to_non_tty;
47
48
49 #include "constants.h"
50 #ifdef DEBUG
51 # include "debug.h"
52 #endif
53
54 #include "hookmacros.h"
55 #include "trackfds.h"
56
57
58
59 /* Should the "action" handler be invoked for this file descriptor? */
60 static int check_handle_fd(int fd) {
61     /* Load state from environment. Only necessary once per process. */
62     if (!initialized) {
63         init_from_environment();
64     }
65     if (tracked_fds_count == 0) {
66         return 0;
67     }
68
69     /* Never touch anything not going to a terminal - unless we are explicitly
70      * asked to do so. */
71     if (!force_write_to_non_tty && !isatty(fd)) {
72         return 0;
73     }
74
75     return tracked_fds_find(fd);
76 }
77
78 static void dup_fd(int oldfd, int newfd) {
79 #ifdef DEBUG
80     debug("%3d -> %3d\t\t\t[%d]\n", oldfd, newfd, getpid());
81 #endif
82
83     if (!initialized) {
84         init_from_environment();
85     }
86     if (tracked_fds_count == 0) {
87         return;
88     }
89
90     /* We are already tracking this file descriptor, add newfd to the list as
91      * it will reference the same descriptor. */
92     if (tracked_fds_find(oldfd)) {
93         if (!tracked_fds_find(newfd)) {
94             tracked_fds_add(newfd);
95         }
96     /* We are not tracking this file descriptor, remove newfd from the list
97      * (if present). */
98     } else {
99         tracked_fds_remove(newfd);
100     }
101 }
102
103 static void close_fd(int fd) {
104 #ifdef DEBUG
105     debug("%3d ->   .\t\t\t[%d]\n", fd, getpid());
106 #endif
107
108     if (!initialized) {
109         init_from_environment();
110     }
111     if (tracked_fds_count == 0) {
112         return;
113     }
114
115     tracked_fds_remove(fd);
116 }
117
118
119 /* "Action" handlers called when a file descriptor is matched. */
120
121 static char *pre_string;
122 static size_t pre_string_size;
123 static char *post_string;
124 static size_t post_string_size;
125
126 /* Load alternative pre/post strings from the environment if available, fall
127  * back to default values. */
128 inline static void init_pre_post_string() {
129     pre_string = getenv(ENV_NAME_PRE_STRING);
130     if (!pre_string) {
131         pre_string = DEFAULT_PRE_STRING;
132     }
133     pre_string_size = strlen(pre_string);
134
135     post_string = getenv(ENV_NAME_POST_STRING);
136     if (!post_string) {
137         post_string = DEFAULT_POST_STRING;
138     }
139     post_string_size = strlen(post_string);
140 }
141
142 static void handle_fd_pre(int fd, int action) {
143     (void)action;
144
145     if (!pre_string || !post_string) {
146         init_pre_post_string();
147     }
148
149     DLSYM_FUNCTION(real_write, "write");
150     real_write(fd, pre_string, pre_string_size);
151 }
152 static void handle_fd_post(int fd, int action) {
153     (void)action;
154
155     /* write() already loaded above in handle_fd_pre(). */
156     real_write(fd, post_string, post_string_size);
157 }
158
159 static void handle_file_pre(FILE *stream, int action) {
160     (void)action;
161
162     if (!pre_string || !post_string) {
163         init_pre_post_string();
164     }
165
166     DLSYM_FUNCTION(real_fwrite, "fwrite");
167     real_fwrite(pre_string, pre_string_size, 1, stream);
168 }
169 static void handle_file_post(FILE *stream, int action) {
170     (void)action;
171
172     /* fwrite() already loaded above in handle_file_pre(). */
173     real_fwrite(post_string, post_string_size, 1, stream);
174 }
175
176
177
178 /* Hook all important output functions to manipulate their output. */
179
180 HOOK_FD3(ssize_t, write, fd,
181          int, fd, const void *, buf, size_t, count)
182 HOOK_FILE4(size_t, fwrite, stream,
183            const void *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
184
185 /* puts(3) */
186 HOOK_FILE2(int, fputs, stream,
187            const char *, s, FILE *, stream)
188 HOOK_FILE2(int, fputc, stream,
189            int, c, FILE *, stream)
190 HOOK_FILE2(int, putc, stream,
191            int, c, FILE *, stream)
192 HOOK_FILE1(int, putchar, stdout,
193            int, c)
194 HOOK_FILE1(int, puts, stdout,
195            const char *, s)
196
197 /* printf(3), excluding all s*() and vs*() functions (no output) */
198 HOOK_VAR_FILE1(int, printf, stdout, vprintf,
199                const char *, format)
200 HOOK_VAR_FILE2(int, fprintf, stream, vfprintf,
201                FILE *, stream, const char *, format)
202 HOOK_FILE2(int, vprintf, stdout,
203            const char *, format, va_list, ap)
204 HOOK_FILE3(int, vfprintf, stream,
205            FILE *, stream, const char *, format, va_list, ap)
206 /* Hardening functions (-D_FORTIFY_SOURCE=2), only functions from above */
207 HOOK_VAR_FILE2(int, __printf_chk, stdout, __vprintf_chk,
208                int, flag, const char *, format)
209 HOOK_VAR_FILE3(int, __fprintf_chk, fp, __vfprintf_chk,
210                FILE *, fp, int, flag, const char *, format)
211 HOOK_FILE3(int, __vprintf_chk, stdout,
212            int, flag, const char *, format, va_list, ap)
213 HOOK_FILE4(int, __vfprintf_chk, stream,
214            FILE *, stream, int, flag, const char *, format, va_list, ap)
215
216 /* unlocked_stdio(3), only functions from above are hooked */
217 HOOK_FILE4(size_t, fwrite_unlocked, stream,
218            const void *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
219 HOOK_FILE2(int, fputs_unlocked, stream,
220            const char *, s, FILE *, stream)
221 HOOK_FILE2(int, fputc_unlocked, stream,
222            int, c, FILE *, stream)
223 HOOK_FILE2(int, putc_unlocked, stream,
224            int, c, FILE *, stream)
225 HOOK_FILE1(int, putchar_unlocked, stdout,
226            int, c)
227 HOOK_FILE1(int, puts_unlocked, stdout,
228            const char *, s)
229
230 /* perror(3) */
231 HOOK_VOID1(void, perror, STDERR_FILENO,
232            const char *, s)
233
234
235 /* Hook functions which duplicate file descriptors to track them. */
236
237 static int (*real_dup)(int);
238 static int (*real_dup2)(int, int);
239 static int (*real_dup3)(int, int, int);
240 int dup(int oldfd) {
241     int newfd;
242
243     DLSYM_FUNCTION(real_dup, "dup");
244
245     newfd = real_dup(oldfd);
246     if (newfd != -1) {
247         int saved_errno = errno;
248         dup_fd(oldfd, newfd);
249         errno = saved_errno;
250     }
251
252     return newfd;
253 }
254 int dup2(int oldfd, int newfd) {
255     DLSYM_FUNCTION(real_dup2, "dup2");
256
257     newfd = real_dup2(oldfd, newfd);
258     if (newfd != -1) {
259         int saved_errno = errno;
260         dup_fd(oldfd, newfd);
261         errno = saved_errno;
262     }
263
264     return newfd;
265 }
266 int dup3(int oldfd, int newfd, int flags) {
267     DLSYM_FUNCTION(real_dup3, "dup3");
268
269     newfd = real_dup3(oldfd, newfd, flags);
270     if (newfd != -1) {
271         int saved_errno = errno;
272         dup_fd(oldfd, newfd);
273         errno = saved_errno;
274     }
275
276     return newfd;
277 }
278
279 static int (*real_fcntl)(int, int, ...);
280 int fcntl(int fd, int cmd, ...) {
281     int result;
282     va_list ap;
283
284     DLSYM_FUNCTION(real_fcntl, "fcntl");
285
286     /* fcntl() takes different types of arguments depending on the cmd type
287      * (int, void and pointers are used at the moment). Handling these
288      * arguments for different systems and with possible changes in the future
289      * is error prone.
290      *
291      * Therefore always retrieve a void-pointer from our arguments (even if it
292      * wasn't there) and pass it to real_fcntl(). This shouldn't cause any
293      * problems because a void-pointer is most-likely bigger than an int
294      * (something which is not true in reverse) and shouldn't cause
295      * truncation. For register based calling conventions an invalid register
296      * content is passed, but ignored by real_fcntl(). Not perfect, but should
297      * work fine.
298      */
299     va_start(ap, cmd);
300     result = real_fcntl(fd, cmd, va_arg(ap, void *));
301     va_end(ap);
302
303     /* We only care about duping fds. */
304     if (cmd == F_DUPFD && result != -1) {
305         int saved_errno = errno;
306         dup_fd(fd, result);
307         errno = saved_errno;
308     }
309
310     return result;
311 }
312
313 static int (*real_close)(int);
314 int close(int fd) {
315     DLSYM_FUNCTION(real_close, "close");
316
317     close_fd(fd);
318     return real_close(fd);
319 }
320 static int (*real_fclose)(FILE *);
321 int fclose(FILE *fp) {
322     DLSYM_FUNCTION(real_fclose, "fclose");
323
324     close_fd(fileno(fp));
325     return real_fclose(fp);
326 }
327
328
329 /* Hook functions which are necessary for correct tracking. */
330
331 #if defined(HAVE_VFORK) && defined(HAVE_FORK)
332 pid_t vfork(void) {
333     /* vfork() is similar to fork() but the address space is shared between
334      * father and child. It's designed for fork()/exec() usage because it's
335      * faster than fork(). However according to the POSIX standard the "child"
336      * isn't allowed to perform any memory-modifications before the exec()
337      * (except the pid_t result variable of vfork()).
338      *
339      * As some programs don't adhere to the standard (e.g. the "child" closes
340      * or dups a descriptor before the exec()) and this breaks our tracking of
341      * file descriptors (e.g. it gets closed in the parent as well), we just
342      * fork() instead. This is in compliance with the POSIX standard and as
343      * most systems use copy-on-write anyway not a performance issue. */
344     return fork();
345 }
346 #endif
347
348
349 /* Hook execve() and the other exec*() functions. Some shells use exec*() with
350  * a custom environment which doesn't necessarily contain our updates to
351  * ENV_NAME_FDS. It's also faster to update the environment only when
352  * necessary, right before the exec() to pass it to the new process. */
353
354 static int (*real_execve)(const char *filename, char *const argv[], char *const env[]);
355 int execve(const char *filename, char *const argv[], char *const env[]) {
356     DLSYM_FUNCTION(real_execve, "execve");
357
358     int found = 0;
359     size_t index = 0;
360
361     /* Count arguments and search for existing ENV_NAME_FDS environment
362      * variable. */
363     size_t count = 0;
364     char * const *x = env;
365     while (*x) {
366         if (!strncmp(*x, ENV_NAME_FDS "=", strlen(ENV_NAME_FDS) + 1)) {
367             found = 1;
368             index = count;
369         }
370
371         x++;
372         count++;
373     }
374     /* Terminating NULL. */
375     count++;
376
377     char *env_copy[count + 1 /* space for our new entry if necessary */];
378     memcpy(env_copy, env, count * sizeof(char *));
379
380     /* Make sure the information from the environment is loaded. We can't just
381      * do nothing (like update_environment()) because the caller might pass a
382      * different environment which doesn't include any of our settings. */
383     if (!initialized) {
384         init_from_environment();
385     }
386
387     char fds_env[strlen(ENV_NAME_FDS) + 1 + update_environment_buffer_size()];
388     strcpy(fds_env, ENV_NAME_FDS "=");
389     update_environment_buffer(fds_env + strlen(ENV_NAME_FDS) + 1);
390
391     if (found) {
392         env_copy[index] = fds_env;
393     } else {
394         /* If the process removed ENV_NAME_FDS from the environment, re-add
395          * it. */
396         env_copy[count-1] = fds_env;
397         env_copy[count] = NULL;
398     }
399
400     return real_execve(filename, argv, env_copy);
401 }
402
403 #define EXECL_COPY_VARARGS_START(args) \
404     va_list ap; \
405     char *x; \
406     \
407     /* Count arguments. */ \
408     size_t count = 1; /* arg */ \
409     va_start(ap, arg); \
410     while (va_arg(ap, const char *)) { \
411         count++; \
412     } \
413     va_end(ap); \
414     \
415     /* Copy varargs. */ \
416     char *args[count + 1 /* terminating NULL */]; \
417     args[0] = (char *)arg; \
418     \
419     size_t i = 1; \
420     va_start(ap, arg); \
421     while ((x = va_arg(ap, char *))) { \
422         args[i++] = x; \
423     } \
424     args[i] = NULL;
425 #define EXECL_COPY_VARARGS_END(args) \
426     va_end(ap);
427 #define EXECL_COPY_VARARGS(args) \
428     EXECL_COPY_VARARGS_START(args); \
429     EXECL_COPY_VARARGS_END(args);
430
431 int execl(const char *path, const char *arg, ...) {
432     EXECL_COPY_VARARGS(args);
433
434     update_environment();
435     return execv(path, args);
436 }
437
438 int execlp(const char *file, const char *arg, ...) {
439     EXECL_COPY_VARARGS(args);
440
441     update_environment();
442     return execvp(file, args);
443 }
444
445 int execle(const char *path, const char *arg, ... /*, char *const envp[] */) {
446     EXECL_COPY_VARARGS_START(args);
447     /* Get envp[] located after arguments. */
448     char * const *envp = va_arg(ap, char * const *);
449     EXECL_COPY_VARARGS_END(args);
450
451     return execve(path, args, envp);
452 }
453
454 static int (*real_execv)(const char *path, char *const argv[]);
455 int execv(const char *path, char *const argv[]) {
456     DLSYM_FUNCTION(real_execv, "execv");
457
458     update_environment();
459     return real_execv(path, argv);
460 }
461
462 static int (*real_execvp)(const char *path, char *const argv[]);
463 int execvp(const char *path, char *const argv[]) {
464     DLSYM_FUNCTION(real_execvp, "execvp");
465
466     update_environment();
467     return real_execvp(path, argv);
468 }