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