Don't wait until lazy init to block SIGPIPE
[platform/core/system/dlog.git] / src / libdlog / log.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: t -*-
2  * DLOG
3  * Copyright (c) 2005-2008, The Android Open Source Project
4  * Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
5  *
6  * Licensed under the Apache License, Version 2.0 (the License);
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18
19 // C
20 #include <assert.h>
21 #include <stdbool.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 // POSIX
26 #include <pthread.h>
27 #include <sys/wait.h>
28 #include <unistd.h>
29
30 // DLog
31 #include <dynamic_config.h>
32 #include <libdlog.h>
33 #include <logcommon.h>
34 #include "logconfig.h"
35 #include "loglimiter.h"
36
37 #define DEFAULT_CONFIG_LIMITER false
38 #define DEFAULT_CONFIG_PLOG true
39 #define DEFAULT_CONFIG_DEBUGMODE 0
40 #define DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS 0
41
42 /**
43  * @brief Points to a function which writes a log message
44  * @details The function pointed to depends on the backend used
45  * @param[in] log_id ID of the buffer to log to. Belongs to (LOG_ID_INVALID, LOG_ID_MAX) non-inclusive
46  * @param[in] prio Priority of the message.
47  * @param[in] tag The message tag, identifies the sender.
48  * @param[in] msg The contents of the message.
49  * @return Returns the number of bytes written on success and a negative error value on error.
50  * @see __dlog_init_backend
51  */
52 int (*write_to_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg) = NULL;
53 void (*destroy_backend)();
54
55 pthread_rwlock_t log_limiter_lock = PTHREAD_RWLOCK_INITIALIZER;
56 static pthread_mutex_t log_construction_lock = PTHREAD_MUTEX_INITIALIZER;
57 static bool is_initialized = false;
58
59 extern void __dlog_init_pipe(const struct log_config *conf);
60 extern void __dlog_init_android(const struct log_config *conf);
61
62 bool limiter;
63 static bool dynamic_config;
64 static bool plog[LOG_ID_MAX];
65 static bool plog_default_values[LOG_ID_MAX];
66
67 static int debugmode;
68 static int fatal_assert;
69 static int limiter_apply_to_all_buffers;
70
71 static void __configure_limiter(struct log_config *config)
72 {
73         assert(config);
74
75         if (!limiter)
76                 return;
77
78         limiter = __log_limiter_create(config);
79 }
80
81 static int __configure_backend(struct log_config *config)
82 {
83         assert(config);
84
85         const char *const backend = log_config_get(config, "backend");
86         if (!backend)
87                 return 0;
88
89         if (!strcmp(backend, "pipe"))
90                 __dlog_init_pipe(config);
91         else if (!strcmp(backend, "logger"))
92                 __dlog_init_android(config);
93         else
94                 return 0;
95
96         return 1;
97 }
98
99 static void __set_plog_default_values()
100 {
101         for (int i = 0; i < NELEMS(plog); ++i)
102                 plog_default_values[i] = plog[i];
103 }
104
105 static void __initialize_plog(const struct log_config *config)
106 {
107         assert(config);
108
109         const bool plog_default = log_config_get_boolean(config, "plog", DEFAULT_CONFIG_PLOG);
110         for (int i = 0; i < NELEMS(plog); ++i)
111                 plog[i] = plog_default;
112         plog[LOG_ID_APPS] = true; // the default does not apply here for backward compatibility reasons.
113         __set_plog_default_values();
114 }
115
116 static void __configure_parameters(struct log_config *config)
117 {
118         assert(config);
119
120         __initialize_plog(config);
121         __update_plog(config);
122         __set_plog_default_values();
123
124         debugmode = log_config_get_int(config, "debugmode", DEFAULT_CONFIG_DEBUGMODE);
125         fatal_assert = access(DEBUGMODE_FILE, F_OK) != -1;
126         limiter = log_config_get_boolean(config, "limiter", DEFAULT_CONFIG_LIMITER);
127         limiter_apply_to_all_buffers = log_config_get_int(config,
128                                                                         "limiter_apply_to_all_buffers",
129                                                                         DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS);
130 }
131
132 void __update_plog(const struct log_config *conf)
133 {
134         assert(conf);
135
136         for (int i = 0; i < NELEMS(plog); ++i) {
137                 char key[MAX_CONF_KEY_LEN];
138                 const int r = snprintf(key, sizeof key, "enable_%s", log_name_by_id((log_id_t)i));
139                 if (r < 0)
140                         continue;
141                 plog[i] = log_config_get_boolean(conf, key, plog_default_values[i]);
142         }
143 }
144
145 /**
146  * @brief Configure the library
147  * @details Reads relevant config values
148  * @remarks This is more or less a constructor, but there are some obstacles
149  *          to using it as such (i.e. with attribute constructor):
150  *
151  *  - some important pieces of the system link to dlog, they start very early
152  *    such that dlog can't properly initialize (which lasts for program lifetime)
153  *    but don't actually log anything until later on and would be fine under lazy
154  *    initialisation. The way to do it "properly" would be to expose this function
155  *    into the API so that people can manually call it when they're ready, but
156  *    one of the design goals of the current API is that it requires absolutely no
157  *    other calls than `dlog_print`. Changing it would require somebody with a
158  *    bird's eye view of the system to produce a design so I wouldn't count on it.
159  *
160  *  - the constructor would need to have as high of a priority as possible (so as
161  *    to minimize the risk of another library's constructor using uninitialized data)
162  *    but at the same time others might want some room to wrap functions before
163  *    dlog uses them (think mprobe/mcheck). This would also require a design pass.
164  */
165 #ifndef UNIT_TEST
166 static
167 #endif
168 bool __configure(void)
169 {
170         __attribute__((cleanup(log_config_free))) struct log_config config;
171
172         if (log_config_read(&config) < 0)
173                 return false;
174
175         dynamic_config = __dynamic_config_create(&config);
176
177         __configure_parameters(&config);
178
179         if (!__configure_backend(&config)) {
180                 __dynamic_config_destroy();
181                 dynamic_config = false;
182                 return false;
183         }
184
185         __configure_limiter(&config);
186         return true;
187 }
188
189 static void __attribute__((constructor(101))) __install_pipe_handler(void)
190 {
191         /* We mask SIGPIPE signal because most applications do not install their
192          * own SIGPIPE handler. Default behaviour in SIGPIPE case is to abort the
193          * process. SIGPIPE occurs when e.g. dlog daemon closes read pipe endpoint.
194          *
195          * We do this in the library constructor (at maximum priority) and not
196          * during regular (lazy) initialisation so as to prevent overwriting the
197          * program's actual signal handler, if it has one.
198          *
199          * In theory this is not required for the Android logger backend; however,
200          * this early we don't yet know the backend and also it is good to behave
201          * consistently in this regard anyway.
202          *
203          * We don't revert this in a destructor because Unix signals are bonkers
204          * and we have no way to do this cleanly. Most libdlog users don't use
205          * runtime linking so this would mostly done at program exit either way. */
206         signal(SIGPIPE, SIG_IGN);
207 }
208
209 static bool first = true;
210 static bool initialize()
211 {
212         if (is_initialized)
213                 return true;
214
215         /* The mutex acts as a barrier, but otherwise the C language's
216          * machine abstraction is single-threaded. This means that the
217          * compiler is free to rearrange calls inside the mutex according
218          * to the as-if rule because it doesn't care if another thread can
219          * access it in parallel. In particular, `is_initialized = true`
220          * directly after `__configure()` could be rearranged to go in
221          * front of it because it is not touched inside that function
222          * if the compiler thinks it helps somehow (not unlikely: since
223          * it is checked before the mutex, it is very probable for it to
224          * still be in the CPU register or something like that). On top
225          * of that, some architectures (in particular, armv7l) don't have
226          * strict memory guarantees and can reorder actual memory stores
227          * on their own, even if the compiler didn't do anything fancy
228          * when creating machine code. For more info about the issue,
229          * see https://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
230          *
231          * Ultimately this means that there needs to be some sort of
232          * barrier between `__configure` and `is_initialized = true`,
233          * and the simplest way to achieve that is to just wait until
234          * the second entry into the mutex. */
235
236         bool ret;
237         pthread_mutex_lock(&log_construction_lock);
238                 if (first)
239                         first = !__configure();
240                 else
241                         is_initialized = true;
242                 ret = !first;
243         pthread_mutex_unlock(&log_construction_lock);
244         return ret;
245 }
246
247 /**
248  * @brief Fatal assertion
249  * @details Conditionally crash the sucka who sent the log
250  * @param[in] prio Priority of the log
251  */
252 static void __dlog_fatal_assert(int prio)
253 {
254         assert(!fatal_assert || (prio != DLOG_FATAL));
255 }
256
257 /**
258  * @brief Check log validity
259  * @details Checks whether the log is valid and eligible for printing
260  * @param[in] log_id The target buffer ID
261  * @param[in] prio The log's priority
262  * @param[in] tag The log's tag
263  * @return DLOG_ERROR_NONE on success, else an error code.
264  * @retval DLOG_ERROR_INVALID_PARAMETER Invalid parameter
265  */
266 static int dlog_check_validity(log_id_t log_id, int prio, const char *tag)
267 {
268         if (!tag)
269                 return DLOG_ERROR_INVALID_PARAMETER;
270
271         if (log_id <= LOG_ID_INVALID || LOG_ID_MAX <= log_id)
272                 return DLOG_ERROR_INVALID_PARAMETER;
273
274         return DLOG_ERROR_NONE;
275 }
276
277 /**
278  * @brief Check log against limiter rules
279  * @details Checks whether the log passes current limiter rules
280  * @param[in] log_id The target buffer ID
281  * @param[in] prio The log's priority
282  * @param[in] tag The log's tag
283  * @return DLOG_ERROR_NONE on success, else an error code.
284  * @retval DLOG_ERROR_NOT_PERMITTED Not permitted
285  */
286 static int dlog_check_limiter(log_id_t log_id, int prio, const char *tag)
287 {
288         if (!debugmode && prio <= DLOG_DEBUG)
289                 return DLOG_ERROR_NOT_PERMITTED;
290
291         if (dynamic_config)
292                 __dynamic_config_update();
293
294         if (limiter) {
295                 int should_log = 0;
296                 if (!pthread_rwlock_rdlock(&log_limiter_lock)) {
297                         should_log = __log_limiter_pass_log(tag, prio);
298                         pthread_rwlock_unlock(&log_limiter_lock);
299                 }
300
301                 if (!should_log) {
302                         return DLOG_ERROR_NOT_PERMITTED;
303                 } else if (should_log < 0) {
304                         write_to_log(log_id, prio, tag,
305                                         "Your log has been blocked due to limit of log lines per minute.");
306                         return DLOG_ERROR_NOT_PERMITTED;
307                 }
308         }
309
310         /* This can change due to __dynamic_config_update(), but is atomic and its
311          * value implies nothing else so does not need to be under a lock. */
312         if (!plog[log_id])
313                 return DLOG_ERROR_NOT_PERMITTED;
314
315         return DLOG_ERROR_NONE;
316 }
317
318 static int __write_to_log_critical_section(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap, bool check_should_log)
319 {
320         if ((check_should_log || limiter_apply_to_all_buffers) && (dlog_check_limiter(log_id, prio, tag) < 0))
321                 return DLOG_ERROR_NONE;
322
323         char buf[LOG_MAX_PAYLOAD_SIZE];
324         vsnprintf(buf, sizeof buf, fmt, ap);
325         return write_to_log(log_id, prio, tag, buf);
326 }
327
328 static int __write_to_log(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap, bool check_should_log)
329 {
330         int ret = dlog_check_validity(log_id, prio, tag);
331         if (ret < 0)
332                 return ret;
333
334         /* Threads can be cancelled before they give up a lock.
335          * Therefore cancellation is temporarily disabled.
336          * This solution is comparatively simple and cheap.
337          * The other solutions (cleanup handlers, robust mutexes)
338          * would be much more complicated and also inflict larger
339          * runtime costs. The downside of disabling cancellation
340          * is not a problem in our case because it is temporary
341          * and very brief so we don't keep an obsolete thread
342          * for much longer than we otherwise would. */
343         int old_cancel_state;
344         pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancel_state);
345
346         /* The only thing that needs to be protected here is `write_to_log` since
347          * all other resources already have their own specific locks (and even the
348          * pointer could be made to point at a null handler instead of a true NULL)
349          * but giving this guarantee makes everything a lot simpler as it removes
350          * the risk of something suddenly becoming NULL during processing. */
351         ret = !initialize() || !write_to_log
352                 ? DLOG_ERROR_NOT_PERMITTED
353                 : __write_to_log_critical_section(log_id, prio, tag, fmt, ap, check_should_log)
354                 ;
355
356         pthread_setcancelstate(old_cancel_state, NULL);
357
358         return ret;
359 }
360
361 int __critical_log_append_timestamp(char *buf, size_t buflen)
362 {
363         /* NB: the timestamp may slightly differ from the one that gets
364          * added onto the copy that goes into the regular buffer, and
365          * timestamp acquisition is duplicated. This would ideally be
366          * solved, but timestamps are currently added fairly deep in
367          * backend-specific functions so for now this will have to do.
368          * Also, since we're the sender, there is just this one set of
369          * timestamps, i.e. the send timestamp! The usual alternative
370          * set of receive timestamps will never have the opportunity
371          * to get added to the entry since this log is supposed to end
372          * up straight in the file (there's potentially the trusted
373          * writer binary but we're trying to keep the set of actions
374          * it needs to do to the minimum and those timestamps would
375          * in practice be the same anyway). */
376
377         struct timespec ts;
378         clock_gettime(CLOCK_REALTIME, &ts);
379         const time_t tt = ts.tv_sec;
380         const long int real_millisec = ts.tv_nsec / 1000000;
381         clock_gettime(CLOCK_MONOTONIC, &ts);
382 #ifdef HAVE_LOCALTIME_R
383         struct tm tmBuf;
384         struct tm *const ptm = localtime_r(&tt, &tmBuf);
385 #else
386         struct tm *const ptm = localtime(&tt);
387 #endif
388         assert(ptm); // we're in a short lived fork so asserts are fine and make things simple
389
390         int len = strftime(buf, buflen, "%m-%d %H:%M:%S", ptm);
391         assert(len != 0);
392
393         int tmp_len = snprintf(buf + len, buflen - len, ".%03ld", real_millisec);
394         assert(tmp_len > 0);
395         assert(tmp_len < buflen - len);
396         len += tmp_len;
397
398         tmp_len = strftime(buf + len, buflen - len, "%z ", ptm);
399         assert(tmp_len != 0);
400         len += tmp_len;
401
402         tmp_len = snprintf(buf + len, buflen - len, "%5lu.%03ld", ts.tv_sec, ts.tv_nsec / 1000000);
403         assert(tmp_len > 0);
404         assert(tmp_len < buflen - len);
405         len += tmp_len;
406
407         return len;
408 }
409
410 int __critical_log_build_msg(char *buf, size_t buflen, pid_t main_pid, pid_t main_tid, log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
411 {
412         int len = __critical_log_append_timestamp(buf, buflen);
413         const int metadata_len = snprintf(buf + len, buflen - len, " P%5d T%5d B%-6s %c/%-8s: ",
414                 main_pid,
415                 main_tid,
416                 log_name_by_id(log_id),
417                 filter_pri_to_char(prio),
418                 tag ?: "CRITICAL_NO_TAG");
419         assert(metadata_len > 0);
420         if (metadata_len >= buflen - len)
421                 return buflen - 1; // can genuinely happen with an exceedingly large tag
422         len += metadata_len;
423
424         const int content_len = vsnprintf(buf + len, buflen - len, fmt, ap);
425         assert(content_len >= 0); // 0 is legit with format == ""
426         if (content_len >= buflen - len)
427                 return buflen - 1;
428         len += content_len;
429
430         return len;
431 }
432
433 #ifndef UNIT_TEST
434 __attribute__ ((noreturn))
435 #endif
436 void __critical_log_child(pid_t main_pid, pid_t main_tid, log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
437 {
438         char buf[LOG_MAX_PAYLOAD_SIZE + 128]; // extra space for some metadata
439         const int len = __critical_log_build_msg(buf, sizeof buf - 1, main_pid, main_tid, log_id, prio, tag, fmt, ap);
440         buf[len] = '\n';
441         buf[len + 1] = '\0';
442
443         static const char *const path = "/usr/libexec/dlog-log-critical";
444         execl(path, path /* argv[0] convention */, buf, (char *) NULL);
445
446 #ifndef UNIT_TEST
447         /* Compilers are sometimes smart enough to recognize _exit's
448          * noreturn attribute, even if we wrap it with something that
449          * returns. This causes it to behave in unexpected ways, for
450          * example it can blow up the program regardless or it can
451          * optimize some conditionals out (and incorrectly enter them
452          * after the exit call fails to actually exit). This makes it
453          * unsuitable for tests. */
454
455         _exit(1); // not the regular `exit` so as not to trigger any `atexit` handlers prematurely
456 #endif
457 }
458
459 #ifndef UNIT_TEST // contains forks and exits, these don't work well with wrapping (see above)
460 void __critical_log(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
461 {
462         /* Critical log functionality is mostly done in a separate binary
463          * to handle security correctly (else every process would have to
464          * possess the necessary privilege to write onto that file, which
465          * would be opening a fairly nasty can of worms from the security
466          * point of view). Our use of exec() is why a simple thread would
467          * not suffice and we're resorting to a fork.
468          *
469          * The double fork, much like a double barreled 12 gauge shotgun,
470          * is an elegant solution designed to stop a zombie army. We'd be
471          * creating zombie processes if we didn't wait() for the children
472          * we spawn, but we don't really want to do that since it results
473          * in a needless delay. Instead, the writer process is actually a
474          * grandchild, with our direct child exiting immediately just for
475          * us to have something to wait on that is guaranteed not to take
476          * too long. The orphaned grandchild is adopted by init, who will
477          * take care to reap it when it dies. In addition to avoiding the
478          * delay, the client will not have any unexpected children (which
479          * could ruin logic in its own waits).
480          *
481          * Right after forks:
482          * ┌───────┐   ┌─────────┐   ┌─────────────┐   ┌────────┐
483          * │ pid 1 ├──>│ libdlog ├──>│ immediately ├──>│ execs  │
484          * │ init  │   │ client  │   │    exits    │   │ writer │
485          * └───────┘   └─────────┘   └─────────────┘   └────────┘
486          *
487          * Afterwards, libdlog has no children:
488          * ┌───────┐   ┌─────────┐                     ┌────────┐
489          * │ pid 1 ├──>│ libdlog │          ┌─────────>│ writer │
490          * │ init  ├─┐ │ client  │          │          │ binary │
491          * └───────┘ │ └─────────┘          │          └────────┘
492          *           └──────────────────────┘
493          */
494
495         const pid_t main_pid = getpid();
496         const pid_t main_tid = gettid();
497
498         const int temporary_exiter_pid = fork();
499         if (temporary_exiter_pid < 0)
500                 return;
501         if (temporary_exiter_pid != 0) {
502                 waitpid(temporary_exiter_pid, NULL, 0);
503                 return;
504         }
505
506         const int child_pid = fork();
507         if (child_pid < 0)
508                 _exit(1);
509         if (child_pid != 0)
510                 _exit(0);
511
512         __critical_log_child(main_pid, main_tid, log_id, prio, tag, fmt, ap);
513 }
514
515 int __dlog_critical_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
516 {
517         va_list ap;
518
519         va_start(ap, fmt);
520         __critical_log(log_id, prio, tag, fmt, ap);
521         va_end(ap);
522
523         va_start(ap, fmt);
524         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
525         va_end(ap);
526
527         return ret;
528 }
529 #endif
530
531 /**
532  * @brief Print log
533  * @details Print a log line
534  * @param[in] log_id The target buffer ID
535  * @param[in] prio Priority
536  * @param[in] tag tag
537  * @param[in] fmt Format (same as printf)
538  * @param[in] ap Argument list
539  * @return Bytes written, or negative error
540  */
541 int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
542 {
543         int ret = __write_to_log(log_id, prio, tag, fmt, ap, true);
544         __dlog_fatal_assert(prio);
545
546         return ret;
547 }
548
549 /**
550  * @brief Print log
551  * @details Print a log line
552  * @param[in] log_id The target buffer ID
553  * @param[in] prio Priority
554  * @param[in] tag tag
555  * @param[in] fmt Format (same as printf)
556  * @return Bytes written, or negative error
557  */
558 int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
559 {
560         va_list ap;
561
562         va_start(ap, fmt);
563         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
564         va_end(ap);
565
566         return ret;
567 }
568
569 /**
570  * @brief Print log
571  * @details Print a log line
572  * @param[in] log_id The target buffer ID
573  * @param[in] prio Priority
574  * @param[in] tag tag
575  * @param[in] fmt Format (same as printf)
576  * @return Bytes written, or negative error
577  */
578 int __dlog_sec_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
579 {
580         va_list ap;
581
582         va_start(ap, fmt);
583         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
584         va_end(ap);
585
586         return ret;
587 }
588
589 int dlog_vprint(log_priority prio, const char *tag, const char *fmt, va_list ap)
590 {
591         return __write_to_log(LOG_ID_APPS, prio, tag, fmt, ap, false);
592 }
593
594 int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
595 {
596         va_list ap;
597
598         va_start(ap, fmt);
599         int ret = dlog_vprint(prio, tag, fmt, ap);
600         va_end(ap);
601
602         return ret;
603 }
604
605 /**
606  * @brief Finalize DLog
607  * @details Finalizes and deallocates the library
608  * @notes Used directly in tests; brings back the pre-init state
609  */
610 void __dlog_fini(void)
611 {
612         if (destroy_backend) {
613                 destroy_backend();
614                 destroy_backend = NULL;
615         }
616         write_to_log = NULL;
617         is_initialized = false;
618         first = true;
619
620         __log_limiter_destroy();
621         __dynamic_config_destroy();
622 }