]> ruderich.org/simon Gitweb - coloredstderr/coloredstderr.git/blob - src/coloredstderr.c
Minor documentation updates.
[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
66     /* Never touch anything not going to a terminal - unless we are explicitly
67      * asked to do so. */
68     if (!force_write_to_non_tty && !isatty(fd)) {
69         return 0;
70     }
71
72     if (tracked_fds_count == 0) {
73         return 0;
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             update_environment();
96         }
97     /* We are not tracking this file descriptor, remove newfd from the list
98      * (if present). */
99     } else {
100         if (tracked_fds_remove(newfd)) {
101             update_environment();
102         }
103     }
104 }
105
106 static void close_fd(int fd) {
107 #ifdef DEBUG
108     debug("%3d ->   .\t\t\t[%d]\n", fd, getpid());
109 #endif
110
111     if (!initialized) {
112         init_from_environment();
113     }
114
115     if (tracked_fds_count == 0) {
116         return;
117     }
118     tracked_fds_remove(fd);
119 }
120
121
122 /* "Action" handlers called when a file descriptor is matched. */
123
124 static char *pre_string;
125 static size_t pre_string_size;
126 static char *post_string;
127 static size_t post_string_size;
128
129 /* Load alternative pre/post strings from the environment if available, fall
130  * back to default values. */
131 inline static void init_pre_post_string() {
132     pre_string = getenv(ENV_NAME_PRE_STRING);
133     if (!pre_string) {
134         pre_string = DEFAULT_PRE_STRING;
135     }
136     pre_string_size = strlen(pre_string);
137
138     post_string = getenv(ENV_NAME_POST_STRING);
139     if (!post_string) {
140         post_string = DEFAULT_POST_STRING;
141     }
142     post_string_size = strlen(post_string);
143 }
144
145 static void handle_fd_pre(int fd, int action) {
146     (void)action;
147
148     if (!pre_string || !post_string) {
149         init_pre_post_string();
150     }
151
152     DLSYM_FUNCTION(real_write, "write");
153     real_write(fd, pre_string, pre_string_size);
154 }
155 static void handle_fd_post(int fd, int action) {
156     (void)action;
157
158     /* write() already loaded above in handle_fd_pre(). */
159     real_write(fd, post_string, post_string_size);
160 }
161
162 static void handle_file_pre(FILE *stream, int action) {
163     (void)action;
164
165     if (!pre_string || !post_string) {
166         init_pre_post_string();
167     }
168
169     DLSYM_FUNCTION(real_fwrite, "fwrite");
170     real_fwrite(pre_string, pre_string_size, 1, stream);
171 }
172 static void handle_file_post(FILE *stream, int action) {
173     (void)action;
174
175     /* fwrite() already loaded above in handle_file_pre(). */
176     real_fwrite(post_string, post_string_size, 1, stream);
177 }
178
179
180
181 /* Hook all important output functions to manipulate their output. */
182
183 HOOK_FD3(ssize_t, write, fd,
184          int, fd, const void *, buf, size_t, count)
185 HOOK_FILE4(size_t, fwrite, stream,
186            const void *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
187
188 /* puts(3) */
189 HOOK_FILE2(int, fputs, stream,
190            const char *, s, FILE *, stream)
191 HOOK_FILE2(int, fputc, stream,
192            int, c, FILE *, stream)
193 HOOK_FILE2(int, putc, stream,
194            int, c, FILE *, stream)
195 HOOK_FILE1(int, putchar, stdout,
196            int, c)
197 HOOK_FILE1(int, puts, stdout,
198            const char *, s)
199
200 /* printf(3), excluding all s*() and vs*() functions (no output) */
201 HOOK_VAR_FILE1(int, printf, stdout, vprintf,
202                const char *, format)
203 HOOK_VAR_FILE2(int, fprintf, stream, vfprintf,
204                FILE *, stream, const char *, format)
205 HOOK_FILE2(int, vprintf, stdout,
206            const char *, format, va_list, ap)
207 HOOK_FILE3(int, vfprintf, stream,
208            FILE *, stream, const char *, format, va_list, ap)
209 /* Hardening functions (-D_FORTIFY_SOURCE=2), only functions from above */
210 HOOK_VAR_FILE2(int, __printf_chk, stdout, __vprintf_chk,
211                int, flag, const char *, format)
212 HOOK_VAR_FILE3(int, __fprintf_chk, fp, __vfprintf_chk,
213                FILE *, fp, int, flag, const char *, format)
214 HOOK_FILE3(int, __vprintf_chk, stdout,
215            int, flag, const char *, format, va_list, ap)
216 HOOK_FILE4(int, __vfprintf_chk, stream,
217            FILE *, stream, int, flag, const char *, format, va_list, ap)
218
219 /* unlocked_stdio(3), only functions from above are hooked */
220 HOOK_FILE4(size_t, fwrite_unlocked, stream,
221            const void *, ptr, size_t, size, size_t, nmemb, FILE *, stream)
222 HOOK_FILE2(int, fputs_unlocked, stream,
223            const char *, s, FILE *, stream)
224 HOOK_FILE2(int, fputc_unlocked, stream,
225            int, c, FILE *, stream)
226 HOOK_FILE2(int, putc_unlocked, stream,
227            int, c, FILE *, stream)
228 HOOK_FILE1(int, putchar_unlocked, stdout,
229            int, c)
230 HOOK_FILE1(int, puts_unlocked, stdout,
231            const char *, s)
232
233 /* perror(3) */
234 HOOK_VOID1(void, perror, STDERR_FILENO,
235            const char *, s)
236
237
238 /* Hook functions which duplicate file descriptors to track them. */
239
240 static int (*real_dup)(int);
241 static int (*real_dup2)(int, int);
242 static int (*real_dup3)(int, int, int);
243 int dup(int oldfd) {
244     int newfd;
245
246     DLSYM_FUNCTION(real_dup, "dup");
247
248     newfd = real_dup(oldfd);
249     if (newfd != -1) {
250         int saved_errno = errno;
251         dup_fd(oldfd, newfd);
252         errno = saved_errno;
253     }
254
255     return newfd;
256 }
257 int dup2(int oldfd, int newfd) {
258     DLSYM_FUNCTION(real_dup2, "dup2");
259
260     newfd = real_dup2(oldfd, newfd);
261     if (newfd != -1) {
262         int saved_errno = errno;
263         dup_fd(oldfd, newfd);
264         errno = saved_errno;
265     }
266
267     return newfd;
268 }
269 int dup3(int oldfd, int newfd, int flags) {
270     DLSYM_FUNCTION(real_dup3, "dup3");
271
272     newfd = real_dup3(oldfd, newfd, flags);
273     if (newfd != -1) {
274         int saved_errno = errno;
275         dup_fd(oldfd, newfd);
276         errno = saved_errno;
277     }
278
279     return newfd;
280 }
281
282 static int (*real_fcntl)(int, int, ...);
283 int fcntl(int fd, int cmd, ...) {
284     int result;
285     va_list ap;
286
287     DLSYM_FUNCTION(real_fcntl, "fcntl");
288
289     /* fcntl() takes different types of arguments depending on the cmd type
290      * (int, void and pointers are used at the moment). Handling these
291      * arguments for different systems and with possible changes in the future
292      * is error prone.
293      *
294      * Therefore always retrieve a void-pointer from our arguments (even if it
295      * wasn't there) and pass it to real_fcntl(). This shouldn't cause any
296      * problems because a void-pointer is most-likely bigger than an int
297      * (something which is not true in reverse) and shouldn't cause
298      * truncation. For register based calling conventions an invalid register
299      * content is passed, but ignored by real_fcntl(). Not perfect, but should
300      * work fine.
301      */
302     va_start(ap, cmd);
303     result = real_fcntl(fd, cmd, va_arg(ap, void *));
304     va_end(ap);
305
306     /* We only care about duping fds. */
307     if (cmd == F_DUPFD && result != -1) {
308         int saved_errno = errno;
309         dup_fd(fd, result);
310         errno = saved_errno;
311     }
312
313     return result;
314 }
315
316 static int (*real_close)(int);
317 int close(int fd) {
318     DLSYM_FUNCTION(real_close, "close");
319
320     close_fd(fd);
321     return real_close(fd);
322 }
323 static int (*real_fclose)(FILE *);
324 int fclose(FILE *fp) {
325     DLSYM_FUNCTION(real_fclose, "fclose");
326
327     close_fd(fileno(fp));
328     return real_fclose(fp);
329 }
330
331
332 /* Hook functions which are necessary for correct tracking. */
333
334 #if defined(HAVE_VFORK) && defined(HAVE_FORK)
335 pid_t vfork(void) {
336     /* vfork() is similar to fork() but the address space is shared between
337      * father and child. It's designed for fork()/exec() usage because it's
338      * faster than fork(). However according to the POSIX standard the "child"
339      * isn't allowed to perform any memory-modifications before the exec()
340      * (except the pid_t result variable of vfork()).
341      *
342      * As some programs don't adhere to the standard (e.g. the "child" closes
343      * or dups a descriptor before the exec()) and this breaks our tracking of
344      * file descriptors (e.g. it gets closed in the parent as well), we just
345      * fork() instead. This is in compliance with the POSIX standard and as
346      * most systems use copy-on-write anyway not a performance issue. */
347     return fork();
348 }
349 #endif