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