]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/coloredstderr.c
handle_*_pre(),handle_*_post(): Remove unused action parameter.
[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, void const *, size_t);
43 static int (*real_close)(int);
44 static size_t (*real_fwrite)(void const *, 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 const *pre_string;
123 static size_t pre_string_size;
124 static char const *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(void) {
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) {
144     if (!pre_string || !post_string) {
145         init_pre_post_string();
146     }
147
148     DLSYM_FUNCTION(real_write, "write");
149     real_write(fd, pre_string, pre_string_size);
150 }
151 static void handle_fd_post(int fd) {
152     /* write() already loaded above in handle_fd_pre(). */
153     real_write(fd, post_string, post_string_size);
154 }
155
156 static void handle_file_pre(FILE *stream) {
157     if (!pre_string || !post_string) {
158         init_pre_post_string();
159     }
160
161     DLSYM_FUNCTION(real_fwrite, "fwrite");
162     real_fwrite(pre_string, pre_string_size, 1, stream);
163 }
164 static void handle_file_post(FILE *stream) {
165     /* fwrite() already loaded above in handle_file_pre(). */
166     real_fwrite(post_string, post_string_size, 1, stream);
167 }
168
169
170
171 /* Hook all important output functions to manipulate their output. */
172
173 HOOK_FD3(ssize_t, write, fd,
174          int, fd, void const *, buf, size_t, count)
175 HOOK_FILE4(size_t, fwrite, stream,
176            void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
177
178 /* puts(3) */
179 HOOK_FILE2(int, fputs, stream,
180            char const *, s, FILE *, stream)
181 HOOK_FILE2(int, fputc, stream,
182            int, c, FILE *, stream)
183 HOOK_FILE2(int, putc, stream,
184            int, c, FILE *, stream)
185 HOOK_FILE1(int, putchar, stdout,
186            int, c)
187 HOOK_FILE1(int, puts, stdout,
188            char const *, s)
189
190 /* printf(3), excluding all s*() and vs*() functions (no output) */
191 HOOK_VAR_FILE1(int, printf, stdout, vprintf,
192                char const *, format)
193 HOOK_VAR_FILE2(int, fprintf, stream, vfprintf,
194                FILE *, stream, char const *, format)
195 HOOK_FILE2(int, vprintf, stdout,
196            char const *, format, va_list, ap)
197 HOOK_FILE3(int, vfprintf, stream,
198            FILE *, stream, char const *, format, va_list, ap)
199 /* Hardening functions (-D_FORTIFY_SOURCE=2), only functions from above */
200 HOOK_VAR_FILE2(int, __printf_chk, stdout, __vprintf_chk,
201                int, flag, char const *, format)
202 HOOK_VAR_FILE3(int, __fprintf_chk, fp, __vfprintf_chk,
203                FILE *, fp, int, flag, char const *, format)
204 HOOK_FILE3(int, __vprintf_chk, stdout,
205            int, flag, char const *, format, va_list, ap)
206 HOOK_FILE4(int, __vfprintf_chk, stream,
207            FILE *, stream, int, flag, char const *, format, va_list, ap)
208
209 /* unlocked_stdio(3), only functions from above are hooked */
210 HOOK_FILE4(size_t, fwrite_unlocked, stream,
211            void const *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
212 HOOK_FILE2(int, fputs_unlocked, stream,
213            char const *, s, FILE *, stream)
214 HOOK_FILE2(int, fputc_unlocked, stream,
215            int, c, FILE *, stream)
216 HOOK_FILE2(int, putc_unlocked, stream,
217            int, c, FILE *, stream)
218 HOOK_FILE1(int, putchar_unlocked, stdout,
219            int, c)
220
221 /* perror(3) */
222 HOOK_VOID1(void, perror, STDERR_FILENO,
223            char const *, s)
224
225 /* error(3) */
226 #ifdef HAVE_ERROR_H
227 static void  error_vararg(int status, int errnum,
228                    char const *filename, unsigned int linenum,
229                    char const *format, va_list ap) {
230     static char const *last_filename;
231     static unsigned int last_linenum;
232
233     /* Skip this error message if requested and if there was already an error
234      * in the same file/line. */
235     if (error_one_per_line
236             && filename != NULL && linenum != 0
237             && filename == last_filename && linenum == last_linenum) {
238         return;
239     }
240     last_filename = filename;
241     last_linenum  = linenum;
242
243     error_message_count++;
244
245     fflush(stdout);
246
247     if (error_print_progname) {
248         error_print_progname();
249     } else {
250         fprintf(stderr, "%s:", program_invocation_name);
251     }
252     if (filename != NULL && linenum != 0) {
253         fprintf(stderr, "%s:%u:", filename, linenum);
254         if (error_print_progname) {
255             fprintf(stderr, " ");
256         }
257     }
258     if (!error_print_progname) {
259         fprintf(stderr, " ");
260     }
261
262
263     vfprintf(stderr, format, ap);
264
265     if (errnum != 0) {
266         fprintf(stderr, ": %s", strerror(errnum));
267     }
268
269     fprintf(stderr, "\n");
270
271     if (status != 0) {
272         exit(status);
273     }
274 }
275 void error_at_line(int status, int errnum,
276                    char const *filename, unsigned int linenum,
277                    char const *format, ...) {
278     va_list ap;
279
280     va_start(ap, format);
281     error_vararg(status, errnum, filename, linenum, format, ap);
282     va_end(ap);
283 }
284 void error(int status, int errnum, char const *format, ...) {
285     va_list ap;
286
287     va_start(ap, format);
288     error_vararg(status, errnum, NULL, 0, format, ap);
289     va_end(ap);
290 }
291 #endif
292
293
294 /* Hook functions which duplicate file descriptors to track them. */
295
296 static int (*real_dup)(int);
297 static int (*real_dup2)(int, int);
298 static int (*real_dup3)(int, int, int);
299 int dup(int oldfd) {
300     int newfd;
301
302     DLSYM_FUNCTION(real_dup, "dup");
303
304     newfd = real_dup(oldfd);
305     if (newfd != -1) {
306         int saved_errno = errno;
307         dup_fd(oldfd, newfd);
308         errno = saved_errno;
309     }
310
311     return newfd;
312 }
313 int dup2(int oldfd, int newfd) {
314     DLSYM_FUNCTION(real_dup2, "dup2");
315
316     newfd = real_dup2(oldfd, newfd);
317     if (newfd != -1) {
318         int saved_errno = errno;
319         dup_fd(oldfd, newfd);
320         errno = saved_errno;
321     }
322
323     return newfd;
324 }
325 int dup3(int oldfd, int newfd, int flags) {
326     DLSYM_FUNCTION(real_dup3, "dup3");
327
328     newfd = real_dup3(oldfd, newfd, flags);
329     if (newfd != -1) {
330         int saved_errno = errno;
331         dup_fd(oldfd, newfd);
332         errno = saved_errno;
333     }
334
335     return newfd;
336 }
337
338 static int (*real_fcntl)(int, int, ...);
339 int fcntl(int fd, int cmd, ...) {
340     int result;
341     va_list ap;
342
343     DLSYM_FUNCTION(real_fcntl, "fcntl");
344
345     /* fcntl() takes different types of arguments depending on the cmd type
346      * (int, void and pointers are used at the moment). Handling these
347      * arguments for different systems and with possible changes in the future
348      * is error prone.
349      *
350      * Therefore always retrieve a void-pointer from our arguments (even if it
351      * wasn't there) and pass it to real_fcntl(). This shouldn't cause any
352      * problems because a void-pointer is most-likely bigger than an int
353      * (something which is not true in reverse) and shouldn't cause
354      * truncation. For register based calling conventions an invalid register
355      * content is passed, but ignored by real_fcntl(). Not perfect, but should
356      * work fine.
357      */
358     va_start(ap, cmd);
359     result = real_fcntl(fd, cmd, va_arg(ap, void *));
360     va_end(ap);
361
362     /* We only care about duping fds. */
363     if (cmd == F_DUPFD && result != -1) {
364         int saved_errno = errno;
365         dup_fd(fd, result);
366         errno = saved_errno;
367     }
368
369     return result;
370 }
371
372 static int (*real_close)(int);
373 int close(int fd) {
374     DLSYM_FUNCTION(real_close, "close");
375
376     close_fd(fd);
377     return real_close(fd);
378 }
379 static int (*real_fclose)(FILE *);
380 int fclose(FILE *fp) {
381     DLSYM_FUNCTION(real_fclose, "fclose");
382
383     close_fd(fileno(fp));
384     return real_fclose(fp);
385 }
386
387
388 /* Hook functions which are necessary for correct tracking. */
389
390 #if defined(HAVE_VFORK) && defined(HAVE_FORK)
391 pid_t vfork(void) {
392     /* vfork() is similar to fork() but the address space is shared between
393      * father and child. It's designed for fork()/exec() usage because it's
394      * faster than fork(). However according to the POSIX standard the "child"
395      * isn't allowed to perform any memory-modifications before the exec()
396      * (except the pid_t result variable of vfork()).
397      *
398      * As some programs don't adhere to the standard (e.g. the "child" closes
399      * or dups a descriptor before the exec()) and this breaks our tracking of
400      * file descriptors (e.g. it gets closed in the parent as well), we just
401      * fork() instead. This is in compliance with the POSIX standard and as
402      * most systems use copy-on-write anyway not a performance issue. */
403     return fork();
404 }
405 #endif
406
407
408 /* Hook execve() and the other exec*() functions. Some shells use exec*() with
409  * a custom environment which doesn't necessarily contain our updates to
410  * ENV_NAME_FDS. It's also faster to update the environment only when
411  * necessary, right before the exec() to pass it to the new process. */
412
413 static int (*real_execve)(char const *filename, char * const argv[], char * const env[]);
414 int execve(char const *filename, char * const argv[], char * const env[]) {
415     DLSYM_FUNCTION(real_execve, "execve");
416
417     int found = 0;
418     size_t index = 0;
419
420     /* Count arguments and search for existing ENV_NAME_FDS environment
421      * variable. */
422     size_t count = 0;
423     char * const *x = env;
424     while (*x) {
425         if (!strncmp(*x, ENV_NAME_FDS "=", strlen(ENV_NAME_FDS) + 1)) {
426             found = 1;
427             index = count;
428         }
429
430         x++;
431         count++;
432     }
433     /* Terminating NULL. */
434     count++;
435
436     char *env_copy[count + 1 /* space for our new entry if necessary */];
437     memcpy(env_copy, env, count * sizeof(char *));
438
439     /* Make sure the information from the environment is loaded. We can't just
440      * do nothing (like update_environment()) because the caller might pass a
441      * different environment which doesn't include any of our settings. */
442     if (!initialized) {
443         init_from_environment();
444     }
445
446     char fds_env[strlen(ENV_NAME_FDS) + 1 + update_environment_buffer_size()];
447     strcpy(fds_env, ENV_NAME_FDS "=");
448     update_environment_buffer(fds_env + strlen(ENV_NAME_FDS) + 1);
449
450     if (found) {
451         env_copy[index] = fds_env;
452     } else {
453         /* If the process removed ENV_NAME_FDS from the environment, re-add
454          * it. */
455         env_copy[count-1] = fds_env;
456         env_copy[count] = NULL;
457     }
458
459     return real_execve(filename, argv, env_copy);
460 }
461
462 #define EXECL_COPY_VARARGS_START(args) \
463     va_list ap; \
464     char *x; \
465     \
466     /* Count arguments. */ \
467     size_t count = 1; /* arg */ \
468     va_start(ap, arg); \
469     while (va_arg(ap, char const *)) { \
470         count++; \
471     } \
472     va_end(ap); \
473     \
474     /* Copy varargs. */ \
475     char *args[count + 1 /* terminating NULL */]; \
476     args[0] = (char *)arg; \
477     \
478     size_t i = 1; \
479     va_start(ap, arg); \
480     while ((x = va_arg(ap, char *))) { \
481         args[i++] = x; \
482     } \
483     args[i] = NULL;
484 #define EXECL_COPY_VARARGS_END(args) \
485     va_end(ap);
486 #define EXECL_COPY_VARARGS(args) \
487     EXECL_COPY_VARARGS_START(args); \
488     EXECL_COPY_VARARGS_END(args);
489
490 int execl(char const *path, char const *arg, ...) {
491     EXECL_COPY_VARARGS(args);
492
493     update_environment();
494     return execv(path, args);
495 }
496
497 int execlp(char const *file, char const *arg, ...) {
498     EXECL_COPY_VARARGS(args);
499
500     update_environment();
501     return execvp(file, args);
502 }
503
504 int execle(char const *path, char const *arg, ... /*, char * const envp[] */) {
505     EXECL_COPY_VARARGS_START(args);
506     /* Get envp[] located after arguments. */
507     char * const *envp = va_arg(ap, char * const *);
508     EXECL_COPY_VARARGS_END(args);
509
510     return execve(path, args, envp);
511 }
512
513 static int (*real_execv)(char const *path, char * const argv[]);
514 int execv(char const *path, char * const argv[]) {
515     DLSYM_FUNCTION(real_execv, "execv");
516
517     update_environment();
518     return real_execv(path, argv);
519 }
520
521 static int (*real_execvp)(char const *path, char * const argv[]);
522 int execvp(char const *path, char * const argv[]) {
523     DLSYM_FUNCTION(real_execvp, "execvp");
524
525     update_environment();
526     return real_execvp(path, argv);
527 }