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