• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <libgen.h>
20 #include <poll.h>
21 #include <pthread.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/socket.h>
26 #include <sys/types.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29 
30 #include <algorithm>
31 
32 #include <android-base/macros.h>
33 #include <cutils/klog.h>
34 #include <log/log.h>
35 #include <logwrap/logwrap.h>
36 
37 static pthread_mutex_t fd_mutex = PTHREAD_MUTEX_INITIALIZER;
38 // Protected by fd_mutex.  These signals must be blocked while modifying as well.
39 static pid_t child_pid;
40 static struct sigaction old_int;
41 static struct sigaction old_quit;
42 static struct sigaction old_hup;
43 
44 #define ERROR(fmt, args...)                         \
45     do {                                            \
46         fprintf(stderr, fmt, ##args);               \
47         ALOG(LOG_ERROR, "logwrapper", fmt, ##args); \
48     } while (0)
49 
50 #define FATAL_CHILD(fmt, args...) \
51     do {                          \
52         ERROR(fmt, ##args);       \
53         _exit(-1);                \
54     } while (0)
55 
56 #define MAX_KLOG_TAG 16
57 
58 /* This is a simple buffer that holds up to the first beginning_buf->buf_size
59  * bytes of output from a command.
60  */
61 #define BEGINNING_BUF_SIZE 0x1000
62 struct beginning_buf {
63     char* buf;
64     size_t alloc_len;
65     /* buf_size is the usable space, which is one less than the allocated size */
66     size_t buf_size;
67     size_t used_len;
68 };
69 
70 /* This is a circular buf that holds up to the last ending_buf->buf_size bytes
71  * of output from a command after the first beginning_buf->buf_size bytes
72  * (which are held in beginning_buf above).
73  */
74 #define ENDING_BUF_SIZE 0x1000
75 struct ending_buf {
76     char* buf;
77     ssize_t alloc_len;
78     /* buf_size is the usable space, which is one less than the allocated size */
79     ssize_t buf_size;
80     ssize_t used_len;
81     /* read and write offsets into the circular buffer */
82     int read;
83     int write;
84 };
85 
86 /* A structure to hold all the abbreviated buf data */
87 struct abbr_buf {
88     struct beginning_buf b_buf;
89     struct ending_buf e_buf;
90     int beginning_buf_full;
91 };
92 
93 /* Collect all the various bits of info needed for logging in one place. */
94 struct log_info {
95     int log_target;
96     char klog_fmt[MAX_KLOG_TAG * 2];
97     const char* btag;
98     bool abbreviated;
99     FILE* fp;
100     struct abbr_buf a_buf;
101 };
102 
103 /* Forware declaration */
104 static void add_line_to_abbr_buf(struct abbr_buf* a_buf, char* linebuf, int linelen);
105 
106 /* Return 0 on success, and 1 when full */
add_line_to_linear_buf(struct beginning_buf * b_buf,char * line,ssize_t line_len)107 static int add_line_to_linear_buf(struct beginning_buf* b_buf, char* line, ssize_t line_len) {
108     int full = 0;
109 
110     if ((line_len + b_buf->used_len) > b_buf->buf_size) {
111         full = 1;
112     } else {
113         /* Add to the end of the buf */
114         memcpy(b_buf->buf + b_buf->used_len, line, line_len);
115         b_buf->used_len += line_len;
116     }
117 
118     return full;
119 }
120 
add_line_to_circular_buf(struct ending_buf * e_buf,char * line,ssize_t line_len)121 static void add_line_to_circular_buf(struct ending_buf* e_buf, char* line, ssize_t line_len) {
122     ssize_t free_len;
123     ssize_t needed_space;
124     int cnt;
125 
126     if (e_buf->buf == nullptr) {
127         return;
128     }
129 
130     if (line_len > e_buf->buf_size) {
131         return;
132     }
133 
134     free_len = e_buf->buf_size - e_buf->used_len;
135 
136     if (line_len > free_len) {
137         /* remove oldest entries at read, and move read to make
138          * room for the new string */
139         needed_space = line_len - free_len;
140         e_buf->read = (e_buf->read + needed_space) % e_buf->buf_size;
141         e_buf->used_len -= needed_space;
142     }
143 
144     /* Copy the line into the circular buffer, dealing with possible
145      * wraparound.
146      */
147     cnt = std::min(line_len, e_buf->buf_size - e_buf->write);
148     memcpy(e_buf->buf + e_buf->write, line, cnt);
149     if (cnt < line_len) {
150         memcpy(e_buf->buf, line + cnt, line_len - cnt);
151     }
152     e_buf->used_len += line_len;
153     e_buf->write = (e_buf->write + line_len) % e_buf->buf_size;
154 }
155 
156 /* Log directly to the specified log */
do_log_line(struct log_info * log_info,const char * line)157 static void do_log_line(struct log_info* log_info, const char* line) {
158     if (log_info->log_target & LOG_KLOG) {
159         klog_write(6, log_info->klog_fmt, line);
160     }
161     if (log_info->log_target & LOG_ALOG) {
162         ALOG(LOG_INFO, log_info->btag, "%s", line);
163     }
164     if (log_info->fp) {
165         fprintf(log_info->fp, "%s\n", line);
166     }
167 }
168 
169 /* Log to either the abbreviated buf, or directly to the specified log
170  * via do_log_line() above.
171  */
log_line(struct log_info * log_info,char * line,int len)172 static void log_line(struct log_info* log_info, char* line, int len) {
173     if (log_info->abbreviated) {
174         add_line_to_abbr_buf(&log_info->a_buf, line, len);
175     } else {
176         do_log_line(log_info, line);
177     }
178 }
179 
180 /*
181  * The kernel will take a maximum of 1024 bytes in any single write to
182  * the kernel logging device file, so find and print each line one at
183  * a time.  The allocated size for buf should be at least 1 byte larger
184  * than buf_size (the usable size of the buffer) to make sure there is
185  * room to temporarily stuff a null byte to terminate a line for logging.
186  */
print_buf_lines(struct log_info * log_info,char * buf,int buf_size)187 static void print_buf_lines(struct log_info* log_info, char* buf, int buf_size) {
188     char* line_start;
189     char c;
190     int i;
191 
192     line_start = buf;
193     for (i = 0; i < buf_size; i++) {
194         if (*(buf + i) == '\n') {
195             /* Found a line ending, print the line and compute new line_start */
196             /* Save the next char and replace with \0 */
197             c = *(buf + i + 1);
198             *(buf + i + 1) = '\0';
199             do_log_line(log_info, line_start);
200             /* Restore the saved char */
201             *(buf + i + 1) = c;
202             line_start = buf + i + 1;
203         } else if (*(buf + i) == '\0') {
204             /* The end of the buffer, print the last bit */
205             do_log_line(log_info, line_start);
206             break;
207         }
208     }
209     /* If the buffer was completely full, and didn't end with a newline, just
210      * ignore the partial last line.
211      */
212 }
213 
init_abbr_buf(struct abbr_buf * a_buf)214 static void init_abbr_buf(struct abbr_buf* a_buf) {
215     char* new_buf;
216 
217     memset(a_buf, 0, sizeof(struct abbr_buf));
218     new_buf = static_cast<char*>(malloc(BEGINNING_BUF_SIZE));
219     if (new_buf) {
220         a_buf->b_buf.buf = new_buf;
221         a_buf->b_buf.alloc_len = BEGINNING_BUF_SIZE;
222         a_buf->b_buf.buf_size = BEGINNING_BUF_SIZE - 1;
223     }
224     new_buf = static_cast<char*>(malloc(ENDING_BUF_SIZE));
225     if (new_buf) {
226         a_buf->e_buf.buf = new_buf;
227         a_buf->e_buf.alloc_len = ENDING_BUF_SIZE;
228         a_buf->e_buf.buf_size = ENDING_BUF_SIZE - 1;
229     }
230 }
231 
free_abbr_buf(struct abbr_buf * a_buf)232 static void free_abbr_buf(struct abbr_buf* a_buf) {
233     free(a_buf->b_buf.buf);
234     free(a_buf->e_buf.buf);
235 }
236 
add_line_to_abbr_buf(struct abbr_buf * a_buf,char * linebuf,int linelen)237 static void add_line_to_abbr_buf(struct abbr_buf* a_buf, char* linebuf, int linelen) {
238     if (!a_buf->beginning_buf_full) {
239         a_buf->beginning_buf_full = add_line_to_linear_buf(&a_buf->b_buf, linebuf, linelen);
240     }
241     if (a_buf->beginning_buf_full) {
242         add_line_to_circular_buf(&a_buf->e_buf, linebuf, linelen);
243     }
244 }
245 
print_abbr_buf(struct log_info * log_info)246 static void print_abbr_buf(struct log_info* log_info) {
247     struct abbr_buf* a_buf = &log_info->a_buf;
248 
249     /* Add the abbreviated output to the kernel log */
250     if (a_buf->b_buf.alloc_len) {
251         print_buf_lines(log_info, a_buf->b_buf.buf, a_buf->b_buf.used_len);
252     }
253 
254     /* Print an ellipsis to indicate that the buffer has wrapped or
255      * is full, and some data was not logged.
256      */
257     if (a_buf->e_buf.used_len == a_buf->e_buf.buf_size) {
258         do_log_line(log_info, "...\n");
259     }
260 
261     if (a_buf->e_buf.used_len == 0) {
262         return;
263     }
264 
265     /* Simplest way to print the circular buffer is allocate a second buf
266      * of the same size, and memcpy it so it's a simple linear buffer,
267      * and then cal print_buf_lines on it */
268     if (a_buf->e_buf.read < a_buf->e_buf.write) {
269         /* no wrap around, just print it */
270         print_buf_lines(log_info, a_buf->e_buf.buf + a_buf->e_buf.read, a_buf->e_buf.used_len);
271     } else {
272         /* The circular buffer will always have at least 1 byte unused,
273          * so by allocating alloc_len here we will have at least
274          * 1 byte of space available as required by print_buf_lines().
275          */
276         char* nbuf = static_cast<char*>(malloc(a_buf->e_buf.alloc_len));
277         if (!nbuf) {
278             return;
279         }
280         int first_chunk_len = a_buf->e_buf.buf_size - a_buf->e_buf.read;
281         memcpy(nbuf, a_buf->e_buf.buf + a_buf->e_buf.read, first_chunk_len);
282         /* copy second chunk */
283         memcpy(nbuf + first_chunk_len, a_buf->e_buf.buf, a_buf->e_buf.write);
284         print_buf_lines(log_info, nbuf, first_chunk_len + a_buf->e_buf.write);
285         free(nbuf);
286     }
287 }
288 
289 static void signal_handler(int signal_num);
290 
block_signals(sigset_t * oldset)291 static void block_signals(sigset_t* oldset) {
292     sigset_t blockset;
293 
294     sigemptyset(&blockset);
295     sigaddset(&blockset, SIGINT);
296     sigaddset(&blockset, SIGQUIT);
297     sigaddset(&blockset, SIGHUP);
298     pthread_sigmask(SIG_BLOCK, &blockset, oldset);
299 }
300 
unblock_signals(sigset_t * oldset)301 static void unblock_signals(sigset_t* oldset) {
302     pthread_sigmask(SIG_SETMASK, oldset, nullptr);
303 }
304 
setup_signal_handlers(pid_t pid)305 static void setup_signal_handlers(pid_t pid) {
306     struct sigaction handler = {.sa_handler = signal_handler};
307 
308     child_pid = pid;
309     sigaction(SIGINT, &handler, &old_int);
310     sigaction(SIGQUIT, &handler, &old_quit);
311     sigaction(SIGHUP, &handler, &old_hup);
312 }
313 
restore_signal_handlers()314 static void restore_signal_handlers() {
315     sigaction(SIGINT, &old_int, nullptr);
316     sigaction(SIGQUIT, &old_quit, nullptr);
317     sigaction(SIGHUP, &old_hup, nullptr);
318     child_pid = 0;
319 }
320 
signal_handler(int signal_num)321 static void signal_handler(int signal_num) {
322     if (child_pid == 0 || kill(child_pid, signal_num) != 0) {
323         restore_signal_handlers();
324         raise(signal_num);
325     }
326 }
327 
parent(const char * tag,int parent_read,pid_t pid,int * chld_sts,int log_target,bool abbreviated,const char * file_path,bool forward_signals)328 static int parent(const char* tag, int parent_read, pid_t pid, int* chld_sts, int log_target,
329                   bool abbreviated, const char* file_path, bool forward_signals) {
330     int status = 0;
331     char buffer[4096];
332     struct pollfd poll_fds[] = {
333             {
334                     .fd = parent_read,
335                     .events = POLLIN,
336             },
337     };
338     int rc = 0;
339     int fd;
340 
341     struct log_info log_info = {};
342 
343     int a = 0;  // start index of unprocessed data
344     int b = 0;  // end index of unprocessed data
345     int sz;
346     bool found_child = false;
347     // There is a very small chance that opening child_ptty in the child will fail, but in this case
348     // POLLHUP will not be generated below.  Therefore, we use a 1 second timeout for poll() until
349     // we receive a message from child_ptty.  If this times out, we call waitpid() with WNOHANG to
350     // check the status of the child process and exit appropriately if it has terminated.
351     bool received_messages = false;
352     char tmpbuf[256];
353 
354     log_info.btag = basename(tag);
355     if (!log_info.btag) {
356         log_info.btag = tag;
357     }
358 
359     if (abbreviated && (log_target == LOG_NONE)) {
360         abbreviated = 0;
361     }
362     if (abbreviated) {
363         init_abbr_buf(&log_info.a_buf);
364     }
365 
366     if (log_target & LOG_KLOG) {
367         snprintf(log_info.klog_fmt, sizeof(log_info.klog_fmt), "<6>%.*s: %%s\n", MAX_KLOG_TAG,
368                  log_info.btag);
369     }
370 
371     if ((log_target & LOG_FILE) && !file_path) {
372         /* No file_path specified, clear the LOG_FILE bit */
373         log_target &= ~LOG_FILE;
374     }
375 
376     if (log_target & LOG_FILE) {
377         fd = open(file_path, O_WRONLY | O_CREAT | O_CLOEXEC, 0664);
378         if (fd < 0) {
379             ERROR("Cannot log to file %s\n", file_path);
380             log_target &= ~LOG_FILE;
381         } else {
382             lseek(fd, 0, SEEK_END);
383             log_info.fp = fdopen(fd, "a");
384         }
385     }
386 
387     log_info.log_target = log_target;
388     log_info.abbreviated = abbreviated;
389 
390     while (!found_child) {
391         int timeout = received_messages ? -1 : 1000;
392         if (TEMP_FAILURE_RETRY(poll(poll_fds, arraysize(poll_fds), timeout)) < 0) {
393             ERROR("poll failed\n");
394             rc = -1;
395             goto err_poll;
396         }
397 
398         if (poll_fds[0].revents & POLLIN) {
399             received_messages = true;
400             sz = TEMP_FAILURE_RETRY(read(parent_read, &buffer[b], sizeof(buffer) - 1 - b));
401 
402             sz += b;
403             // Log one line at a time
404             for (b = 0; b < sz; b++) {
405                 if (buffer[b] == '\r') {
406                     if (abbreviated) {
407                         /* The abbreviated logging code uses newline as
408                          * the line separator.  Lucikly, the pty layer
409                          * helpfully cooks the output of the command
410                          * being run and inserts a CR before NL.  So
411                          * I just change it to NL here when doing
412                          * abbreviated logging.
413                          */
414                         buffer[b] = '\n';
415                     } else {
416                         buffer[b] = '\0';
417                     }
418                 } else if (buffer[b] == '\n') {
419                     buffer[b] = '\0';
420                     log_line(&log_info, &buffer[a], b - a);
421                     a = b + 1;
422                 }
423             }
424 
425             if (a == 0 && b == sizeof(buffer) - 1) {
426                 // buffer is full, flush
427                 buffer[b] = '\0';
428                 log_line(&log_info, &buffer[a], b - a);
429                 b = 0;
430             } else if (a != b) {
431                 // Keep left-overs
432                 b -= a;
433                 memmove(buffer, &buffer[a], b);
434                 a = 0;
435             } else {
436                 a = 0;
437                 b = 0;
438             }
439         }
440 
441         if (!received_messages || (poll_fds[0].revents & POLLHUP)) {
442             int ret;
443             sigset_t oldset;
444 
445             if (forward_signals) {
446                 // Our signal handlers forward these signals to 'child_pid', but waitpid() may reap
447                 // the child, so we must block these signals until we either 1) conclude that the
448                 // child is still running or 2) determine the child has been reaped and we have
449                 // reset the signals to their original disposition.
450                 block_signals(&oldset);
451             }
452 
453             int flags = (poll_fds[0].revents & POLLHUP) ? 0 : WNOHANG;
454             ret = TEMP_FAILURE_RETRY(waitpid(pid, &status, flags));
455             if (ret < 0) {
456                 rc = errno;
457                 ALOG(LOG_ERROR, "logwrap", "waitpid failed with %s\n", strerror(errno));
458                 goto err_waitpid;
459             }
460             if (ret > 0) {
461                 found_child = true;
462             }
463 
464             if (forward_signals) {
465                 if (found_child) {
466                     restore_signal_handlers();
467                 }
468                 unblock_signals(&oldset);
469             }
470         }
471     }
472 
473     if (chld_sts != nullptr) {
474         *chld_sts = status;
475     } else {
476         if (WIFEXITED(status))
477             rc = WEXITSTATUS(status);
478         else
479             rc = -ECHILD;
480     }
481 
482     // Flush remaining data
483     if (a != b) {
484         buffer[b] = '\0';
485         log_line(&log_info, &buffer[a], b - a);
486     }
487 
488     /* All the output has been processed, time to dump the abbreviated output */
489     if (abbreviated) {
490         print_abbr_buf(&log_info);
491     }
492 
493     if (WIFEXITED(status)) {
494         if (WEXITSTATUS(status)) {
495             snprintf(tmpbuf, sizeof(tmpbuf), "%s terminated by exit(%d)\n", log_info.btag,
496                      WEXITSTATUS(status));
497             do_log_line(&log_info, tmpbuf);
498         }
499     } else {
500         if (WIFSIGNALED(status)) {
501             snprintf(tmpbuf, sizeof(tmpbuf), "%s terminated by signal %d\n", log_info.btag,
502                      WTERMSIG(status));
503             do_log_line(&log_info, tmpbuf);
504         } else if (WIFSTOPPED(status)) {
505             snprintf(tmpbuf, sizeof(tmpbuf), "%s stopped by signal %d\n", log_info.btag,
506                      WSTOPSIG(status));
507             do_log_line(&log_info, tmpbuf);
508         }
509     }
510 
511 err_waitpid:
512 err_poll:
513     if (log_info.fp) {
514         fclose(log_info.fp);
515     }
516     if (abbreviated) {
517         free_abbr_buf(&log_info.a_buf);
518     }
519     return rc;
520 }
521 
child(int argc,const char * const * argv)522 static void child(int argc, const char* const* argv) {
523     // create null terminated argv_child array
524     char* argv_child[argc + 1];
525     memcpy(argv_child, argv, argc * sizeof(char*));
526     argv_child[argc] = nullptr;
527 
528     if (execvp(argv_child[0], argv_child)) {
529         FATAL_CHILD("executing %s failed: %s\n", argv_child[0], strerror(errno));
530     }
531 }
532 
logwrap_fork_execvp(int argc,const char * const * argv,int * status,bool forward_signals,int log_target,bool abbreviated,const char * file_path)533 int logwrap_fork_execvp(int argc, const char* const* argv, int* status, bool forward_signals,
534                         int log_target, bool abbreviated, const char* file_path) {
535     pid_t pid;
536     int parent_ptty;
537     sigset_t oldset;
538     int rc = 0;
539 
540     rc = pthread_mutex_lock(&fd_mutex);
541     if (rc) {
542         ERROR("failed to lock signal_fd mutex\n");
543         goto err_lock;
544     }
545 
546     /* Use ptty instead of socketpair so that STDOUT is not buffered */
547     parent_ptty = TEMP_FAILURE_RETRY(posix_openpt(O_RDWR | O_CLOEXEC));
548     if (parent_ptty < 0) {
549         ERROR("Cannot create parent ptty\n");
550         rc = -1;
551         goto err_open;
552     }
553 
554     char child_devname[64];
555     if (grantpt(parent_ptty) || unlockpt(parent_ptty) ||
556         ptsname_r(parent_ptty, child_devname, sizeof(child_devname)) != 0) {
557         ERROR("Problem with /dev/ptmx\n");
558         rc = -1;
559         goto err_ptty;
560     }
561 
562     if (forward_signals) {
563         // Block these signals until we have the child pid and our signal handlers set up.
564         block_signals(&oldset);
565     }
566 
567     pid = fork();
568     if (pid < 0) {
569         ERROR("Failed to fork\n");
570         rc = -1;
571         goto err_fork;
572     } else if (pid == 0) {
573         pthread_mutex_unlock(&fd_mutex);
574         if (forward_signals) {
575             unblock_signals(&oldset);
576         }
577 
578         setsid();
579 
580         int child_ptty = TEMP_FAILURE_RETRY(open(child_devname, O_RDWR | O_CLOEXEC));
581         if (child_ptty < 0) {
582             FATAL_CHILD("Cannot open child_ptty: %s\n", strerror(errno));
583         }
584         close(parent_ptty);
585 
586         dup2(child_ptty, 1);
587         dup2(child_ptty, 2);
588         close(child_ptty);
589 
590         child(argc, argv);
591     } else {
592         if (forward_signals) {
593             setup_signal_handlers(pid);
594             unblock_signals(&oldset);
595         }
596 
597         rc = parent(argv[0], parent_ptty, pid, status, log_target, abbreviated, file_path,
598                     forward_signals);
599 
600         if (forward_signals) {
601             restore_signal_handlers();
602         }
603     }
604 
605 err_fork:
606     if (forward_signals) {
607         unblock_signals(&oldset);
608     }
609 err_ptty:
610     close(parent_ptty);
611 err_open:
612     pthread_mutex_unlock(&fd_mutex);
613 err_lock:
614     return rc;
615 }
616