Use buffer traits over specific IDs
[platform/core/system/dlog.git] / src / libdlog / log.c
1 /*  MIT License
2  *
3  * Copyright (c) 2012-2020 Samsung Electronics Co., Ltd
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy
6  * of this software and associated documentation files (the "Software"), to deal
7  * in the Software without restriction, including without limitation the rights
8  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9  * copies of the Software, and to permit persons to whom the Software is furnished
10  * to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21  * THE SOFTWARE. */
22
23 // C
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28
29 // POSIX
30 #include <pthread.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33
34 // Tizen
35 #include <tizen.h>
36
37 // DLog
38 #include <buffer_traits.h>
39 #include "deduplicate.h"
40 #include <dynamic_config.h>
41 #include <libdlog.h>
42 #include "logconfig.h"
43 #include "loglimiter.h"
44
45 #define DEFAULT_CONFIG_LIMITER false
46 #define DEFAULT_CONFIG_PLOG true
47 #define DEFAULT_CONFIG_DEBUGMODE 0
48 #define DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS 0
49
50
51 /* A pseudo-backend that does nothing. Useful for removing the overhead of dlog
52  * for debugging and measurement purposes, also it simplifies some checking as
53  * the `write_to_log` pointer below never needs to be NULL. Note that features
54  * independent of the backend (such as limiter or dynamic config) are controlled
55  * separately if dlog is to be disabled completely and that minimal overhead is
56  * always present (e.g. building the message via vprintf). */
57 static int write_to_log_null (log_id_t log_id, log_priority prio, const char *tag, const char *msg, struct timespec *tp_mono, int32_t pid, int32_t tid)
58 {
59         return DLOG_ERROR_NONE;
60 }
61
62 /**
63  * @brief Points to a function which writes a log message
64  * @details The function pointed to depends on the backend used
65  * @param[in] log_id ID of the buffer to log to. Belongs to (LOG_ID_INVALID, LOG_ID_MAX) non-inclusive
66  * @param[in] prio Priority of the message.
67  * @param[in] tag The message tag, identifies the sender.
68  * @param[in] msg The contents of the message.
69  * @return Returns the number of bytes written on success and a negative error value on error.
70  * @see __dlog_init_backend
71  */
72 int (*write_to_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg, struct timespec *tp_mono, int32_t pid, int32_t tid) = write_to_log_null;
73 void (*destroy_backend)(void);
74
75 int (*stash_failed_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg) = NULL;
76 #ifndef UNIT_TEST
77 static int stash_critical(log_id_t log_id, log_priority prio, const char *tag, const char *msg);
78 #endif
79
80 pthread_rwlock_t log_limiter_lock = PTHREAD_RWLOCK_INITIALIZER;
81 static pthread_mutex_t log_construction_lock = PTHREAD_MUTEX_INITIALIZER;
82 static bool is_initialized = false;
83
84 extern void __dlog_init_pipe(const struct log_config *conf);
85 extern void __dlog_init_android(const struct log_config *conf);
86 extern void __dlog_init_zero_copy();
87
88 extern void prepend_container_tag_if_in_container(size_t buf_size, char buf[static buf_size], int *len);
89
90 bool limiter;
91 struct limiter_data *limiter_data;
92 static bool dynamic_config;
93 static bool plog[LOG_ID_MAX];
94 static bool plog_default_values[LOG_ID_MAX];
95 static bool enable_secure_logs = true;
96 static bool enable_critical = true;
97
98 static bool should_disable_cancels;
99
100 static int debugmode;
101 static int fatal_assert;
102 static int limiter_apply_to_all_buffers;
103 static _Atomic log_priority priority_filter_level = DLOG_VERBOSE;
104
105 /* Cache pid and tid to avoid up to two syscalls per log. The update function
106  * is registered to happen when new threads are made (including a full fork). */
107 static int32_t cached_pid = 0;
108 _Thread_local int32_t cached_tid = 0;
109
110 static inline int32_t get_cached_pid()
111 {
112         return (cached_pid = cached_pid ?: getpid());
113 }
114
115 static inline int32_t get_cached_tid()
116 {
117         return (cached_tid = cached_tid ?: gettid());
118 }
119
120 static void update_thread_local_ids(void)
121 {
122         cached_pid = 0;
123         cached_tid = 0;
124 }
125
126 /* Here, static_config is the original config from /etc/dlog.conf{,.d} which can be overriden,
127  * but comes back if the override is removed. both_config additionally contains dynamic rules
128  * (by default from /run/dlog/filters.d) which can be changed in the runtime.
129  * The static_config has to be kept separately, so that we can go back to it when dynamic rules change.
130  * Note that most functions only use static_config, since the parameters can't be changed in runtime. */
131 static void __configure_limiter(struct log_config *static_config, struct log_config *both_config)
132 {
133         assert(static_config);
134         if (dynamic_config)
135                 assert(both_config);
136
137         if (!limiter)
138                 return;
139
140         limiter_data = __log_limiter_create(static_config);
141         if (limiter_data && dynamic_config)
142                 __log_limiter_update(limiter_data, both_config);
143         limiter = (bool)limiter_data;
144
145         should_disable_cancels |= limiter; // due to locks
146 }
147
148 static int __configure_backend(struct log_config *config)
149 {
150         assert(config);
151
152         const char *const backend = log_config_claim_backend(config);
153         if (!backend)
154                 return 0;
155
156         if (!strcmp(backend, "pipe")) {
157                 __dlog_init_pipe(config);
158                 should_disable_cancels = true;
159         } else if (!strcmp(backend, "logger"))
160                 __dlog_init_android(config);
161         else if (!strcmp(backend, "zero-copy"))
162                 __dlog_init_zero_copy(config);
163         else if (!strcmp(backend, "null"))
164                 ; // already the default
165         else
166                 return 0;
167
168         return 1;
169 }
170
171 static void __set_plog_default_values(void)
172 {
173         for (size_t i = 0; i < NELEMS(plog); ++i)
174                 plog_default_values[i] = plog[i];
175 }
176
177 static void __initialize_plog(const struct log_config *config)
178 {
179         assert(config);
180
181         /* plog stands for "platform logging", which is why
182          * non-platform (i.e. application) buffers ignore it */
183         const bool plog_default = log_config_get_boolean(config, "plog", DEFAULT_CONFIG_PLOG);
184         for (size_t i = 0; i < NELEMS(plog); ++i)
185                 plog[i] = is_platform_buffer(i) ? plog_default : true;
186
187         __set_plog_default_values();
188 }
189
190 static void __configure_parameters(struct log_config *static_config, struct log_config *both_config)
191 {
192         assert(static_config);
193         assert(both_config);
194
195         __initialize_plog(static_config);
196         __update_plog(static_config);
197         /* Like in __configure_limiter, we also check the dynamic rules. However, we make sure to
198      * set the default values to the ones generated by the static rules first. */
199         __set_plog_default_values();
200         __update_plog(both_config);
201
202         enable_secure_logs = log_config_get_boolean(both_config, "enable_secure_logs", enable_secure_logs);
203         enable_critical = log_config_get_boolean(both_config, "enable_critical", enable_critical);
204         debugmode = log_config_get_int(both_config, "debugmode", DEFAULT_CONFIG_DEBUGMODE);
205         fatal_assert = access(DEBUGMODE_FILE, F_OK) != -1;
206         limiter = log_config_get_boolean(both_config, "limiter", DEFAULT_CONFIG_LIMITER);
207         limiter_apply_to_all_buffers = log_config_get_int(both_config,
208                                                                         "limiter_apply_to_all_buffers",
209                                                                         DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS);
210
211         stash_failed_log = NULL;
212         const char *stash_failed_log_method = log_config_get(both_config, "stash_failed_log_method");
213         if (stash_failed_log_method) {
214 #ifndef UNIT_TEST
215                 if (strcmp(stash_failed_log_method, "critical") == 0)
216                         stash_failed_log = stash_critical;
217 #endif
218         }
219 }
220
221 void __update_plog(const struct log_config *conf)
222 {
223         assert(conf);
224
225         for (size_t i = 0; i < NELEMS(plog); ++i) {
226                 char key[MAX_CONF_KEY_LEN];
227                 const int r = snprintf(key, sizeof key, "enable_%s", log_name_by_id((log_id_t)i));
228                 if (r < 0)
229                         continue;
230                 plog[i] = log_config_get_boolean(conf, key, plog_default_values[i]);
231         }
232 }
233
234 /**
235  * @brief Configure the library
236  * @details Reads relevant config values
237  * @remarks This is more or less a constructor, but there are some obstacles
238  *          to using it as such (i.e. with attribute constructor):
239  *
240  *  - some important pieces of the system link to dlog, they start very early
241  *    such that dlog can't properly initialize (which lasts for program lifetime)
242  *    but don't actually log anything until later on and would be fine under lazy
243  *    initialisation. The way to do it "properly" would be to expose this function
244  *    into the API so that people can manually call it when they're ready, but
245  *    one of the design goals of the current API is that it requires absolutely no
246  *    other calls than `dlog_print`. Changing it would require somebody with a
247  *    bird's eye view of the system to produce a design so I wouldn't count on it.
248  *
249  *  - the constructor would need to have as high of a priority as possible (so as
250  *    to minimize the risk of another library's constructor using uninitialized data)
251  *    but at the same time others might want some room to wrap functions before
252  *    dlog uses them (think mprobe/mcheck). This would also require a design pass.
253  */
254 #ifndef UNIT_TEST
255 static
256 #endif
257 bool __configure(void)
258 {
259         __attribute__((cleanup(log_config_free))) struct log_config static_config = {};
260         __attribute__((cleanup(log_config_free))) struct log_config both_config = {};
261
262         if (log_config_read(&static_config) < 0)
263                 return false;
264         log_config_copy(&both_config, &static_config);
265
266         dynamic_config = __dynamic_config_create(&both_config);
267
268         __configure_parameters(&static_config, &both_config);
269
270         if (!__configure_backend(&both_config)) {
271                 __dynamic_config_destroy();
272                 dynamic_config = false;
273                 return false;
274         }
275
276         __configure_deduplicate(&both_config);
277         __configure_limiter(&static_config, &both_config);
278
279         /* The fork handler also runs when a new thread is made (not just
280          * when the whole process forks), so we can cache both pid and tid. */
281         pthread_atfork(NULL, NULL, update_thread_local_ids);
282
283         return true;
284 }
285
286 static void __attribute__((constructor(101))) __install_pipe_handler(void)
287 {
288         /* We mask SIGPIPE signal because most applications do not install their
289          * own SIGPIPE handler. Default behaviour in SIGPIPE case is to abort the
290          * process. SIGPIPE occurs when e.g. dlog daemon closes read pipe endpoint.
291          *
292          * We do this in the library constructor (at maximum priority) and not
293          * during regular (lazy) initialisation so as to prevent overwriting the
294          * program's actual signal handler, if it has one.
295          *
296          * In theory this is not required for the Android logger backend; however,
297          * this early we don't yet know the backend and also it is good to behave
298          * consistently in this regard anyway.
299          *
300          * We don't revert this in a destructor because Unix signals are bonkers
301          * and we have no way to do this cleanly. Most libdlog users don't use
302          * runtime linking so this would mostly done at program exit either way. */
303         signal(SIGPIPE, SIG_IGN);
304 }
305
306 static void __attribute__((constructor(102))) __set_output_buffering(void)
307 {
308         /* If stdout and/or stderr is redirected to dlog (service, driver)
309          * it is best if we buffer lines, otherwise the following can happen:
310          *  - no buffering: service/driver recives every single byte (precisely
311          *    every single write*(2) call), causing it to either buffer the data
312          *    anyway (service), or print logs at random places (driver)
313          *  - full buffering: service/driver receives several hundred lines,
314          *    which results in one giant entry being added (driver) or long delays
315          *    before logs appear (service) */
316         if (getenv(DLOG_ENV_STDOUT_LINE_BUFFERED))
317                 setlinebuf(stdout);
318
319         if (getenv(DLOG_ENV_STDERR_LINE_BUFFERED))
320                 setlinebuf(stderr);
321 }
322
323 static bool first = true;
324 static bool initialize(void)
325 {
326         if (is_initialized)
327                 return true;
328
329         /* The mutex acts as a barrier, but otherwise the C language's
330          * machine abstraction is single-threaded. This means that the
331          * compiler is free to rearrange calls inside the mutex according
332          * to the as-if rule because it doesn't care if another thread can
333          * access it in parallel. In particular, `is_initialized = true`
334          * directly after `__configure()` could be rearranged to go in
335          * front of it because it is not touched inside that function
336          * if the compiler thinks it helps somehow (not unlikely: since
337          * it is checked before the mutex, it is very probable for it to
338          * still be in the CPU register or something like that). On top
339          * of that, some architectures (in particular, armv7l) don't have
340          * strict memory guarantees and can reorder actual memory stores
341          * on their own, even if the compiler didn't do anything fancy
342          * when creating machine code. For more info about the issue,
343          * see https://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
344          *
345          * Ultimately this means that there needs to be some sort of
346          * barrier between `__configure` and `is_initialized = true`,
347          * and the simplest way to achieve that is to just wait until
348          * the second entry into the mutex. */
349
350         bool ret;
351         pthread_mutex_lock(&log_construction_lock);
352                 if (first)
353                         first = !__configure();
354                 else
355                         is_initialized = true;
356                 ret = !first;
357         pthread_mutex_unlock(&log_construction_lock);
358         return ret;
359 }
360
361 /**
362  * @brief Fatal assertion
363  * @details Conditionally crash the sucka who sent the log
364  * @param[in] prio Priority of the log
365  */
366 static void __dlog_fatal_assert(int prio)
367 {
368         assert(!fatal_assert || (prio != DLOG_FATAL));
369 }
370
371 /**
372  * @brief Check log validity
373  * @details Checks whether the log is valid and eligible for printing
374  * @param[in] log_id The target buffer ID
375  * @param[in] prio The log's priority
376  * @param[in] tag The log's tag
377  * @return DLOG_ERROR_NONE on success, else an error code.
378  * @retval DLOG_ERROR_INVALID_PARAMETER Invalid parameter
379  */
380 static int dlog_check_validity(log_id_t log_id, int prio, const char *tag)
381 {
382         (void) prio;
383         if (!tag)
384                 return DLOG_ERROR_INVALID_PARAMETER;
385
386         if (!is_buffer_valid(log_id))
387                 return DLOG_ERROR_INVALID_PARAMETER;
388
389         return DLOG_ERROR_NONE;
390 }
391
392 /**
393  * @brief Check log against limiter rules
394  * @details Checks whether the log passes current limiter rules
395  * @param[in] log_id The target buffer ID
396  * @param[in] prio The log's priority
397  * @param[in] tag The log's tag
398  * @return DLOG_ERROR_NONE on success, else an error code.
399  * @retval DLOG_ERROR_NOT_PERMITTED Not permitted
400  */
401 static int dlog_check_limiter(log_id_t log_id, int prio, const char *tag)
402 {
403         if (!debugmode && prio <= DLOG_DEBUG)
404                 return DLOG_ERROR_NOT_PERMITTED;
405
406         if (dynamic_config)
407                 __dynamic_config_update(limiter_data);
408
409         if (limiter) {
410                 struct pass_log_result should_log = { .decision = DECISION_DENIED };
411
412                 /* Since the only `wrlock` is done by the dynamic config, we can avoid
413                  * the `rdlock` entirely if the config is static. This sounds unsafe
414                  * but lets us save an entire syscall, which is a lot (both comparatively
415                  * and because it compounds). */
416                 if (!dynamic_config || !pthread_rwlock_rdlock(&log_limiter_lock)) {
417                         should_log = __log_limiter_pass_log_pid(limiter_data, tag, prio, get_cached_pid());
418                         if (dynamic_config)
419                                 pthread_rwlock_unlock(&log_limiter_lock);
420                 }
421
422                 switch (should_log.decision) {
423                         case DECISION_DENIED:
424                                 return DLOG_ERROR_NOT_PERMITTED;
425
426                         case DECISION_TAG_LIMIT_EXCEEDED_MESSAGE:
427                         case DECISION_PID_LIMIT_EXCEEDED_MESSAGE: {
428                                 struct timespec tp;
429                                 int result = clock_gettime(CLOCK_MONOTONIC, &tp);
430                                 if (result < 0)
431                                         return DLOG_ERROR_NOT_PERMITTED;
432                                 char buf[100] = {};
433                                 snprintf(buf, sizeof(buf),
434                                                 "Your log has been blocked due to per-%s limit of %d logs per %d seconds.",
435                                                 should_log.decision == DECISION_TAG_LIMIT_EXCEEDED_MESSAGE ? "tag" : "PID",
436                                                 should_log.logs_per_period, should_log.period_s);
437                                 write_to_log(log_id, prio, tag, buf, &tp, get_cached_pid(), get_cached_tid());
438                                 return DLOG_ERROR_NOT_PERMITTED;
439                         }
440
441                         case DECISION_ALLOWED:
442                                 break;
443                 }
444         }
445
446         /* This can change due to __dynamic_config_update(), but is atomic and its
447          * value implies nothing else so does not need to be under a lock. */
448         if (!plog[log_id])
449                 return DLOG_ERROR_NOT_PERMITTED;
450
451         return DLOG_ERROR_NONE;
452 }
453
454 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)
455 {
456         if ((check_should_log || limiter_apply_to_all_buffers) && (dlog_check_limiter(log_id, prio, tag) < 0))
457                 return DLOG_ERROR_NONE;
458
459         char buf[LOG_MAX_PAYLOAD_SIZE];
460         int len = vsnprintf(buf, sizeof buf, fmt, ap);
461         if (len < 0)
462                 return DLOG_ERROR_NONE;
463         else if (len >= sizeof buf)
464                 len = sizeof buf - 1;
465
466         // Temporary workaround, see temporary.c
467         prepend_container_tag_if_in_container(sizeof buf, buf, &len);
468
469         struct timespec tp;
470         int r;
471         if (deduplicate_func && !clock_gettime(CLOCK_MONOTONIC, &tp)) {
472                 dlog_deduplicate_e ret = deduplicate_func(buf, len, &tp);
473                 if (ret == DLOG_DEDUPLICATE)
474                         return DLOG_ERROR_NONE;
475                 else if (ret == DLOG_DO_NOT_DEDUPLICATE_BUT_WARN)
476                         deduplicate_warn(buf, sizeof buf, len);
477                 r = write_to_log(log_id, prio, tag, buf, &tp, get_cached_pid(), get_cached_tid());
478         } else
479                 r = write_to_log(log_id, prio, tag, buf, NULL, get_cached_pid(), get_cached_tid());
480
481         if (r < 0 && stash_failed_log)
482                 r = stash_failed_log(log_id, prio, tag, buf);
483
484         return r;
485 }
486
487 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)
488 {
489         int ret = dlog_check_validity(log_id, prio, tag);
490         if (ret < 0)
491                 return ret;
492
493         if (check_should_log && prio < priority_filter_level)
494                 return DLOG_ERROR_NONE;
495
496         /* Threads can be cancelled before they give up a lock.
497          * Therefore cancellation is temporarily disabled as
498          * long as the current set of features uses a lock.
499          *
500          * This solution is comparatively simple and cheap.
501          * The other solutions (cleanup handlers, robust mutexes)
502          * would be much more complicated and also inflict larger
503          * runtime costs. The downside of disabling cancellation
504          * is not a problem in our case because it is temporary
505          * and very brief so we don't keep an obsolete thread
506          * for much longer than we otherwise would. */
507         int old_cancel_state;
508         if (should_disable_cancels)
509                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancel_state);
510
511         if (!initialize())
512                 // TODO: We could consider stashing the failed log here
513                 ret = DLOG_ERROR_NOT_PERMITTED;
514         else if (secure_log && !enable_secure_logs)
515                 ret = 0;
516         else
517                 ret = __write_to_log_critical_section(log_id, prio, tag, fmt, ap, check_should_log);
518
519         if (should_disable_cancels)
520                 pthread_setcancelstate(old_cancel_state, NULL);
521
522         return ret;
523 }
524
525 int __critical_log_append_timestamp(char *buf, size_t buflen)
526 {
527         /* NB: the timestamp may slightly differ from the one that gets
528          * added onto the copy that goes into the regular buffer, and
529          * timestamp acquisition is duplicated. This would ideally be
530          * solved, but timestamps are currently added fairly deep in
531          * backend-specific functions so for now this will have to do.
532          * Also, since we're the sender, there is just this one set of
533          * timestamps, i.e. the send timestamp! The usual alternative
534          * set of receive timestamps will never have the opportunity
535          * to get added to the entry since this log is supposed to end
536          * up straight in the file (there's potentially the trusted
537          * writer binary but we're trying to keep the set of actions
538          * it needs to do to the minimum and those timestamps would
539          * in practice be the same anyway). */
540
541         struct timespec ts;
542         clock_gettime(CLOCK_REALTIME, &ts);
543         const time_t tt = ts.tv_sec;
544         const long int real_millisec = ts.tv_nsec / 1000000;
545         clock_gettime(CLOCK_MONOTONIC, &ts);
546         struct tm tmBuf;
547         struct tm *const ptm = localtime_r(&tt, &tmBuf);
548         assert(ptm); // we're in a short lived fork so asserts are fine and make things simple
549
550         int len = strftime(buf, buflen, "%m-%d %H:%M:%S", ptm);
551         assert(len != 0);
552
553         int tmp_len = snprintf(buf + len, buflen - len, ".%03ld", real_millisec);
554         assert(tmp_len > 0);
555         assert(tmp_len < buflen - len);
556         len += tmp_len;
557
558         tmp_len = strftime(buf + len, buflen - len, "%z ", ptm);
559         assert(tmp_len != 0);
560         len += tmp_len;
561
562         tmp_len = snprintf(buf + len, buflen - len, "%5lu.%03ld", ts.tv_sec, ts.tv_nsec / 1000000);
563         assert(tmp_len > 0);
564         assert(tmp_len < buflen - len);
565         len += tmp_len;
566
567         return len;
568 }
569
570 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)
571 {
572         int len = __critical_log_append_timestamp(buf, buflen);
573         const int metadata_len = snprintf(buf + len, buflen - len, " P%5d T%5d B%-6s %c/%-8s: ",
574                 main_pid,
575                 main_tid,
576                 log_name_by_id(log_id),
577                 filter_pri_to_char(prio),
578                 tag ?: "CRITICAL_NO_TAG");
579         assert(metadata_len > 0);
580         if (metadata_len >= buflen - len)
581                 return buflen - 1; // can genuinely happen with an exceedingly large tag
582         len += metadata_len;
583
584         const int content_len = vsnprintf(buf + len, buflen - len, fmt, ap);
585         assert(content_len >= 0); // 0 is legit with format == ""
586         if (content_len >= buflen - len)
587                 return buflen - 1;
588         len += content_len;
589
590         return len;
591 }
592
593 #ifndef UNIT_TEST
594 __attribute__ ((noreturn))
595 #endif
596 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)
597 {
598         char buf[LOG_MAX_PAYLOAD_SIZE + 128]; // extra space for some metadata
599         const int len = __critical_log_build_msg(buf, sizeof buf - 1, main_pid, main_tid, log_id, prio, tag, fmt, ap);
600         buf[len] = '\n';
601         buf[len + 1] = '\0';
602
603         static const char *const path = "/usr/libexec/dlog-log-critical";
604         execl(path, path /* argv[0] convention */, buf, (char *) NULL);
605
606 #ifndef UNIT_TEST
607         /* Compilers are sometimes smart enough to recognize _exit's
608          * noreturn attribute, even if we wrap it with something that
609          * returns. This causes it to behave in unexpected ways, for
610          * example it can blow up the program regardless or it can
611          * optimize some conditionals out (and incorrectly enter them
612          * after the exit call fails to actually exit). This makes it
613          * unsuitable for tests. */
614
615         _exit(1); // not the regular `exit` so as not to trigger any `atexit` handlers prematurely
616 #endif
617 }
618
619 #ifndef UNIT_TEST // contains forks and exits, these don't work well with wrapping (see above)
620 void __critical_log(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
621 {
622         /* Critical log functionality is mostly done in a separate binary
623          * to handle security correctly (else every process would have to
624          * possess the necessary privilege to write onto that file, which
625          * would be opening a fairly nasty can of worms from the security
626          * point of view). Our use of exec() is why a simple thread would
627          * not suffice and we're resorting to a fork.
628          *
629          * The double fork, much like a double barreled 12 gauge shotgun,
630          * is an elegant solution designed to stop a zombie army. We'd be
631          * creating zombie processes if we didn't wait() for the children
632          * we spawn, but we don't really want to do that since it results
633          * in a needless delay. Instead, the writer process is actually a
634          * grandchild, with our direct child exiting immediately just for
635          * us to have something to wait on that is guaranteed not to take
636          * too long. The orphaned grandchild is adopted by init, who will
637          * take care to reap it when it dies. In addition to avoiding the
638          * delay, the client will not have any unexpected children (which
639          * could ruin logic in its own waits).
640          *
641          * Right after forks:
642          * ┌───────┐   ┌─────────┐   ┌─────────────┐   ┌────────┐
643          * │ pid 1 ├──>│ libdlog ├──>│ immediately ├──>│ execs  │
644          * │ init  │   │ client  │   │    exits    │   │ writer │
645          * └───────┘   └─────────┘   └─────────────┘   └────────┘
646          *
647          * Afterwards, libdlog has no children:
648          * ┌───────┐   ┌─────────┐                     ┌────────┐
649          * │ pid 1 ├──>│ libdlog │          ┌─────────>│ writer │
650          * │ init  ├─┐ │ client  │          │          │ binary │
651          * └───────┘ │ └─────────┘          │          └────────┘
652          *           └──────────────────────┘
653          */
654
655         initialize();
656
657         if (!enable_critical)
658                 return;
659
660         const pid_t main_pid = getpid();
661         const pid_t main_tid = gettid();
662
663         const int temporary_exiter_pid = fork();
664         if (temporary_exiter_pid < 0)
665                 return;
666         if (temporary_exiter_pid != 0) {
667                 waitpid(temporary_exiter_pid, NULL, 0);
668                 return;
669         }
670
671         const int child_pid = fork();
672         if (child_pid < 0)
673                 _exit(1);
674         if (child_pid != 0)
675                 _exit(0);
676
677         __critical_log_child(main_pid, main_tid, log_id, prio, tag, fmt, ap);
678 }
679
680 static void stash_critical_inner(log_id_t log_id, log_priority prio, const char *tag, const char *fmt, ...)
681 {
682         va_list ap;
683
684         va_start(ap, fmt);
685         __critical_log(log_id, prio, tag, fmt, ap);
686         va_end(ap);
687 }
688
689 static int stash_critical(log_id_t log_id, log_priority prio, const char *tag, const char *msg)
690 {
691         stash_critical_inner(log_id, prio, tag, "FAILED TO LOG: %s", msg);
692         return 0;
693 }
694
695 EXPORT_API int __dlog_critical_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
696 {
697         va_list ap;
698
699         va_start(ap, fmt);
700         __critical_log(log_id, prio, tag, fmt, ap);
701         va_end(ap);
702
703         va_start(ap, fmt);
704         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
705         va_end(ap);
706
707         return ret;
708 }
709 #endif
710
711 EXPORT_API int dlog_set_minimum_priority(int priority)
712 {
713         if (priority < DLOG_DEFAULT || priority > DLOG_PRIO_MAX)
714                 return DLOG_ERROR_INVALID_PARAMETER;
715
716         priority_filter_level = priority;
717         return DLOG_ERROR_NONE;
718 }
719
720 /**
721  * @brief Print log
722  * @details Print a log line
723  * @param[in] log_id The target buffer ID
724  * @param[in] prio Priority
725  * @param[in] tag tag
726  * @param[in] fmt Format (same as printf)
727  * @param[in] ap Argument list
728  * @return Bytes written, or negative error
729  */
730 EXPORT_API int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
731 {
732         int ret = __write_to_log(log_id, prio, tag, fmt, ap, true, false);
733         __dlog_fatal_assert(prio);
734
735         return ret;
736 }
737
738 /**
739  * @brief Print log
740  * @details Print a log line
741  * @param[in] log_id The target buffer ID
742  * @param[in] prio Priority
743  * @param[in] tag tag
744  * @param[in] fmt Format (same as printf)
745  * @return Bytes written, or negative error
746  */
747 EXPORT_API int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
748 {
749         va_list ap;
750
751         va_start(ap, fmt);
752         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
753         va_end(ap);
754
755         return ret;
756 }
757
758 /**
759  * @brief Print log
760  * @details Print a log line
761  * @param[in] log_id The target buffer ID
762  * @param[in] prio Priority
763  * @param[in] tag tag
764  * @param[in] fmt Format (same as printf)
765  * @return Bytes written, or negative error
766  */
767 EXPORT_API int __dlog_sec_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
768 {
769         if (!enable_secure_logs)
770                 return 0;
771
772         va_list ap;
773
774         va_start(ap, fmt);
775         int ret = __write_to_log(log_id, prio, tag, fmt, ap, true, true);
776         __dlog_fatal_assert(prio);
777         va_end(ap);
778
779         return ret;
780 }
781
782 EXPORT_API int dlog_vprint(log_priority prio, const char *tag, const char *fmt, va_list ap)
783 {
784         return __write_to_log(LOG_ID_APPS, prio, tag, fmt, ap, false, false);
785 }
786
787 EXPORT_API int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
788 {
789         va_list ap;
790
791         va_start(ap, fmt);
792         int ret = dlog_vprint(prio, tag, fmt, ap);
793         va_end(ap);
794
795         return ret;
796 }
797
798 /**
799  * @brief Finalize DLog
800  * @details Finalizes and deallocates the library
801  * @notes Used directly in tests; brings back the pre-init state
802  */
803 void __dlog_fini(void)
804 {
805         if (destroy_backend) {
806                 destroy_backend();
807                 destroy_backend = NULL;
808         }
809         write_to_log = write_to_log_null;
810         stash_failed_log = NULL;
811         is_initialized = false;
812         first = true;
813
814         enable_secure_logs = true;
815         enable_critical = false;
816         __deduplicate_destroy();
817         __log_limiter_destroy(limiter_data);
818         limiter = false;
819         __dynamic_config_destroy();
820         should_disable_cancels = false;
821 }