Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : // glibc declares memrchr(), renameat2() and the thread-name calls only under
26 : // this.
27 : #ifndef _GNU_SOURCE
28 : #define _GNU_SOURCE
29 : #endif
30 :
31 : #include <chashmap.h>
32 : #include <clogger.h>
33 : #include <common.h>
34 : #include <cthreadcomm.h>
35 : #include <ctype.h>
36 : #include <cvector.h>
37 : #include <dirent.h>
38 : #include <errno.h>
39 : #include <fcntl.h>
40 : #include <internal/catfork.h>
41 : #include <internal/cgrowbuf.h>
42 : #include <internal/chashinsert.h>
43 : #include <internal/clogderive.h>
44 : #include <internal/cpintable.h>
45 : #include <internal/cqueueowner.h>
46 : #include <internal/test_helpers/clogger.h>
47 : #include <internal/test_helpers/common.h>
48 : #include <limits.h>
49 : #include <poll.h>
50 : #include <sched.h>
51 : #include <signal.h>
52 : #include <stdarg.h>
53 : #include <stdatomic.h>
54 : #include <stdint.h>
55 : #include <stdio.h>
56 : #include <stdlib.h>
57 : #include <string.h>
58 : #include <sys/ioctl.h>
59 : #include <sys/socket.h>
60 : #include <sys/stat.h>
61 : #include <sys/syscall.h>
62 : #include <sys/time.h>
63 : #if defined(__linux__)
64 : #include <sys/prctl.h>
65 : #endif
66 : #if defined(__FreeBSD__) || defined(__OpenBSD__)
67 : #include <pthread_np.h>
68 : #endif
69 : #include <internal/crandom.h>
70 : #include <internal/csock.h>
71 : #include <internal/ctlsmodel.h>
72 : #include <time.h>
73 : #include <unistd.h>
74 : #include <zlib.h>
75 :
76 : // musl has no backtrace(), so a record there carries the "backtrace
77 : // unavailable" marker instead of frames.
78 : #if defined(__GLIBC__) || defined(__APPLE__) || defined(__FreeBSD__) || \
79 : defined(__OpenBSD__)
80 : #include <execinfo.h>
81 : #define CLOG_HAS_BACKTRACE 1
82 : #else
83 : #define CLOG_HAS_BACKTRACE 0
84 : #endif
85 :
86 : // The first size of a record buffer, and the most one record may grow to.
87 : #define CLOG_BUF_INITIAL 4096U
88 : #define CLOG_BUF_LIMIT (16U * 1024U * 1024U)
89 :
90 : // How many frames a backtrace captures at most.
91 : #define CLOG_BACKTRACE_DEPTH 64
92 :
93 : // A rotated name is "<base>.YYYYMMDDHHMMSS", optionally followed by "_" and a
94 : // collision sequence number of at least 4 digits and at most
95 : // CLOG_ROTATION_SEQ_MAX_DIGITS. CLOG_ROTATION_EXTRA is the room that suffix
96 : // needs.
97 : #define CLOG_ROTATION_FMT ".%Y%m%d%H%M%S"
98 : #define CLOG_ROTATION_FMT_LEN 15
99 : #define CLOG_ROTATION_SEQ_MAX_DIGITS 9
100 : #define CLOG_ROTATION_SEQ_LIMIT 999999999UL
101 : #define CLOG_ROTATION_EXTRA (1 + CLOG_ROTATION_SEQ_MAX_DIGITS)
102 : #define CLOG_ROTATION_STAMP_DIGITS 14
103 :
104 : // A rotated-looking name whose stamp is more than this above both the clock and
105 : // the newest name the target made isn't one of its generations (see
106 : // clog_gen_filter_init()). Real clock steps are far smaller than 30 days.
107 : #define CLOG_ROTATION_FUTURE_TOLERANCE_SECS ((int64_t)30 * 24 * 60 * 60)
108 :
109 : // A rotation creates the next live file under "<base>.tmp" plus 11 hex digits
110 : // before it renames it onto the live name. The name is as long as a rotated
111 : // name, and it never parses as one, because there a digit follows "<base>.".
112 : #define CLOG_ROTATION_TMP_TAG ".tmp"
113 : #define CLOG_ROTATION_TMP_HEX_DIGITS 11
114 : #define CLOG_ROTATION_TMP_LEN \
115 : (sizeof(CLOG_ROTATION_TMP_TAG) - 1 + CLOG_ROTATION_TMP_HEX_DIGITS)
116 : _Static_assert(CLOG_ROTATION_TMP_LEN == CLOG_ROTATION_FMT_LEN,
117 : "the private name of a new live file must be no longer than a "
118 : "rotated name");
119 :
120 : // At most this many WARN records about entries that look like generations but
121 : // aren't go out per target in each window of this many seconds.
122 : #define CLOG_IGNORED_NOTE_BURST 8U
123 : #define CLOG_IGNORED_NOTE_WINDOW_SECS ((time_t)60)
124 :
125 : // After a failed rotation, later attempts wait this long instead of paying a
126 : // rename() and an open() on every write while the failure lasts.
127 : #define CLOG_ROTATE_RETRY_BACKOFF_SECS ((time_t)1)
128 :
129 : #ifdef RUNNING_UNIT_TESTS
130 :
131 : // Offset that clog__test_set_wall_clock_offset() adds to the wall clock of a
132 : // test build.
133 : static _Atomic int64_t clog_test_wall_offset = 0;
134 :
135 : // Sets the offset, in seconds, that a test build adds to rotation's wall clock,
136 : // so a test can step the clock forward and back.
137 10 : void clog__test_set_wall_clock_offset(int64_t secs) {
138 10 : atomic_store(&clog_test_wall_offset, secs);
139 10 : }
140 :
141 : // Gives the wall clock that rotation reads (the stamp of a rotated name, the
142 : // start of a time interval, the retry backoff). It's a function of its own so a
143 : // test build can add an offset and step the clock without touching the system
144 : // clock.
145 8102 : static time_t clog_wall_now(void) {
146 8102 : return (time_t)((int64_t)time(NULL) + atomic_load(&clog_test_wall_offset));
147 : }
148 :
149 : // How many of the next rotate() calls fail before they touch the directory.
150 : static _Atomic unsigned int clog_test_rotate_failures = 0;
151 :
152 : // Makes the next count rotate() calls fail before they touch the directory, so
153 : // a test can check the retry backoff.
154 2 : void clog__test_force_rotate_failures(unsigned int count) {
155 2 : atomic_store(&clog_test_rotate_failures, count);
156 2 : }
157 :
158 : // Takes one forced rotation failure, for rotate() in a test build. True when
159 : // one was left.
160 2033 : static bool clog_test_consume_rotate_failure(void) {
161 2033 : unsigned int n = atomic_load(&clog_test_rotate_failures);
162 2033 : while (n > 0) {
163 1 : if (atomic_compare_exchange_weak(&clog_test_rotate_failures, &n, n - 1))
164 : return true;
165 : }
166 : return false;
167 : }
168 : #else
169 :
170 : // Stubs of a non-test build, so rotate() and the rotation checks need no
171 : // #ifdef: The clock is time(NULL) and no rotation failure is forced.
172 : static inline time_t clog_wall_now(void) { return time(NULL); }
173 : static inline bool clog_test_consume_rotate_failure(void) { return false; }
174 : #endif
175 :
176 : // Level names, indexed by clog_level. The assert ties the size to the enum, so
177 : // a new level that isn't added here fails to compile.
178 : static const char *const LEVEL_STR[] = {"TRACE", "DEBUG", "INFO", "WARN",
179 : "ERROR", "ALERT", "FATAL", "OFF"};
180 : _Static_assert(sizeof(LEVEL_STR) / sizeof(LEVEL_STR[0]) == CLOG_OFF + 1,
181 : "LEVEL_STR must have exactly one entry per clog_level value");
182 :
183 : // Keys clog_set_field() refuses: The fixed keys every record carries. A user
184 : // field with one of them would give a duplicate key in JSON and logfmt, and a
185 : // duplicate SD-PARAM-NAME in syslog, which RFC 5424 forbids.
186 : static const char *const RESERVED_FIELD_KEYS[] = {
187 : "ts", "level", "proc", "src", "func", "msg", "bt", "bt_error"};
188 : #define RESERVED_FIELD_KEYS_COUNT \
189 : (sizeof(RESERVED_FIELD_KEYS) / sizeof(RESERVED_FIELD_KEYS[0]))
190 :
191 : // Tells whether key is one of RESERVED_FIELD_KEYS, so clog_set_field() can
192 : // refuse a key every record already carries.
193 1238 : static bool is_reserved_field_key(const char *key) {
194 11106 : for (size_t i = 0; i < RESERVED_FIELD_KEYS_COUNT; i++)
195 9876 : if (strcmp(key, RESERVED_FIELD_KEYS[i]) == 0) return true;
196 : return false;
197 : }
198 :
199 : // RFC 5424 severity of each clog_level: TRACE and DEBUG are debug (7), INFO is
200 : // informational, WARN warning, ERROR error, ALERT alert and FATAL emergency.
201 : // The last entry is for CLOG_OFF, which is never a message level.
202 : static const int SYSLOG_SEVERITY[] = {
203 : 7, 7, 6, 4, 3, 1, 0, 7,
204 : };
205 : _Static_assert(
206 : sizeof(SYSLOG_SEVERITY) / sizeof(SYSLOG_SEVERITY[0]) == CLOG_OFF + 1,
207 : "SYSLOG_SEVERITY must have exactly one entry per clog_level value");
208 :
209 : // One gzip compression of a rotated file. rotate() queues it for the target's
210 : // compressor thread. src and dst ("<src>.gz") are relative to the target's
211 : // dir_fd. Only the running job (clog_shared.compress_running) protects its
212 : // generation from prune_rotated(); a queued job doesn't, and if its source gets
213 : // pruned the compression does nothing. The queue is guarded by the target's
214 : // mutex.
215 : typedef struct clog_compress_job {
216 : struct clog_compress_job *next;
217 : char *src;
218 : char *dst;
219 : // The owner of the live file when the job was queued; src is compressed only
220 : // when it's owned by this user or by the effective user.
221 : uid_t live_uid;
222 : // Identity of a temporary output a failed compression couldn't remove.
223 : dev_t tmp_dev;
224 : ino_t tmp_ino;
225 : } clog_compress_job;
226 :
227 : // A growable byte buffer for building records.
228 : typedef struct {
229 : char *data;
230 : size_t len;
231 : size_t cap;
232 : // Hard growth ceiling. CLOG_BUF_LIMIT for every buffer except the async
233 : // batch, which shared_async_init() raises to the configured
234 : // flush_buffer_size.
235 : size_t cap_limit;
236 : const ccol_memmgmt_procs *m_procs;
237 : // Set by buf_ensure() when the allocator itself failed, as opposed to hitting
238 : // cap_limit. clog_build_record() resets and reads it to pick the right
239 : // fallback message.
240 : bool oom;
241 : } clog_buf;
242 :
243 : // Values of clog_shared.async_partial_record. A record can span several lines
244 : // (a logfmt backtrace), so a short write can stop inside a line or exactly at a
245 : // newline inside the record. Only the first leaves a line open on disk, so the
246 : // two need different repairs. CLOG_OWED_REPAIR is a separate bit: The target
247 : // owes its output a newline or a loss marker.
248 : enum {
249 : CLOG_SPLIT_NONE = 0,
250 : CLOG_SPLIT_MID_LINE = 1,
251 : CLOG_SPLIT_AT_LINE = 2,
252 : CLOG_SPLIT_MASK = 3,
253 : CLOG_OWED_REPAIR = 4,
254 : };
255 :
256 : // The backing store that a root logger and all loggers derived from it share:
257 : // the fd, the rotation state, the async machinery and the mutex. It's reference
258 : // counted, and an owned fd is closed when the count reaches zero. mutex guards
259 : // almost everything here; the fields read without it are noted.
260 : typedef struct clog_shared {
261 : int fd;
262 : bool owns_fd;
263 : // The low bits (CLOG_SPLIT_MASK) say whether the leading bytes of async_buf
264 : // continue a record whose first half a short write already put on disk. While
265 : // they're set no rotation happens and no other record goes to the fd, so the
266 : // two halves stay together. CLOG_OWED_REPAIR marks a debt (see owe_newline).
267 : // It sits next to fd because every write path tests both.
268 : unsigned char async_partial_record;
269 : // fd's clog_sink_kind, from fstat() at open and after each rotation. True
270 : // sink_per_record means a message socket: One write per record, never a
271 : // batch.
272 : unsigned char sink_kind;
273 : bool sink_per_record;
274 : // NULL for an fd-based logger.
275 : char *file_path;
276 :
277 : bool rotation_enabled;
278 : clog_rotation_cfg rotation;
279 : off_t bytes_written;
280 : time_t last_rotation;
281 : // Earliest time a rotation may be tried again after a failed one; 0 for no
282 : // backoff.
283 : time_t rotate_retry_after;
284 : // The job the compressor thread runs right now, or NULL.
285 : clog_compress_job *compress_running;
286 :
287 : ccol__mutex mutex;
288 : int ref_count;
289 : clog_format format;
290 : // Syslog facility, and the hostname and APP-NAME cached at creation.
291 : clog_syslog_facility syslog_facility;
292 : char syslog_hostname[256];
293 : char syslog_appname[49];
294 : // Heap copy of the caller's procs; NULL for the default allocator.
295 : ccol_memmgmt_procs *m_procs;
296 :
297 : // Async state; all zero for a synchronous logger. async_enabled is written
298 : // once before the object is published (or by the fork child handler), so it's
299 : // read without a lock.
300 : bool async_enabled;
301 : bool is_bounded_queue;
302 : union {
303 : ccircq *circq;
304 : cdynmq *dynmq;
305 : } q;
306 : // Deadline of the drain that turned q's sends off, set before the sends go
307 : // off. drain_left is set when a drain gave up on a writer thread that didn't
308 : // answer; later records then never wait on it. owes_repair mirrors
309 : // CLOG_OWED_REPAIR so the exit drain can see a debt without the mutex.
310 : _Atomic uint64_t drain_deadline_ns;
311 : _Atomic bool drain_left;
312 : _Atomic bool owes_repair;
313 : clog_async_cfg async_cfg;
314 : ccol__thread_id writer_thread;
315 : // The writer thread's batch, shared by every handle of this target.
316 : // last_flush_monotonic is on CLOCK_MONOTONIC so a clock step can't stretch
317 : // the flush interval.
318 : clog_buf async_buf;
319 : struct timespec last_flush_monotonic;
320 :
321 : // Rotation state, at the end so no field each write reads moves.
322 : // rot_last_stamp and rot_last_seq name the newest rotated file (stamp digits
323 : // without a NUL, and the collision number); every new name sorts above it.
324 : // The ignored_note fields rate-limit WARNs about entries that aren't
325 : // generations.
326 : char rot_last_stamp[CLOG_ROTATION_STAMP_DIGITS];
327 : bool rot_name_known;
328 : unsigned long rot_last_seq;
329 : time_t ignored_note_window;
330 : unsigned ignored_note_count;
331 : // Last component of file_path; every rotation step works on it relative to
332 : // dir_fd.
333 : const char *file_base;
334 : // Compression queue, oldest first, and its thread. compress_cv and the thread
335 : // exist while compressor_live is true.
336 : clog_compress_job *compress_head;
337 : clog_compress_job *compress_tail;
338 : ccol__cond_var compress_cv;
339 : ccol__thread_id compressor_thread;
340 : // The log file's directory, opened at create when rotation is on, else -1. It
341 : // keeps a relative path valid after a chdir().
342 : int dir_fd;
343 : bool compressor_live;
344 : bool compressor_stop;
345 : // compress_prune_deferred: A deletion pass kept an old generation only
346 : // because its compression was running, so the compressor runs the pass again
347 : // after it. compress_abort: The exit drain ran out of time, so the running
348 : // compression stops at its next block and keeps the source.
349 : bool compress_prune_deferred;
350 : _Atomic bool compress_abort;
351 : // The directory entry this target writes (directory dev/ino plus file_base),
352 : // so a second open of the same file finds it in clog_slot_table.file_shareds.
353 : bool file_id_known;
354 : dev_t file_dir_dev;
355 : ino_t file_dir_ino;
356 : // CLOG_FATAL calls waiting for mutex; the writer thread yields while it's not
357 : // zero (see clog_writer_lock()).
358 : atomic_uint fatal_waiters;
359 : // The repair this target owes its output (see clog_pay_owed()): A newline
360 : // closing a line left open on disk, and the count, records and bytes of
361 : // losses no marker has named yet. owed_err is the last failed write's errno,
362 : // and owed_detail is the text of the first loss.
363 : bool owe_newline;
364 : int owed_err;
365 : size_t owed_losses;
366 : size_t owed_records;
367 : size_t owed_bytes;
368 : char owed_detail[128];
369 : // errno of the last partial write of the async batch, while the batch keeps
370 : // the bytes.
371 : int retain_err;
372 : #ifdef RUNNING_UNIT_TESTS
373 : // White-box counters for the test hooks of the same names, and the writer
374 : // thread's recorded signal mask (bit 0 SIGPIPE, bit 1 SIGXFSZ, bit 2
375 : // recorded).
376 : _Atomic size_t test_writer_timeout_wakeups;
377 : _Atomic size_t test_writer_interval_flushes;
378 : _Atomic size_t test_sync_lock_waiters;
379 : _Atomic size_t test_sync_records_locked;
380 : _Atomic unsigned test_writer_blocked_signals;
381 : #endif
382 : } clog_shared;
383 :
384 : // One logger handle's object: Its level, its own fields and its record buffer.
385 : // fields_mutex guards fields only, so field changes on one derived logger don't
386 : // contend with writes on a sibling. When both locks are needed, shared->mutex
387 : // is taken first. min_level is atomic because clog__write() reads it before it
388 : // takes any lock.
389 : struct clogger {
390 : clog_shared *shared;
391 : _Atomic clog_level min_level;
392 : ccol__mutex fields_mutex;
393 : chmap fields;
394 : clog_buf buf;
395 : // Written once before the handle is published, so an unpin finds its slot.
396 : clog self_handle;
397 : };
398 :
399 : // A slot of the handle table. A clog is (index << 32) | generation, so a stale
400 : // handle never resolves. in_use goes false at the start of a close; freed goes
401 : // true only when logger_free() has run, which is what the fork walk tests
402 : // before it locks fields_mutex.
403 : typedef struct {
404 : struct clogger *ptr;
405 : uint32_t generation;
406 : bool in_use;
407 : bool freed;
408 : } clog_slot;
409 :
410 : // The lock-free half of the handle table: Handle to pointer, plus the pin that
411 : // keeps a logger alive during a call. Every log call resolves here and must
412 : // write nothing another thread reads.
413 : static ccol_pintable clog_pintable;
414 :
415 : // The cold half of the handle table. The rwlock guards it for acquire, close
416 : // and the fork walk; resolves go through clog_pintable and never take it. The
417 : // vectors use the default allocator whatever a logger's procs are.
418 : static struct {
419 : ccol__rw_lock rwlock;
420 : ccol__once_flag once;
421 : cvec slots;
422 : cvec free_indices;
423 : // Every clog_shared from its first handle until it's freed, whatever in_use
424 : // says; the fork walk locks the mutex of each.
425 : cvec live_shareds;
426 : // Closes that have cleared their slot but still use this table; without the
427 : // count a second close could free live_shareds under the first.
428 : size_t closes_in_flight;
429 : // Set when the exit destructor found a logger open; the last close then
430 : // releases the table.
431 : bool release_deferred;
432 : // File-backed targets with a known directory entry, so opening the same file
433 : // again attaches or fails instead of building a second target. A target
434 : // leaves it only after its last close stopped its threads.
435 : cvec file_shareds;
436 : } clog_slot_table = {0};
437 :
438 : static bool clog_any_slot_live_locked(void);
439 : static void clog_release_slot_table_locked(void);
440 : static void clog_release_slot_table_if_deferred_locked(void);
441 :
442 : #if CCOL_FORK_SAFETY_REQUIRED
443 :
444 : // A slot that a fork() caught in the middle of clog_close() (in_use false,
445 : // freed false). The child finishes that close, since the closing thread doesn't
446 : // exist there. With CCOL_FORK_SAFETY_REQUIRED at 0 none of the fork code is
447 : // compiled.
448 : typedef struct {
449 : uint32_t idx;
450 : struct clogger *raw;
451 : } clog_atfork_closing;
452 :
453 : // What clog_atfork_prepare() locked and recorded, so the parent and child
454 : // handlers undo exactly that. Only the forking thread touches it, between
455 : // prepare and release.
456 : static struct {
457 : cvec locked_fields;
458 : cvec closing_slots;
459 : } clog_atfork_state = {0};
460 :
461 : static void clog_atfork_prepare(void);
462 : static void clog_atfork_parent(void);
463 : static void clog_atfork_child(void);
464 : #endif
465 : static void clog_slot_table_init_globals(void);
466 :
467 : // Removes sh from v, a vector of clog_shared* in no order, by moving the last
468 : // entry into its place. The close path uses it to take a target out of
469 : // live_shareds or file_shareds. The caller holds the table's write lock.
470 1974 : static void clog_shareds_remove(cvec v, clog_shared *sh) {
471 1974 : size_t n = cvector_size(v);
472 3101 : for (size_t i = 0; i < n; i++) {
473 3020 : if (*(clog_shared **)cvector_at(v, i) != sh) continue;
474 1893 : clog_shared *last = *(clog_shared **)cvector_at(v, n - 1);
475 1893 : *(clog_shared **)cvector_at(v, i) = last;
476 1893 : cvector_pop_back(v, &last);
477 1893 : return;
478 : }
479 : }
480 :
481 : static void logger_free(struct clogger *lg);
482 : static void shared_close_owned_fd(clog_shared *sh);
483 : static void shared_free_partial(clog_shared *sh);
484 :
485 : #ifdef RUNNING_UNIT_TESTS
486 :
487 : // Forces the next clog_handle_acquire() to take a fresh slot and fail its
488 : // live_shareds registration, which reaches the rollback that has to reset
489 : // freed. It disarms itself when it fires.
490 : static _Atomic bool clog_test_force_next_fresh_slot_reg_failure = false;
491 :
492 : // Takes the forced registration failure, for clog_handle_acquire() in a test
493 : // build; true when it was armed.
494 3679 : static bool clog_test_consume_forced_fresh_slot_reg_failure(void) {
495 3679 : return atomic_exchange(&clog_test_force_next_fresh_slot_reg_failure, false);
496 : }
497 :
498 : // Arms or disarms the forced live_shareds failure of the next handle
499 : // acquisition, so a test can reach the rollback that resets freed.
500 415 : void clog__test_force_next_fresh_slot_registration_failure(bool force) {
501 415 : atomic_store(&clog_test_force_next_fresh_slot_reg_failure, force);
502 415 : }
503 :
504 : // Close hold gate of clog__test_hold_close_finalize(). It doesn't disarm
505 : // itself; a held close gives up after CLOG_TEST_CLOSE_HOLD_MAX_US so a broken
506 : // test fails instead of hanging.
507 : #define CLOG_TEST_CLOSE_HOLD_MAX_US 30000000U
508 : static _Atomic bool clog_test_close_finalize_hold = false;
509 : static _Atomic bool clog_test_close_finalize_entered_state = false;
510 :
511 : // Holds or releases closes at the close gate (between in_use and freed), so a
512 : // test can fork inside that window; holding also clears the entered flag.
513 2 : void clog__test_hold_close_finalize(bool hold) {
514 2 : if (hold) atomic_store(&clog_test_close_finalize_entered_state, false);
515 2 : atomic_store(&clog_test_close_finalize_hold, hold);
516 2 : }
517 :
518 : // Tells whether a close has reached the held gate, so a test knows when to act.
519 2 : bool clog__test_close_finalize_entered(void) {
520 2 : return atomic_load(&clog_test_close_finalize_entered_state);
521 : }
522 :
523 : // Closes that found their handle pinned and started to wait (step 3).
524 : static _Atomic size_t clog_test_close_pin_waits_state = 0;
525 :
526 : // Gives how many closes started to wait for a pinned handle, so a test can see
527 : // a close wait for a call in flight.
528 3 : size_t clog__test_close_pin_waits(void) {
529 3 : return atomic_load(&clog_test_close_pin_waits_state);
530 : }
531 :
532 : // Delay of clog__test_set_close_release_window_us(); it doesn't disarm itself.
533 : static _Atomic unsigned int clog_test_close_release_window_us = 0;
534 : static _Atomic bool clog_test_close_release_window_entered_state = false;
535 :
536 : // Sets how long a close stays in its release window (slot cleared, table still
537 : // in use), so a test can race a second close there; it clears the entered flag.
538 2 : void clog__test_set_close_release_window_us(unsigned int delay_us) {
539 2 : atomic_store(&clog_test_close_release_window_entered_state, false);
540 2 : atomic_store(&clog_test_close_release_window_us, delay_us);
541 2 : }
542 :
543 : // Tells whether a close has entered its release window.
544 3 : bool clog__test_close_release_window_entered(void) {
545 3 : return atomic_load(&clog_test_close_release_window_entered_state);
546 : }
547 :
548 : // Gives the number of targets in live_shareds, read under the table's read
549 : // lock, so a test can check that every rollback unregisters its target.
550 6 : size_t clog__test_live_shareds_count(void) {
551 6 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
552 6 : ccol__rw_lock_rdlock(clog_slot_table.rwlock);
553 12 : size_t n = clog_slot_table.live_shareds
554 6 : ? cvector_size(clog_slot_table.live_shareds)
555 6 : : 0;
556 6 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
557 6 : return n;
558 : }
559 : #else
560 :
561 : // Stub of a non-test build, so clog_handle_acquire() needs no #ifdef: No
562 : // registration failure is forced.
563 : static inline bool clog_test_consume_forced_fresh_slot_reg_failure(void) {
564 : return false;
565 : }
566 : #endif
567 :
568 : // Initializes the handle table and the fork scratch vectors, once, through
569 : // clog_slot_table.once, before the first handle exists. It also registers the
570 : // fork handlers, so they exist whenever a logger can. A failure here is fatal.
571 46 : static void clog_slot_table_init_globals(void) {
572 46 : if (ccol__rw_lock_init(clog_slot_table.rwlock) != 0)
573 0 : ccol__fatal_err("clog slot table: failed to initialize rwlock");
574 46 : clog_slot_table.slots = cvector_create(sizeof(clog_slot), NULL);
575 46 : if (!clog_slot_table.slots)
576 0 : ccol__fatal_err("clog slot table: failed to allocate slots vector");
577 46 : clog_slot_table.free_indices = cvector_create(sizeof(uint32_t), NULL);
578 46 : if (!clog_slot_table.free_indices)
579 0 : ccol__fatal_err("clog slot table: failed to allocate free-index vector");
580 46 : clog_slot_table.live_shareds = cvector_create(sizeof(clog_shared *), NULL);
581 46 : if (!clog_slot_table.live_shareds)
582 0 : ccol__fatal_err("clog slot table: failed to allocate live-shareds vector");
583 46 : clog_slot_table.file_shareds = cvector_create(sizeof(clog_shared *), NULL);
584 46 : if (!clog_slot_table.file_shareds)
585 0 : ccol__fatal_err("clog slot table: failed to allocate file-shareds vector");
586 : #if CCOL_FORK_SAFETY_REQUIRED
587 46 : clog_atfork_state.locked_fields =
588 46 : cvector_create(sizeof(struct clogger *), NULL);
589 46 : if (!clog_atfork_state.locked_fields)
590 0 : ccol__fatal_err(
591 : "clog slot table: failed to allocate atfork scratch vector");
592 46 : clog_atfork_state.closing_slots =
593 46 : cvector_create(sizeof(clog_atfork_closing), NULL);
594 46 : if (!clog_atfork_state.closing_slots)
595 0 : ccol__fatal_err(
596 : "clog slot table: failed to allocate atfork closing-slots vector");
597 46 : ccol__at_fork(clog_atfork_prepare, clog_atfork_parent, clog_atfork_child);
598 : #endif
599 46 : }
600 :
601 : // Registers this module's fork handlers now, so they're registered before the
602 : // caller's. Prepare handlers run in reverse order, so the caller's prepare (for
603 : // chttpserver, which calls into clog while holding its engine mutex) then runs
604 : // first and the fork lock order matches the ordinary one.
605 39 : void clog__ensure_atfork_registered_before_caller(void) {
606 39 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
607 39 : }
608 :
609 : // Resolves h and pins the logger against a concurrent close; NULL for a null,
610 : // stale or out of range handle. The caller must unpin exactly once on every
611 : // path. It takes no lock and writes nothing shared, since every log call runs
612 : // it.
613 53524 : static struct clogger *clog_resolve(clog h) {
614 53524 : return (struct clogger *)ccol_pintable_pin(&clog_pintable, h);
615 : }
616 :
617 : // Releases the pin clog_resolve() took, on every path out of a public call.
618 : // Nothing may touch raw after the release, since a close may free it at once,
619 : // and no lock or wakeup belongs here, because the close polls the pin count.
620 53511 : static void clog_resolve_unpin(struct clogger *raw) {
621 53511 : ccol_pintable_unpin(&clog_pintable, raw->self_handle);
622 5 : }
623 :
624 : // Makes a handle for a fully built lg (from a create or clog_derive()), and
625 : // registers lg->shared in live_shareds unless it's there already. Gives
626 : // CLOG_NULL when the table can't grow or was released at exit. Takes the write
627 : // lock. Every acquire sets freed = false, and every rollback leaves the slot
628 : // freed with ptr NULL, because the fork walk locks fields_mutex of any slot
629 : // that isn't freed. A failed publish also undoes the live_shareds push (the
630 : // tail entry, since the lock is held throughout), or the next fork would lock a
631 : // mutex inside freed memory.
632 3680 : static clog clog_handle_acquire(struct clogger *lg) {
633 3680 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
634 3680 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
635 3680 : if (__builtin_expect(clog_slot_table.slots == NULL, 0)) {
636 1 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
637 1 : return CLOG_NULL;
638 : }
639 :
640 3679 : bool force_fresh_slot_reg_failure =
641 3679 : clog_test_consume_forced_fresh_slot_reg_failure();
642 :
643 3679 : uint32_t idx;
644 3679 : clog_slot *slot;
645 7303 : if (!force_fresh_slot_reg_failure &&
646 3624 : cvector_size(clog_slot_table.free_indices) > 0) {
647 3550 : cvector_pop_back(clog_slot_table.free_indices, &idx);
648 3550 : slot = (clog_slot *)cvector_at(clog_slot_table.slots, idx);
649 : } else {
650 129 : if (cvector_size(clog_slot_table.slots) >= CCOL_PIN_MAX_SLOTS) {
651 0 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
652 0 : return CLOG_NULL;
653 : }
654 129 : clog_slot fresh = {0};
655 129 : if (cvector_push_back(clog_slot_table.slots, &fresh) != ccol_success) {
656 0 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
657 0 : return CLOG_NULL;
658 : }
659 129 : idx = (uint32_t)cvector_size(clog_slot_table.slots) - 1;
660 129 : slot = (clog_slot *)cvector_at(clog_slot_table.slots, idx);
661 : }
662 :
663 3679 : bool already_registered = false;
664 3679 : size_t n = cvector_size(clog_slot_table.live_shareds);
665 5289 : for (size_t i = 0; i < n; i++) {
666 7588 : clog_shared *seen =
667 3794 : *(clog_shared **)cvector_at(clog_slot_table.live_shareds, i);
668 3794 : if (seen == lg->shared) {
669 : already_registered = true;
670 : break;
671 : }
672 : }
673 3679 : bool live_shareds_registration_failed = force_fresh_slot_reg_failure;
674 3679 : if (!live_shareds_registration_failed && !already_registered) {
675 1471 : live_shareds_registration_failed =
676 1471 : cvector_push_back(clog_slot_table.live_shareds, &lg->shared) !=
677 : ccol_success;
678 : }
679 3679 : if (live_shareds_registration_failed) {
680 55 : slot->freed = true;
681 55 : slot->ptr = NULL;
682 55 : cvector_push_back(clog_slot_table.free_indices, &idx);
683 55 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
684 55 : return CLOG_NULL;
685 : }
686 :
687 3624 : slot->generation++;
688 3624 : if (slot->generation == 0) slot->generation++;
689 :
690 3624 : clog h = ((clog)idx << 32) | (clog)slot->generation;
691 :
692 3624 : lg->self_handle = h;
693 :
694 3624 : if (!ccol_pintable_publish(&clog_pintable, idx, slot->generation, lg)) {
695 2 : if (!already_registered) {
696 2 : clog_shared *rolled_back = NULL;
697 2 : cvector_pop_back(clog_slot_table.live_shareds, &rolled_back);
698 : }
699 2 : lg->self_handle = 0;
700 2 : slot->freed = true;
701 2 : slot->ptr = NULL;
702 2 : cvector_push_back(clog_slot_table.free_indices, &idx);
703 2 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
704 2 : return CLOG_NULL;
705 : }
706 :
707 3622 : slot->ptr = lg;
708 3622 : slot->in_use = true;
709 3622 : slot->freed = false;
710 :
711 3622 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
712 3622 : return h;
713 : }
714 :
715 : #if CCOL_FORK_SAFETY_REQUIRED
716 :
717 : // Fork prepare handler. fork() copies only the calling thread, so it takes the
718 : // table's write lock, the mutex of every live clog_shared (from live_shareds,
719 : // because a closing slot isn't in_use while its close still holds that mutex)
720 : // and the fields_mutex of every slot that isn't freed. A lock it can't record
721 : // for lack of memory is released again at once. It also records the slots
722 : // caught in the middle of a close (in_use false, freed false), which the child
723 : // finishes.
724 337 : static void clog_atfork_prepare(void) {
725 : #ifdef RUNNING_UNIT_TESTS
726 337 : ccol__atfork_order_record(ccol__atfork_module_clogger);
727 : #endif
728 337 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
729 337 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
730 337 : if (clog_slot_table.slots == NULL) return;
731 :
732 337 : size_t ns = cvector_size(clog_slot_table.live_shareds);
733 498 : for (size_t i = 0; i < ns; i++) {
734 322 : clog_shared *sh =
735 161 : *(clog_shared **)cvector_at(clog_slot_table.live_shareds, i);
736 161 : ccol__mutex_lock(sh->mutex);
737 : }
738 :
739 337 : size_t n = cvector_size(clog_slot_table.slots);
740 3248 : for (size_t i = 0; i < n; i++) {
741 2911 : clog_slot *slot = (clog_slot *)cvector_at(clog_slot_table.slots, i);
742 2911 : if (slot->freed) continue;
743 203 : ccol__mutex_lock(slot->ptr->fields_mutex);
744 203 : if (cvector_push_back(clog_atfork_state.locked_fields, &slot->ptr) !=
745 : ccol_success) {
746 0 : ccol__mutex_unlock(slot->ptr->fields_mutex);
747 : }
748 :
749 203 : if (!slot->in_use) {
750 1 : clog_atfork_closing c = {.idx = (uint32_t)i, .raw = slot->ptr};
751 1 : cvector_push_back(clog_atfork_state.closing_slots, &c);
752 : }
753 : }
754 : }
755 :
756 : // Undoes clog_atfork_prepare() in the parent or the child. The child
757 : // initializes the table's rwlock afresh, since glibc tracks the writer by TID
758 : // and an unlock from the child's new TID releases nothing. In the child it also
759 : // resets the pin count of every slot (no other thread can release a pin there),
760 : // forgets the compression jobs and turns async off for every target (their
761 : // threads don't exist in the child), finishes every close the fork interrupted,
762 : // and forgets targets that were in the middle of their last close.
763 : // closing_slots is cleared on both sides, so a later fork never acts on stale
764 : // entries.
765 337 : static void clog_atfork_release(bool in_child) {
766 337 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
767 337 : if (clog_slot_table.slots == NULL) {
768 0 : if (in_child) {
769 0 : if (ccol__rw_lock_reinit_in_child(clog_slot_table.rwlock) != 0)
770 0 : ccol__fatal_err(
771 : "clog atfork release: failed to reinit slot table rwlock");
772 : } else {
773 0 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
774 : }
775 0 : return;
776 : }
777 337 : size_t nf = cvector_size(clog_atfork_state.locked_fields);
778 540 : for (size_t i = nf; i-- > 0;) {
779 406 : struct clogger *lg =
780 203 : *(struct clogger **)cvector_at(clog_atfork_state.locked_fields, i);
781 203 : if (in_child) {
782 0 : ccol_pintable_reset_for(&clog_pintable, lg->self_handle);
783 : }
784 203 : ccol__mutex_unlock(lg->fields_mutex);
785 : }
786 :
787 337 : size_t ns = cvector_size(clog_slot_table.live_shareds);
788 498 : for (size_t i = 0; i < ns; i++) {
789 322 : clog_shared *sh =
790 161 : *(clog_shared **)cvector_at(clog_slot_table.live_shareds, i);
791 161 : if (in_child) {
792 0 : sh->compress_running = NULL;
793 0 : sh->compress_head = NULL;
794 0 : sh->compress_tail = NULL;
795 0 : sh->compressor_live = false;
796 0 : sh->compressor_stop = false;
797 0 : sh->compress_prune_deferred = false;
798 : }
799 0 : if (in_child && sh->async_enabled) {
800 0 : sh->async_enabled = false;
801 0 : sh->async_partial_record &= (unsigned char)~CLOG_SPLIT_MASK;
802 : }
803 161 : ccol__mutex_unlock(sh->mutex);
804 : }
805 :
806 337 : if (in_child) {
807 0 : size_t nc = cvector_size(clog_atfork_state.closing_slots);
808 0 : for (size_t i = 0; i < nc; i++) {
809 0 : clog_atfork_closing *c =
810 0 : (clog_atfork_closing *)cvector_at(clog_atfork_state.closing_slots, i);
811 0 : clog_slot *slot = (clog_slot *)cvector_at(clog_slot_table.slots, c->idx);
812 0 : if (slot->freed) continue;
813 :
814 0 : struct clogger *raw = c->raw;
815 0 : clog_shared *sh = raw->shared;
816 :
817 0 : ccol_pintable_reset_for(&clog_pintable, raw->self_handle);
818 :
819 0 : logger_free(raw);
820 0 : slot->freed = true;
821 0 : slot->ptr = NULL;
822 0 : slot->generation++;
823 0 : if (slot->generation == 0) slot->generation++;
824 0 : cvector_push_back(clog_slot_table.free_indices, &c->idx);
825 :
826 0 : if (--sh->ref_count == 0) {
827 0 : clog_shareds_remove(clog_slot_table.live_shareds, sh);
828 0 : clog_shareds_remove(clog_slot_table.file_shareds, sh);
829 0 : shared_close_owned_fd(sh);
830 0 : ccol__mutex_destroy(sh->mutex);
831 0 : shared_free_partial(sh);
832 : }
833 : }
834 : }
835 :
836 337 : if (in_child) {
837 0 : size_t nfs = cvector_size(clog_slot_table.file_shareds);
838 0 : for (size_t i = nfs; i-- > 0;) {
839 0 : clog_shared *fs =
840 0 : *(clog_shared **)cvector_at(clog_slot_table.file_shareds, i);
841 0 : bool live = false;
842 0 : size_t nl = cvector_size(clog_slot_table.live_shareds);
843 0 : for (size_t j = 0; j < nl && !live; j++)
844 0 : live =
845 0 : *(clog_shared **)cvector_at(clog_slot_table.live_shareds, j) == fs;
846 0 : if (!live) clog_shareds_remove(clog_slot_table.file_shareds, fs);
847 : }
848 0 : if (ccol__rw_lock_reinit_in_child(clog_slot_table.rwlock) != 0)
849 0 : ccol__fatal_err(
850 : "clog atfork release: failed to reinit slot table rwlock");
851 : } else {
852 337 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
853 : }
854 337 : cvector_reset(clog_atfork_state.locked_fields);
855 337 : cvector_reset(clog_atfork_state.closing_slots);
856 : }
857 :
858 : // The fork handlers of the parent and the child, registered with
859 : // clog_atfork_prepare(); both undo what prepare took through
860 : // clog_atfork_release().
861 337 : static void clog_atfork_parent(void) { clog_atfork_release(false); }
862 0 : static void clog_atfork_child(void) { clog_atfork_release(true); }
863 : #endif
864 :
865 : static bool clog_table_still_needed_locked(void);
866 :
867 : // True when a slot still names a logger. It reads ptr, which a close clears
868 : // only in its last locked step; in_use goes false much earlier. Callers go
869 : // through clog_table_still_needed_locked(). Needs the write lock.
870 96 : static bool clog_any_slot_live_locked(void) {
871 96 : size_t n = cvector_size(clog_slot_table.slots);
872 454 : for (size_t i = 0; i < n; i++) {
873 410 : clog_slot *slot = (clog_slot *)cvector_at(clog_slot_table.slots, i);
874 410 : if (slot->ptr != NULL) return true;
875 : }
876 : return false;
877 : }
878 :
879 : // Releases the table when the exit destructor deferred that and nothing needs
880 : // it any more, so a program that closes its loggers late leaves nothing
881 : // allocated. The last close calls it. It isn't inlined so that close path keeps
882 : // its shape. Needs the write lock.
883 : static __attribute__((noinline)) void
884 3577 : clog_release_slot_table_if_deferred_locked(void) {
885 3586 : if (clog_slot_table.release_deferred && !clog_table_still_needed_locked()) {
886 2 : clog_release_slot_table_locked();
887 : }
888 3577 : }
889 :
890 : // Tells whether a slot names a logger or a close hasn't finished with the
891 : // table, the test both release paths use before they free the table. Needs the
892 : // write lock.
893 97 : static bool clog_table_still_needed_locked(void) {
894 97 : return clog_slot_table.closes_in_flight != 0 || clog_any_slot_live_locked();
895 : }
896 :
897 : // Frees the table's vectors and the pin index. The caller holds the write lock
898 : // and knows nothing needs the table. Each vector is NULL afterwards, so a later
899 : // call sees the table as released. The rwlock stays.
900 44 : static void clog_release_slot_table_locked(void) {
901 44 : cvector_destroy(clog_slot_table.slots);
902 44 : cvector_destroy(clog_slot_table.free_indices);
903 44 : cvector_destroy(clog_slot_table.live_shareds);
904 44 : cvector_destroy(clog_slot_table.file_shareds);
905 44 : ccol_pintable_dispose(&clog_pintable);
906 : #if CCOL_FORK_SAFETY_REQUIRED
907 44 : cvector_destroy(clog_atfork_state.locked_fields);
908 44 : cvector_destroy(clog_atfork_state.closing_slots);
909 : #endif
910 44 : clog_slot_table.release_deferred = false;
911 44 : }
912 :
913 : // How long the exit release waits for the table's lock before it gives up and
914 : // leaves the table allocated.
915 : #define CLOG_TABLE_RELEASE_WAIT_MS 1000
916 :
917 : // Frees the handle table at exit or unload, but only when no logger is open and
918 : // no close is running; otherwise the last close does it (release_deferred). It
919 : // holds the write lock throughout, with a bounded wait. The rwlock itself is
920 : // never destroyed, because a later caller may still take it.
921 93 : __attribute__((destructor)) static void cleanup_clog_slot_table(void) {
922 140 : if (!clog_slot_table.slots) return;
923 89 : struct timespec until;
924 89 : clock_gettime(CLOCK_REALTIME, &until);
925 89 : until.tv_sec += CLOG_TABLE_RELEASE_WAIT_MS / 1000;
926 89 : until.tv_nsec += (long)(CLOG_TABLE_RELEASE_WAIT_MS % 1000) * 1000000L;
927 89 : if (until.tv_nsec >= 1000000000L) {
928 0 : until.tv_sec++;
929 0 : until.tv_nsec -= 1000000000L;
930 : }
931 89 : if (ccol__rw_lock_timedwrlock(clog_slot_table.rwlock, until) != 0) return;
932 88 : if (clog_table_still_needed_locked()) {
933 46 : clog_slot_table.release_deferred = true;
934 46 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
935 46 : return;
936 : }
937 42 : clog_release_slot_table_locked();
938 42 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
939 : }
940 :
941 : // Gives b its first CLOG_BUF_INITIAL bytes from m_procs, with the default
942 : // growth ceiling; every record buffer starts here. Returns 0 or -1.
943 4050 : static int buf_init(clog_buf *b, const ccol_memmgmt_procs *m_procs) {
944 4050 : b->m_procs = m_procs;
945 4042 : b->data = ccol__mem_alloc(m_procs, CLOG_BUF_INITIAL);
946 4042 : if (!b->data) return -1;
947 4040 : b->data[0] = '\0';
948 4040 : b->len = 0;
949 4040 : b->cap = CLOG_BUF_INITIAL;
950 4040 : b->cap_limit = CLOG_BUF_LIMIT;
951 4040 : b->oom = false;
952 4032 : return 0;
953 : }
954 :
955 : // Raises b's growth ceiling to new_limit, never lowering it, so the async batch
956 : // can hold a flush_buffer_size larger than one record's limit.
957 308 : static void buf_raise_cap_limit(clog_buf *b, size_t new_limit) {
958 5 : if (new_limit > b->cap_limit) b->cap_limit = new_limit;
959 : }
960 :
961 : // Empties b and keeps its memory, so the next record reuses the allocation.
962 22194 : static void buf_reset(clog_buf *b) { b->len = 0; }
963 :
964 : // Frees b's memory when its logger or target goes away.
965 3961 : static void buf_free(clog_buf *b) {
966 3961 : ccol__mem_free(b->m_procs, b->data);
967 3961 : b->data = NULL;
968 3961 : b->len = b->cap = 0;
969 3961 : }
970 :
971 : #ifdef RUNNING_UNIT_TESTS
972 :
973 : // Forces the next buf_append() or buf_appendf() to report an allocation
974 : // failure, even for an append that needs no growth. It disarms itself when it
975 : // fires.
976 : static _Atomic bool clog_test_force_next_buf_ensure_failure_state = false;
977 :
978 : // Takes the forced append failure, for buf_append() and buf_appendf() in a test
979 : // build; true when it was armed.
980 614372 : static bool clog_test_consume_forced_buf_ensure_failure(void) {
981 614372 : return atomic_exchange(&clog_test_force_next_buf_ensure_failure_state, false);
982 : }
983 :
984 : // Arms or disarms the forced failure of the next buffer append, so a test can
985 : // reach the fallbacks of a failed allocation.
986 1 : void clog__test_force_next_buf_ensure_failure(bool force) {
987 1 : atomic_store(&clog_test_force_next_buf_ensure_failure_state, force);
988 1 : }
989 : #else
990 :
991 : // Stub of a non-test build, so the append functions need no #ifdef: No append
992 : // failure is forced.
993 : static inline bool clog_test_consume_forced_buf_ensure_failure(void) {
994 : return false;
995 : }
996 : #endif
997 :
998 : // Makes room for at least need more bytes, doubling the capacity up to
999 : // cap_limit. Returns 0 or -1. Hitting cap_limit is an ordinary size refusal;
1000 : // only a failed allocation sets b->oom. The doubling is guarded against size_t
1001 : // overflow and goes back through the size check after clamping to cap_limit,
1002 : // since a reachable cap_limit can still be too small.
1003 520966 : static int buf_ensure(clog_buf *b, size_t need) {
1004 520966 : if (b->cap - b->len >= need) return 0;
1005 224 : size_t new_cap = b->cap ? b->cap : CLOG_BUF_INITIAL;
1006 497 : while (new_cap - b->len < need) {
1007 366 : if (new_cap >= b->cap_limit) return -1;
1008 273 : if (new_cap > SIZE_MAX / 2) {
1009 : new_cap = b->cap_limit;
1010 : } else {
1011 273 : new_cap *= 2;
1012 273 : if (new_cap > b->cap_limit) new_cap = b->cap_limit;
1013 : }
1014 : }
1015 131 : char *p = ccol__mem_realloc(b->m_procs, b->data, new_cap);
1016 131 : if (!p) {
1017 41 : b->oom = true;
1018 41 : return -1;
1019 : }
1020 90 : b->data = p;
1021 90 : b->cap = new_cap;
1022 90 : return 0;
1023 : }
1024 :
1025 : // Appends n bytes of s to b, growing it as needed, and keeps b NUL-terminated;
1026 : // the basic step of every record builder. Returns 0, or -1 when b can't grow (a
1027 : // test can force that).
1028 520948 : static int buf_append(clog_buf *b, const char *s, size_t n) {
1029 520948 : if (clog_test_consume_forced_buf_ensure_failure()) {
1030 0 : b->oom = true;
1031 0 : return -1;
1032 : }
1033 520948 : if (buf_ensure(b, n + 1) != 0) return -1;
1034 520816 : memcpy(b->data + b->len, s, n);
1035 520816 : b->len += n;
1036 520816 : b->data[b->len] = '\0';
1037 520816 : return 0;
1038 : }
1039 :
1040 : // Appends printf-formatted text to b, growing it when the first attempt doesn't
1041 : // fit, for the parts of a record that need formatting. Returns 0 or -1.
1042 93424 : static int __attribute__((format(printf, 2, 3))) buf_appendf(clog_buf *b,
1043 : const char *fmt,
1044 : ...) {
1045 93424 : if (clog_test_consume_forced_buf_ensure_failure()) {
1046 1 : b->oom = true;
1047 1 : return -1;
1048 : }
1049 :
1050 93423 : va_list ap, ap2;
1051 93423 : va_start(ap, fmt);
1052 93423 : va_copy(ap2, ap);
1053 :
1054 93423 : size_t avail = b->cap - b->len;
1055 93423 : int n = vsnprintf(b->data + b->len, avail, fmt, ap);
1056 93423 : va_end(ap);
1057 :
1058 93423 : if (n < 0) {
1059 0 : va_end(ap2);
1060 0 : return -1;
1061 : }
1062 93423 : if ((size_t)n >= avail) {
1063 18 : if (buf_ensure(b, (size_t)n + 1) != 0) {
1064 2 : va_end(ap2);
1065 2 : return -1;
1066 : }
1067 16 : avail = b->cap - b->len;
1068 16 : n = vsnprintf(b->data + b->len, avail, fmt, ap2);
1069 16 : if (n < 0 || (size_t)n >= avail) {
1070 0 : va_end(ap2);
1071 0 : return -1;
1072 : }
1073 : }
1074 93421 : va_end(ap2);
1075 93421 : b->len += (size_t)n;
1076 93421 : return 0;
1077 : }
1078 :
1079 : // Writes the backslash escape of a control byte c (below 0x20, or 0x7f) to esc
1080 : // and its length to *esc_len: \n, \r and \t, or \xXX. Every escaper uses it, so
1081 : // a control byte looks the same in every format.
1082 16 : static void ctrl_escape(unsigned char c, char esc[5], int *esc_len) {
1083 16 : if (c == '\n') {
1084 6 : esc[0] = '\\';
1085 6 : esc[1] = 'n';
1086 6 : *esc_len = 2;
1087 10 : } else if (c == '\r') {
1088 3 : esc[0] = '\\';
1089 3 : esc[1] = 'r';
1090 3 : *esc_len = 2;
1091 7 : } else if (c == '\t') {
1092 3 : esc[0] = '\\';
1093 3 : esc[1] = 't';
1094 3 : *esc_len = 2;
1095 : } else {
1096 4 : snprintf(esc, 5, "\\x%02x", c);
1097 4 : *esc_len = 4;
1098 : }
1099 16 : }
1100 :
1101 : // Length (2, 3 or 4) of the well-formed UTF-8 sequence that starts at the
1102 : // non-ASCII byte p[0], or 0 when the lead byte is invalid or the sequence is
1103 : // overlong, a surrogate, past U+10FFFF or truncated. It stops at the NUL, so it
1104 : // never reads past the end of the string.
1105 44 : static int utf8_valid_seq_len(const unsigned char *p) {
1106 44 : unsigned char c0 = p[0];
1107 44 : if (c0 < 0xc2 || c0 > 0xf4) return 0;
1108 :
1109 20 : int len;
1110 20 : unsigned char lo1, hi1;
1111 20 : if (c0 <= 0xdf) {
1112 : len = 2;
1113 : lo1 = 0x80;
1114 : hi1 = 0xbf;
1115 8 : } else if (c0 <= 0xef) {
1116 4 : len = 3;
1117 4 : lo1 = (c0 == 0xe0) ? 0xa0 : 0x80;
1118 4 : hi1 = (c0 == 0xed) ? 0x9f : 0xbf;
1119 : } else {
1120 4 : len = 4;
1121 4 : lo1 = (c0 == 0xf0) ? 0x90 : 0x80;
1122 2 : hi1 = (c0 == 0xf4) ? 0x8f : 0xbf;
1123 : }
1124 :
1125 20 : unsigned char c1 = p[1];
1126 20 : if (c1 == '\0' || c1 < lo1 || c1 > hi1) return 0;
1127 21 : for (int i = 2; i < len; i++) {
1128 6 : unsigned char ci = p[i];
1129 6 : if (ci == '\0' || ci < 0x80 || ci > 0xbf) return 0;
1130 : }
1131 : return len;
1132 : }
1133 :
1134 : // For a non-ASCII byte at p, the length of the sequence an escaper copies as it
1135 : // is, or 0 when append_utf8_rewrite() must write it: A C1 control (a terminal
1136 : // can read 0xc2 0x9b as CSI) or a byte that isn't well-formed UTF-8.
1137 55 : static inline int utf8_pass_len(const unsigned char *p) {
1138 12 : if (p[0] == 0xc2 && p[1] <= 0x9f) return 0;
1139 44 : return utf8_valid_seq_len(p);
1140 : }
1141 :
1142 : // Writes the replacement of what utf8_pass_len() refused and returns how many
1143 : // input bytes it stands for, or -1 on failure. A C1 control becomes \u0080 to
1144 : // \u009f (2 bytes); a bad byte becomes U+FFFD (1 byte), as an escape when json
1145 : // is true and as UTF-8 otherwise.
1146 37 : static int append_utf8_rewrite(clog_buf *b, const unsigned char *p, bool json) {
1147 37 : if (p[0] == 0xc2 && p[1] >= 0x80 && p[1] <= 0x9f) {
1148 8 : static const char hex[] = "0123456789abcdef";
1149 8 : char esc[6] = {'\\', 'u', '0', '0', hex[p[1] >> 4], hex[p[1] & 0x0f]};
1150 8 : return buf_append(b, esc, sizeof(esc)) == 0 ? 2 : -1;
1151 : }
1152 29 : if (json) return buf_append(b, "\\ufffd", 6) == 0 ? 1 : -1;
1153 17 : return buf_append(b, "\xef\xbf\xbd", 3) == 0 ? 1 : -1;
1154 : }
1155 :
1156 : // Byte classes for buf_append_lv(): 0 copies as it is, 1 forces quotes (space,
1157 : // '=', '"', '\\', controls, DEL), 2 starts a UTF-8 sequence to check, 3 is the
1158 : // NUL.
1159 : static const unsigned char clog_lv_class[256] = {
1160 : [0x00] = 3, [0x01 ... 0x1F] = 1, [' '] = 1, ['='] = 1,
1161 : ['"'] = 1, ['\\'] = 1, [0x7F] = 1, [0x80 ... 0xFF] = 2};
1162 :
1163 : // Appends a logfmt value. A value with a space, '=', '"', '\\', a control or a
1164 : // bad UTF-8 byte goes in quotes with escapes; an empty one is "". One table
1165 : // load per byte and no strlen(), because records are built under the target's
1166 : // mutex.
1167 139103 : static int buf_append_lv(clog_buf *b, const char *s) {
1168 139103 : if (!s) return buf_append(b, "null", 4);
1169 :
1170 : const unsigned char *p = (const unsigned char *)s;
1171 1658684709 : bool quote = false;
1172 1658684709 : for (;;) {
1173 1658684709 : unsigned char k = clog_lv_class[*p];
1174 1658684709 : if (__builtin_expect(k == 0, 1)) {
1175 1658545604 : p++;
1176 1658545604 : continue;
1177 : }
1178 139105 : if (k == 3) break;
1179 33434 : if (k == 2) {
1180 5 : int n = utf8_pass_len(p);
1181 3 : if (n > 0) {
1182 2 : p += n;
1183 2 : continue;
1184 : }
1185 : }
1186 : quote = true;
1187 : break;
1188 : }
1189 139103 : if (!quote && p != (const unsigned char *)s)
1190 105670 : return buf_append(b, s, (size_t)(p - (const unsigned char *)s));
1191 :
1192 33433 : if (buf_append(b, "\"", 1) != 0) return -1;
1193 :
1194 : const char *run = s;
1195 22356748 : for (const char *q = s;; q++) {
1196 22390181 : unsigned char c = (unsigned char)*q;
1197 22390181 : unsigned char k = clog_lv_class[c];
1198 22390181 : if (__builtin_expect(k == 0, 1)) continue;
1199 :
1200 132584 : if (k == 3) {
1201 33433 : if (q > run && buf_append(b, run, (size_t)(q - run)) != 0) return -1;
1202 33349 : break;
1203 : }
1204 99151 : if (c == '"' || c == '\\') {
1205 8 : if (q > run && buf_append(b, run, (size_t)(q - run)) != 0) return -1;
1206 8 : char esc[2] = {'\\', (char)c};
1207 8 : if (buf_append(b, esc, 2) != 0) return -1;
1208 8 : run = q + 1;
1209 99143 : } else if (c < 0x20 || c == 0x7f) {
1210 5 : if (q > run && buf_append(b, run, (size_t)(q - run)) != 0) return -1;
1211 5 : char esc[5];
1212 5 : int esc_len;
1213 5 : ctrl_escape(c, esc, &esc_len);
1214 5 : if (buf_append(b, esc, (size_t)esc_len) != 0) return -1;
1215 5 : run = q + 1;
1216 99138 : } else if (c >= 0x80) {
1217 12 : int n = utf8_pass_len((const unsigned char *)q);
1218 10 : if (n == 0) {
1219 10 : if (q > run && buf_append(b, run, (size_t)(q - run)) != 0) return -1;
1220 10 : n = append_utf8_rewrite(b, (const unsigned char *)q, false);
1221 10 : if (n < 0) return -1;
1222 10 : run = q + n;
1223 : }
1224 12 : q += n - 1;
1225 : }
1226 : }
1227 :
1228 33349 : return buf_append(b, "\"", 1);
1229 : }
1230 :
1231 : // Appends the JSON-escaped content of s without quotes. Controls (C1 included)
1232 : // become escapes and each byte that isn't well-formed UTF-8 becomes \ufffd, so
1233 : // the output is always valid JSON text whatever the input. s must not be NULL.
1234 29600 : static int buf_append_json_content(clog_buf *b, const char *s) {
1235 29600 : const char *run = s;
1236 29600 : const char *p = s;
1237 824695486 : for (;;) {
1238 824695486 : unsigned char c = (unsigned char)*p;
1239 824695486 : if (c == '\0') {
1240 29600 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1241 : break;
1242 : }
1243 824665886 : if (c == '"' || c == '\\') {
1244 4 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1245 4 : char esc[2] = {'\\', (char)c};
1246 4 : if (buf_append(b, esc, 2) != 0) return -1;
1247 4 : p++;
1248 4 : run = p;
1249 4 : continue;
1250 : }
1251 824665882 : if (c < 0x20 || c == 0x7f) {
1252 6 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1253 6 : char esc[7];
1254 6 : int esc_len;
1255 6 : if (c == '\n') {
1256 2 : esc[0] = '\\';
1257 2 : esc[1] = 'n';
1258 2 : esc_len = 2;
1259 4 : } else if (c == '\r') {
1260 1 : esc[0] = '\\';
1261 1 : esc[1] = 'r';
1262 1 : esc_len = 2;
1263 3 : } else if (c == '\t') {
1264 1 : esc[0] = '\\';
1265 1 : esc[1] = 't';
1266 1 : esc_len = 2;
1267 : } else {
1268 2 : esc_len = snprintf(esc, sizeof(esc), "\\u%04x", c);
1269 : }
1270 6 : if (buf_append(b, esc, (size_t)esc_len) != 0) return -1;
1271 6 : p++;
1272 6 : run = p;
1273 6 : continue;
1274 : }
1275 824665876 : if (c >= 0x80) {
1276 20 : int seq_len = utf8_pass_len((const unsigned char *)p);
1277 18 : if (seq_len > 0) {
1278 6 : p += seq_len;
1279 6 : continue;
1280 : }
1281 14 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1282 14 : seq_len = append_utf8_rewrite(b, (const unsigned char *)p, true);
1283 14 : if (seq_len < 0) return -1;
1284 14 : p += seq_len;
1285 14 : run = p;
1286 14 : continue;
1287 : }
1288 824665856 : p++;
1289 : }
1290 : return 0;
1291 : }
1292 :
1293 : // Appends ,"key":"val" with val escaped, or ,"key":null for a NULL val, for the
1294 : // fixed fields of a JSON record. Returns 0 or -1.
1295 341 : static int buf_append_json_kv(clog_buf *b, const char *key, const char *val) {
1296 341 : if (buf_append(b, ",\"", 2) != 0) return -1;
1297 341 : if (buf_append_json_content(b, key) != 0) return -1;
1298 341 : if (buf_append(b, "\":", 2) != 0) return -1;
1299 341 : if (!val) return buf_append(b, "null", 4);
1300 341 : if (buf_append(b, "\"", 1) != 0) return -1;
1301 341 : if (buf_append_json_content(b, val) != 0) return -1;
1302 341 : return buf_append(b, "\"", 1);
1303 : }
1304 :
1305 : // Appends an RFC 5424 SD-PARAM-VALUE: '"', '\\' and ']' get a backslash, and
1306 : // controls are escaped as in the other formats, \n and \r included, so a record
1307 : // never spans lines. Bad UTF-8 bytes become U+FFFD. NULL is written as null.
1308 133 : static int buf_append_sd_value(clog_buf *b, const char *s) {
1309 133 : if (!s) return buf_append(b, "null", 4);
1310 : const char *run = s;
1311 3936 : for (const char *p = s;; p++) {
1312 4069 : unsigned char c = (unsigned char)*p;
1313 4069 : if (*p == '\0') {
1314 133 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1315 : break;
1316 : }
1317 3936 : if (*p == '"' || *p == '\\' || *p == ']') {
1318 4 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1319 4 : char esc[2] = {'\\', *p};
1320 4 : if (buf_append(b, esc, 2) != 0) return -1;
1321 4 : run = p + 1;
1322 3932 : } else if (c < 0x20 || c == 0x7f) {
1323 3 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1324 3 : char esc[5];
1325 3 : int esc_len;
1326 3 : ctrl_escape(c, esc, &esc_len);
1327 3 : if (buf_append(b, esc, (size_t)esc_len) != 0) return -1;
1328 3 : run = p + 1;
1329 3929 : } else if (c >= 0x80) {
1330 9 : int n = utf8_pass_len((const unsigned char *)p);
1331 8 : if (n == 0) {
1332 6 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1333 6 : n = append_utf8_rewrite(b, (const unsigned char *)p, false);
1334 6 : if (n < 0) return -1;
1335 6 : run = p + n;
1336 : }
1337 9 : p += n - 1;
1338 : }
1339 : }
1340 : return 0;
1341 : }
1342 :
1343 : // Writes the SD-PARAM-NAME for key into name. A key longer than 32 characters
1344 : // becomes its first 23, '~' and an FNV-1a hash of the whole key in 8 hex
1345 : // digits, so two keys with a common prefix don't collide.
1346 14 : static void sd_param_name(const char *key, char name[33]) {
1347 14 : size_t klen = strlen(key);
1348 14 : if (klen <= 32) {
1349 11 : memcpy(name, key, klen + 1);
1350 11 : return;
1351 : }
1352 :
1353 : uint32_t h = 2166136261u;
1354 113 : for (const char *p = key; *p; p++) {
1355 110 : h ^= (unsigned char)*p;
1356 110 : h *= 16777619u;
1357 : }
1358 :
1359 3 : memcpy(name, key, 23);
1360 3 : snprintf(name + 23, 33 - 23, "~%08x", h);
1361 : }
1362 :
1363 : // Appends free text with every control escaped and '\\' doubled, so it reads
1364 : // back without ambiguity and can't split a record: A syslog MSG, and a
1365 : // backtrace frame in logfmt and syslog. Bad UTF-8 becomes U+FFFD. s must not be
1366 : // NULL.
1367 1783 : static int buf_append_ctrl_escaped(clog_buf *b, const char *s) {
1368 1783 : const char *run = s;
1369 35729402 : for (const char *p = s;; p++) {
1370 35729402 : unsigned char c = (unsigned char)*p;
1371 35729402 : if (*p == '\0') {
1372 1783 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1373 : break;
1374 : }
1375 35727619 : if (*p == '\\') {
1376 2 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1377 2 : if (buf_append(b, "\\\\", 2) != 0) return -1;
1378 2 : run = p + 1;
1379 35727617 : } else if (c < 0x20 || c == 0x7f) {
1380 8 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1381 8 : char esc[5];
1382 8 : int esc_len;
1383 8 : ctrl_escape(c, esc, &esc_len);
1384 8 : if (buf_append(b, esc, (size_t)esc_len) != 0) return -1;
1385 8 : run = p + 1;
1386 35727609 : } else if (c >= 0x80) {
1387 9 : int n = utf8_pass_len((const unsigned char *)p);
1388 5 : if (n == 0) {
1389 7 : if (p > run && buf_append(b, run, (size_t)(p - run)) != 0) return -1;
1390 7 : n = append_utf8_rewrite(b, (const unsigned char *)p, false);
1391 7 : if (n < 0) return -1;
1392 7 : run = p + n;
1393 : }
1394 9 : p += n - 1;
1395 : }
1396 : }
1397 : return 0;
1398 : }
1399 :
1400 : // Copies the PRINTUSASCII bytes (0x21 to 0x7e) of raw into out, dropping every
1401 : // other byte, for the syslog APP-NAME and HOSTNAME fields. An empty result
1402 : // becomes "-". outsz may be 0 (nothing is written); the loop bound is written
1403 : // as i + 1 < outsz so it can't underflow.
1404 3044 : static void sanitize_syslog_printusascii_field(const char *raw, char *out,
1405 : size_t outsz) {
1406 3044 : if (outsz == 0) return;
1407 : size_t i = 0;
1408 32244 : for (const char *p = raw; *p && i + 1 < outsz; p++) {
1409 29201 : unsigned char c = (unsigned char)*p;
1410 29201 : if (c < 0x21 || c > 0x7e) continue;
1411 29196 : out[i++] = (char)c;
1412 : }
1413 3043 : if (i == 0 && outsz >= 2) {
1414 3 : out[0] = '-';
1415 3 : i = 1;
1416 : }
1417 3043 : out[i] = '\0';
1418 : }
1419 :
1420 : // Gives the short program name the platform reports, or NULL.
1421 1734 : static const char *raw_progname(void) {
1422 : #if defined(__linux__)
1423 1734 : if (program_invocation_short_name && program_invocation_short_name[0])
1424 : return program_invocation_short_name;
1425 : #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__)
1426 : const char *p = getprogname();
1427 : if (p && p[0]) return p;
1428 : #endif
1429 : return NULL;
1430 : }
1431 :
1432 : // Gives the program name for APP-NAME, or "-".
1433 1518 : static const char *syslog_appname_compute(void) {
1434 1518 : const char *p = raw_progname();
1435 : return p ? p : "-";
1436 : }
1437 :
1438 : // Gives the program name for the proc field, or "unknown".
1439 216 : static const char *get_progname(void) {
1440 216 : const char *p = raw_progname();
1441 : return p ? p : "unknown";
1442 : }
1443 :
1444 : // Gives the calling thread's OS thread ID for the identity cache, so a record's
1445 : // tid matches what ps(1) shows. Where the platform has none, the pthread handle
1446 : // stands in: Unique per thread, but not what the tools show.
1447 199 : static pid_t get_tid(void) {
1448 : #if defined(__linux__)
1449 397 : return (pid_t)syscall(SYS_gettid);
1450 : #elif defined(__APPLE__)
1451 : uint64_t tid64 = 0;
1452 : ccol__get_thread_id_np(NULL, &tid64);
1453 : return (pid_t)tid64;
1454 : #elif defined(__FreeBSD__)
1455 : return (pid_t)ccol__get_own_thread_os_id_np();
1456 : #elif defined(__OpenBSD__)
1457 : return getthrid();
1458 : #else
1459 : return (pid_t)(uintptr_t)ccol__get_thread_id();
1460 : #endif
1461 : }
1462 :
1463 : // Copies the calling thread's name into buf (at most bufsz - 1 characters) for
1464 : // the identity cache. An unnamed thread reads as the program name, as it does
1465 : // on Linux.
1466 198 : static void get_thread_name(char *buf, size_t bufsz) {
1467 : #if defined(__linux__)
1468 198 : char name[16];
1469 198 : if (prctl(PR_GET_NAME, name) == 0 && name[0]) {
1470 199 : snprintf(buf, bufsz, "%s", name);
1471 199 : return;
1472 : }
1473 : #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__)
1474 : if (ccol__get_thread_name_np(ccol__get_thread_id(), buf, bufsz) == 0 &&
1475 : buf[0])
1476 : return;
1477 : snprintf(buf, bufsz, "%.15s", get_progname());
1478 : return;
1479 : #endif
1480 0 : snprintf(buf, bufsz, "unknown");
1481 : }
1482 :
1483 : // Thread identity cache. Each record names its writer as
1484 : // "<progname>(<pid>):<thread name>(<tid>)". A thread reads those once, on its
1485 : // first record, into a heap block reached through a thread-local pointer, so
1486 : // later records make no system call. A fork child handler invalidates the
1487 : // cache, and ccol_set_thread_name() updates it; a rename by any other means
1488 : // isn't seen. A key destructor frees the block at thread exit. The block is on
1489 : // the heap so the library's static TLS stays small for dlopen().
1490 : // CLOG_THREAD_NAME_LIMIT is the longest name the kernel keeps.
1491 : #define CLOG_PROC_VAL_LEN 256
1492 : #define CLOG_THREAD_NAME_LIMIT 15
1493 :
1494 : // One thread's cached identity; proc holds the formatted string.
1495 : typedef struct {
1496 : bool valid;
1497 : pid_t pid;
1498 : pid_t tid;
1499 : char name[CLOG_THREAD_NAME_LIMIT + 1];
1500 : char proc[CLOG_PROC_VAL_LEN];
1501 : } clog_thread_ident;
1502 :
1503 : // The calling thread's cache, initial-exec where allowed so a record reads it
1504 : // with no call.
1505 : #if defined(CMEMPOOL_DYNAMIC_TLS) && CMEMPOOL_DYNAMIC_TLS
1506 : static __thread clog_thread_ident *clog_tident;
1507 : #else
1508 : static __thread clog_thread_ident *clog_tident
1509 : __attribute__((tls_model("initial-exec")));
1510 : #endif
1511 :
1512 : // Guards the key creation and the fork handler registration.
1513 : static ccol__once_flag clog_tident_once = CCOL__ONCE_INIT;
1514 :
1515 : // Identity of a record whose thread couldn't allocate its cache.
1516 : static const clog_thread_ident clog_tident_unknown = {
1517 : .valid = true, .pid = 0, .tid = 0, .name = "", .proc = "unknown"};
1518 :
1519 : // The key whose destructor frees an exiting thread's cache. The module
1520 : // destructor deletes it under the write lock of clog_tident_rwlock, and a
1521 : // thread sets it under the read lock after checking clog_tident_key_live, so a
1522 : // set never hits a deleted key. clog_tident_key_live stays false when the key
1523 : // or lock couldn't be created.
1524 : static ccol__thread_ls_key clog_tident_key;
1525 : static ccol__rw_lock clog_tident_rwlock;
1526 : static atomic_bool clog_tident_key_live;
1527 :
1528 : // Set by the module destructor. A record after it gets clog_tident_late, one
1529 : // identity for the process with no thread part, because no destructor is left
1530 : // to free a new cache.
1531 : static atomic_bool clog_tident_finalized;
1532 : static clog_thread_ident clog_tident_late;
1533 : static ccol__once_flag clog_tident_late_once = CCOL__ONCE_INIT;
1534 :
1535 : #ifdef RUNNING_UNIT_TESTS
1536 :
1537 : // How many times the calling thread read its identity from the system.
1538 : static __thread unsigned clog_test_tident_fills;
1539 :
1540 : // Gives how many times the calling thread read its identity from the system, so
1541 : // a test can check the cache.
1542 4 : unsigned clog__test_thread_identity_fill_count(void) {
1543 4 : return clog_test_tident_fills;
1544 : }
1545 :
1546 : // Gives the calling thread's identity block, or NULL, so a test can check that
1547 : // a block is reused and not leaked.
1548 3 : const void *clog__test_thread_identity_block(void) { return clog_tident; }
1549 :
1550 : // Clears the calling thread's identity pointer while the key keeps the block,
1551 : // which is what macOS does before key destructors run, so a test can run that
1552 : // path anywhere.
1553 1 : void clog__test_forget_thread_identity_pointer(void) { clog_tident = NULL; }
1554 :
1555 : static void clog_tident_fini(void);
1556 :
1557 : // Runs the identity cache's module destructor now, so a test can check the
1558 : // records logged after it.
1559 1 : void clog__test_run_identity_fini(void) { clog_tident_fini(); }
1560 : #endif
1561 :
1562 : // Marks the calling thread's identity cache stale in a fork child, which has a
1563 : // new pid and tid, so the child's records name the child. It takes no lock, so
1564 : // its place among other handlers doesn't matter.
1565 0 : static void clog_tident_atfork_child(void) {
1566 0 : if (clog_tident) clog_tident->valid = false;
1567 0 : }
1568 :
1569 : // Frees an exiting thread's identity cache (arg); it's the destructor of
1570 : // clog_tident_key, so a thread that ends doesn't leak its cache.
1571 120 : static void clog_tident_free(void *arg) {
1572 120 : free(arg);
1573 120 : clog_tident = NULL;
1574 120 : }
1575 :
1576 : // Registers the identity cache's fork child handler and creates its rwlock and
1577 : // key, once. A failed registration only leaves a forked child with the parent's
1578 : // identity.
1579 11 : static void clog_tident_register_atfork(void) {
1580 11 : (void)ccol__at_fork(NULL, NULL, clog_tident_atfork_child);
1581 11 : if (ccol__rw_lock_init(clog_tident_rwlock) != 0) return;
1582 11 : if (ccol__thread_ls_key_create(clog_tident_key, clog_tident_free) != 0)
1583 : return;
1584 11 : atomic_store(&clog_tident_key_live, true);
1585 : }
1586 :
1587 : // See CCOL__ATFORK_AT_LOAD in common.h.
1588 : #if defined(CCOL__ATFORK_AT_LOAD)
1589 : __attribute__((constructor)) static void clog_atfork_at_load(void) {
1590 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
1591 : ccol__call_once(clog_tident_once, clog_tident_register_atfork);
1592 : }
1593 : #endif
1594 :
1595 : // At unload and exit: Frees the calling thread's cache, which no key destructor
1596 : // frees for the thread that ends the process, and deletes the key so no thread
1597 : // exiting after a dlclose() calls into unmapped code.
1598 94 : __attribute__((destructor)) static void clog_tident_fini(void) {
1599 94 : atomic_store(&clog_tident_finalized, true);
1600 94 : free(clog_tident);
1601 94 : clog_tident = NULL;
1602 94 : if (!atomic_load(&clog_tident_key_live)) return;
1603 57 : ccol__rw_lock_wrlock(clog_tident_rwlock);
1604 57 : atomic_store(&clog_tident_key_live, false);
1605 57 : ccol__thread_ls_key_delete(clog_tident_key);
1606 57 : ccol__rw_lock_unlock(clog_tident_rwlock);
1607 : }
1608 :
1609 : // Formats ti->proc, the identity string every record carries, from the other
1610 : // fields of ti.
1611 203 : static void clog_tident_format(clog_thread_ident *ti) {
1612 203 : if (snprintf(ti->proc, sizeof(ti->proc), "%.200s(%d):%.15s(%d)",
1613 203 : get_progname(), (int)ti->pid, ti->name, (int)ti->tid) < 0)
1614 0 : ti->proc[0] = '\0';
1615 203 : }
1616 :
1617 : // Fills clog_tident_late, once, for the records logged after the module
1618 : // destructor.
1619 13 : static void clog_tident_late_init(void) {
1620 13 : clog_tident_late.pid = getpid();
1621 13 : clog_tident_late.tid = 0;
1622 13 : clog_tident_late.name[0] = '\0';
1623 26 : if (snprintf(clog_tident_late.proc, sizeof(clog_tident_late.proc),
1624 : "%.200s(%d)", get_progname(), (int)clog_tident_late.pid) < 0)
1625 0 : clog_tident_late.proc[0] = '\0';
1626 13 : clog_tident_late.valid = true;
1627 13 : }
1628 :
1629 : // Reads the calling thread's identity from the system and caches it; out of
1630 : // line since a thread runs it once. The key's value owns the cache: macOS frees
1631 : // __thread storage before key destructors run, so a record logged from another
1632 : // destructor finds clog_tident NULL and takes the block back from the key
1633 : // instead of leaking it with a new one.
1634 : static __attribute__((noinline, cold)) const clog_thread_ident *
1635 217 : clog_tident_fill(void) {
1636 217 : ccol__call_once(clog_tident_once, clog_tident_register_atfork);
1637 217 : clog_thread_ident *ti = clog_tident;
1638 217 : if (!ti && atomic_load(&clog_tident_key_live)) {
1639 142 : ccol__rw_lock_rdlock(clog_tident_rwlock);
1640 142 : if (atomic_load(&clog_tident_key_live))
1641 141 : ti = ccol__thread_ls_get(clog_tident_key);
1642 143 : ccol__rw_lock_unlock(clog_tident_rwlock);
1643 142 : if (ti) clog_tident = ti;
1644 : }
1645 159 : if (!ti && atomic_load(&clog_tident_finalized)) {
1646 18 : ccol__call_once(clog_tident_late_once, clog_tident_late_init);
1647 18 : return &clog_tident_late;
1648 : }
1649 199 : if (!ti) {
1650 141 : ti = malloc(sizeof(*ti));
1651 141 : if (!ti) return &clog_tident_unknown;
1652 141 : if (atomic_load(&clog_tident_key_live)) {
1653 141 : ccol__rw_lock_rdlock(clog_tident_rwlock);
1654 141 : if (atomic_load(&clog_tident_key_live))
1655 141 : (void)ccol__thread_ls_set(clog_tident_key, ti);
1656 141 : ccol__rw_lock_unlock(clog_tident_rwlock);
1657 : }
1658 141 : clog_tident = ti;
1659 : }
1660 : #ifdef RUNNING_UNIT_TESTS
1661 199 : clog_test_tident_fills++;
1662 : #endif
1663 199 : ti->pid = getpid();
1664 199 : ti->tid = get_tid();
1665 198 : get_thread_name(ti->name, sizeof(ti->name));
1666 199 : clog_tident_format(ti);
1667 197 : ti->valid = true;
1668 197 : return ti;
1669 : }
1670 :
1671 : // Gives the calling thread's cached identity for a record, filling the cache
1672 : // first when it's missing or stale. The pointer is valid while the thread runs,
1673 : // and only that thread may read it.
1674 41619 : static inline const clog_thread_ident *clog_tident_get(void) {
1675 41619 : const clog_thread_ident *ti = clog_tident;
1676 41619 : if (__builtin_expect(!ti || !ti->valid, 0)) return clog_tident_fill();
1677 : return ti;
1678 : }
1679 :
1680 : // Renames the calling thread (cut to the 15 bytes every platform keeps) and
1681 : // updates its identity cache, so its later records carry the new name; a rename
1682 : // by other means isn't seen by the cache.
1683 11 : ccol_retval ccol_set_thread_name(const char *thread_name) {
1684 11 : if (!thread_name || thread_name[0] == '\0') return ccol_invalid_args;
1685 : #if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) || \
1686 : defined(__OpenBSD__)
1687 9 : char name[CLOG_THREAD_NAME_LIMIT + 1];
1688 9 : size_t n = strnlen(thread_name, CLOG_THREAD_NAME_LIMIT);
1689 9 : memcpy(name, thread_name, n);
1690 9 : name[n] = '\0';
1691 : #if defined(__linux__)
1692 9 : if (prctl(PR_SET_NAME, name) != 0) return ccol_not_permitted;
1693 : #else
1694 : if (ccol__set_own_thread_name_np(name) != 0) return ccol_not_permitted;
1695 : #endif
1696 9 : clog_thread_ident *ti = clog_tident;
1697 9 : if (!ti || !ti->valid) {
1698 5 : (void)clog_tident_fill();
1699 : } else {
1700 4 : memcpy(ti->name, name, n + 1);
1701 4 : clog_tident_format(ti);
1702 : }
1703 : return ccol_success;
1704 : #else
1705 : return ccol_not_permitted;
1706 : #endif
1707 : }
1708 :
1709 : #ifdef RUNNING_UNIT_TESTS
1710 :
1711 : // Each of the next clog_test_write_cap_uses writes takes at most this many
1712 : // bytes, so a test can make a short write without a real resource limit.
1713 : static _Atomic size_t clog_test_write_cap = 0;
1714 : static _Atomic unsigned int clog_test_write_cap_uses = 0;
1715 :
1716 : // Takes one capped write, for the write loops of a test build. Gives the cap,
1717 : // or 0 when none is armed.
1718 23368 : static size_t clog_test_consume_next_write_cap(void) {
1719 23368 : unsigned int uses = atomic_load(&clog_test_write_cap_uses);
1720 23368 : while (uses > 0) {
1721 13 : if (atomic_compare_exchange_weak(&clog_test_write_cap_uses, &uses,
1722 : uses - 1))
1723 13 : return atomic_load(&clog_test_write_cap);
1724 : }
1725 : return 0;
1726 : }
1727 :
1728 : // Caps each of the next write_count writes at accepted_bytes, so a test can
1729 : // make short writes without a real resource limit.
1730 8 : void clog__test_force_short_writes(size_t accepted_bytes,
1731 : unsigned int write_count) {
1732 8 : atomic_store(&clog_test_write_cap, accepted_bytes);
1733 8 : atomic_store(&clog_test_write_cap_uses, accepted_bytes ? write_count : 0u);
1734 8 : }
1735 :
1736 : // Each of the next clog_test_write_error_uses writes fails with this errno
1737 : // before writing a byte.
1738 : static _Atomic int clog_test_write_error = 0;
1739 : static _Atomic unsigned int clog_test_write_error_uses = 0;
1740 :
1741 : // Takes one forced write error, for the write loops of a test build. Gives the
1742 : // errno, or 0 when none is armed.
1743 23388 : static int clog_test_consume_next_write_error(void) {
1744 23388 : unsigned int uses = atomic_load(&clog_test_write_error_uses);
1745 23388 : while (uses > 0) {
1746 20 : if (atomic_compare_exchange_weak(&clog_test_write_error_uses, &uses,
1747 : uses - 1))
1748 20 : return atomic_load(&clog_test_write_error);
1749 : }
1750 : return 0;
1751 : }
1752 :
1753 : // Makes each of the next write_count writes fail with err before writing, so a
1754 : // test can check how each error class is handled.
1755 21 : void clog__test_force_write_errors(int err, unsigned int write_count) {
1756 21 : atomic_store(&clog_test_write_error, err);
1757 21 : atomic_store(&clog_test_write_error_uses, err ? write_count : 0u);
1758 21 : }
1759 :
1760 : // A simulated full output: While clog_test_room_err isn't 0, writes take bytes
1761 : // until clog_test_room runs out, and then fail with that errno. After
1762 : // clog_test_room_refusals refused writes the output has room again (0 keeps it
1763 : // full).
1764 : static _Atomic int clog_test_room_err = 0;
1765 : static _Atomic size_t clog_test_room = 0;
1766 : static _Atomic unsigned int clog_test_room_refusals = 0;
1767 :
1768 : // Simulates an output with room bytes left that fails with err once full, until
1769 : // refusals writes have been refused, so a test can reproduce a full disk; err 0
1770 : // turns it off.
1771 30 : void clog__test_set_output_room(int err, size_t room, unsigned int refusals) {
1772 30 : atomic_store(&clog_test_room, room);
1773 30 : atomic_store(&clog_test_room_refusals, refusals);
1774 30 : atomic_store(&clog_test_room_err, err);
1775 30 : }
1776 :
1777 : // Applies the simulated full output to a write of len bytes, for the write
1778 : // loops of a test build. Gives how many bytes it takes; *err is its errno when
1779 : // that's fewer than len, and 0 otherwise.
1780 23368 : static size_t clog_test_room_clip(size_t len, int *err) {
1781 23368 : int e = atomic_load(&clog_test_room_err);
1782 23368 : *err = 0;
1783 23368 : if (e == 0) return len;
1784 1029 : size_t room = atomic_load(&clog_test_room);
1785 1029 : for (;;) {
1786 1029 : size_t take = len < room ? len : room;
1787 1029 : if (atomic_compare_exchange_weak(&clog_test_room, &room, room - take)) {
1788 1029 : if (take < len) {
1789 1028 : *err = e;
1790 1028 : unsigned int r = atomic_load(&clog_test_room_refusals);
1791 1028 : if (r == 1) atomic_store(&clog_test_room_err, 0);
1792 1028 : if (r > 0) atomic_store(&clog_test_room_refusals, r - 1);
1793 : }
1794 1029 : return take;
1795 : }
1796 : }
1797 : }
1798 :
1799 : // While set, a socket sink is classified as a pipe, the path of a system
1800 : // without MSG_NOSIGNAL.
1801 : static _Atomic bool clog_test_sockets_as_pipes = false;
1802 :
1803 : // Turns the classification of sockets as pipes on or off, so a test can run the
1804 : // path of a system without MSG_NOSIGNAL.
1805 1 : void clog__test_classify_sockets_as_pipes(bool on) {
1806 1 : atomic_store(&clog_test_sockets_as_pipes, on);
1807 1 : }
1808 :
1809 : // Tells clog_classify_sink() whether to treat a socket as a pipe, which a test
1810 : // sets to run the path of a system without MSG_NOSIGNAL.
1811 13 : static bool clog_test_socket_is_pipe(void) {
1812 13 : return atomic_load(&clog_test_sockets_as_pipes);
1813 : }
1814 : #else
1815 :
1816 : // Stubs of a non-test build, so the write loops need no #ifdef: None of the
1817 : // write hooks does anything.
1818 : static inline bool clog_test_socket_is_pipe(void) { return false; }
1819 : static inline size_t clog_test_consume_next_write_cap(void) { return 0; }
1820 : static inline int clog_test_consume_next_write_error(void) { return 0; }
1821 : static inline size_t clog_test_room_clip(size_t len, int *err) {
1822 : *err = 0;
1823 : return len;
1824 : }
1825 : #endif
1826 :
1827 : // Signal handling of writes. EPIPE on a pipe or socket raises SIGPIPE, and a
1828 : // write past RLIMIT_FSIZE raises SIGXFSZ; both kill by default. A socket is
1829 : // written with MSG_NOSIGNAL under every policy. Under CLOG_SIGNALS_AUTO the
1830 : // async writer and compressor threads keep both signals blocked and consume the
1831 : // ones their own writes raise; another thread's first pipe write sets SIGPIPE
1832 : // to SIG_IGN, and opening a regular file sets SIGXFSZ to SIG_IGN, each once and
1833 : // only while the disposition is SIG_DFL. The open is the right moment for
1834 : // SIGXFSZ, because a record ending exactly at the limit makes the next write
1835 : // fail with no short write first. Under CLOG_SIGNALS_UNTOUCHED nothing changes
1836 : // and each write raises what the kernel raises.
1837 : #if defined(MSG_NOSIGNAL)
1838 : #define CLOG_HAS_MSG_NOSIGNAL 1
1839 : #else
1840 : #define CLOG_HAS_MSG_NOSIGNAL 0
1841 : #endif
1842 :
1843 : // What a target's fd is. CLOG_SINK_FATAL_BOUND is a flag a CLOG_FATAL call
1844 : // adds, under the mutex, to a sink that isn't a regular file, so every later
1845 : // write ends by clog_fatal_deadline. PLAIN with that flag is a terminal or
1846 : // other device.
1847 : typedef enum {
1848 : CLOG_SINK_PLAIN = 0,
1849 : CLOG_SINK_PIPE = 1,
1850 : CLOG_SINK_SOCKET = 2,
1851 : CLOG_SINK_FATAL_BOUND = 4,
1852 : } clog_sink_kind;
1853 :
1854 : // The policy clog_set_signal_policy() sets. Read relaxed, since nothing else is
1855 : // ordered by it.
1856 : static _Atomic int clog_signal_policy_value = CLOG_SIGNALS_AUTO;
1857 :
1858 : // The once of the SIGPIPE ignore, and a flag so later pipe writes skip the
1859 : // call.
1860 : static ccol__once_flag clog_sigpipe_once = CCOL__ONCE_INIT;
1861 : static atomic_bool clog_sigpipe_once_done;
1862 :
1863 : // The same for SIGXFSZ, which the open of a regular file sets.
1864 : static ccol__once_flag clog_sigxfsz_once = CCOL__ONCE_INIT;
1865 : static atomic_bool clog_sigxfsz_once_done;
1866 :
1867 : // Bits of clog_sig_thread. Only this module's writer and compressor threads
1868 : // (CLOG_SIGT_OWN) set them, recording for each signal whether the module
1869 : // blocked it or the thread inherited it blocked.
1870 : enum {
1871 : CLOG_SIGT_OWN = 1,
1872 : CLOG_SIGT_PIPE_BLOCKED = 2,
1873 : CLOG_SIGT_PIPE_INHERITED = 4,
1874 : CLOG_SIGT_XFSZ_BLOCKED = 8,
1875 : CLOG_SIGT_XFSZ_INHERITED = 16
1876 : };
1877 :
1878 : // The calling thread's signal bits, initial-exec where allowed because every
1879 : // pipe write reads it.
1880 : #if defined(CMEMPOOL_DYNAMIC_TLS) && CMEMPOOL_DYNAMIC_TLS
1881 : static __thread unsigned char clog_sig_thread;
1882 : #else
1883 : static __thread unsigned char clog_sig_thread
1884 : __attribute__((tls_model("initial-exec")));
1885 : #endif
1886 :
1887 : // Sets sig to SIG_IGN when it's SIG_DFL, the process-wide step of the AUTO
1888 : // signal policy. A handler or ignore the application installed stays, since
1889 : // that's the application's choice.
1890 15 : static void clog_ignore_if_default(int sig) {
1891 15 : struct sigaction cur;
1892 19 : if (sigaction(sig, NULL, &cur) != 0) return;
1893 15 : if ((cur.sa_flags & SA_SIGINFO) || cur.sa_handler != SIG_DFL) return;
1894 11 : struct sigaction ign;
1895 11 : memset(&ign, 0, sizeof(ign));
1896 11 : ign.sa_handler = SIG_IGN;
1897 11 : sigemptyset(&ign.sa_mask);
1898 11 : (void)sigaction(sig, &ign, NULL);
1899 : }
1900 :
1901 : // The bodies of the two once flags, which apply the process-wide ignore of
1902 : // SIGPIPE and SIGXFSZ.
1903 6 : static void clog_ignore_sigpipe(void) { clog_ignore_if_default(SIGPIPE); }
1904 9 : static void clog_ignore_sigxfsz(void) { clog_ignore_if_default(SIGXFSZ); }
1905 :
1906 : // Runs the SIGXFSZ ignore once and marks it done, so later regular-file opens
1907 : // skip the call. Out of line since it's cold.
1908 9 : static __attribute__((noinline, cold)) void clog_ignore_sigxfsz_once(void) {
1909 9 : ccol__call_once(clog_sigxfsz_once, clog_ignore_sigxfsz);
1910 9 : atomic_store_explicit(&clog_sigxfsz_once_done, true, memory_order_relaxed);
1911 9 : }
1912 :
1913 : // Applies the SIGXFSZ ignore under CLOG_SIGNALS_AUTO when a logger starts
1914 : // writing a regular file (its open, or a rotation's next file), so a write at
1915 : // RLIMIT_FSIZE fails with EFBIG instead of killing the process.
1916 2638 : static inline void clog_file_sink_prepare(void) {
1917 2638 : if (atomic_load_explicit(&clog_signal_policy_value, memory_order_relaxed) ==
1918 2638 : CLOG_SIGNALS_AUTO &&
1919 2638 : !atomic_load_explicit(&clog_sigxfsz_once_done, memory_order_relaxed))
1920 9 : clog_ignore_sigxfsz_once();
1921 2638 : }
1922 :
1923 : // fd's clog_sink_kind; it also prepares the signal state for a regular file. A
1924 : // descriptor fstat() can't read is PLAIN (its writes fail with EBADF). Without
1925 : // MSG_NOSIGNAL a socket is a pipe.
1926 3555 : static unsigned char clog_classify_sink(int fd) {
1927 3555 : struct stat st;
1928 3555 : if (fstat(fd, &st) != 0) return CLOG_SINK_PLAIN;
1929 3555 : if (S_ISFIFO(st.st_mode)) return CLOG_SINK_PIPE;
1930 2681 : if (S_ISSOCK(st.st_mode))
1931 13 : return CLOG_HAS_MSG_NOSIGNAL && !clog_test_socket_is_pipe()
1932 : ? CLOG_SINK_SOCKET
1933 13 : : CLOG_SINK_PIPE;
1934 2668 : if (S_ISREG(st.st_mode)) clog_file_sink_prepare();
1935 : return CLOG_SINK_PLAIN;
1936 : }
1937 :
1938 : // Tells whether fd is a message socket (SOCK_DGRAM, SOCK_SEQPACKET, SOCK_RDM),
1939 : // which keeps the boundary of each write, so the async writer gives it one
1940 : // record per write instead of a batch.
1941 3555 : static bool clog_sink_is_message(int fd) {
1942 3555 : int type = 0;
1943 3555 : socklen_t type_len = sizeof(type);
1944 3555 : if (getsockopt(fd, SOL_SOCKET, SO_TYPE, &type, &type_len) != 0) return false;
1945 13 : if (type == SOCK_DGRAM || type == SOCK_SEQPACKET) return true;
1946 : #if defined(SOCK_RDM)
1947 5 : if (type == SOCK_RDM) return true;
1948 : #endif
1949 : return false;
1950 : }
1951 :
1952 : // Changes the calling module thread's mask so the module blocks exactly the
1953 : // signals in want (CLOG_SIGT_*_BLOCKED bits), which is how the writer and
1954 : // compressor threads follow the policy. It records the result in
1955 : // clog_sig_thread.
1956 343 : static __attribute__((noinline, cold)) void clog_thread_set_signal_mask(
1957 : unsigned char want) {
1958 343 : unsigned char st = clog_sig_thread;
1959 343 : unsigned char cur = st & (CLOG_SIGT_PIPE_BLOCKED | CLOG_SIGT_XFSZ_BLOCKED);
1960 343 : unsigned char add = want & (unsigned char)~cur;
1961 343 : unsigned char drop = cur & (unsigned char)~want;
1962 343 : sigset_t set;
1963 343 : if (add != 0) {
1964 342 : sigemptyset(&set);
1965 342 : if (add & CLOG_SIGT_PIPE_BLOCKED) sigaddset(&set, SIGPIPE);
1966 342 : if (add & CLOG_SIGT_XFSZ_BLOCKED) sigaddset(&set, SIGXFSZ);
1967 342 : if (ccol__thread_sigmask(SIG_BLOCK, &set, NULL) == 0) st |= add;
1968 : }
1969 343 : if (drop != 0) {
1970 1 : sigemptyset(&set);
1971 1 : if (drop & CLOG_SIGT_PIPE_BLOCKED) sigaddset(&set, SIGPIPE);
1972 1 : if (drop & CLOG_SIGT_XFSZ_BLOCKED) sigaddset(&set, SIGXFSZ);
1973 1 : if (ccol__thread_sigmask(SIG_UNBLOCK, &set, NULL) == 0)
1974 1 : st &= (unsigned char)~drop;
1975 : }
1976 343 : clog_sig_thread = st;
1977 343 : }
1978 :
1979 : // Brings a writer or compressor thread's mask in line with the policy: Both
1980 : // signals blocked under AUTO, as inherited under UNTOUCHED. It unblocks only
1981 : // what the module blocked, and the module never leaves its own signal pending,
1982 : // so an unblock delivers nothing.
1983 28683 : static inline void clog_thread_sync_signal_mask(void) {
1984 28683 : unsigned char st = clog_sig_thread;
1985 28683 : unsigned char want = 0;
1986 28683 : if (atomic_load_explicit(&clog_signal_policy_value, memory_order_relaxed) ==
1987 : CLOG_SIGNALS_AUTO) {
1988 28677 : if (!(st & CLOG_SIGT_PIPE_INHERITED)) want |= CLOG_SIGT_PIPE_BLOCKED;
1989 28677 : if (!(st & CLOG_SIGT_XFSZ_INHERITED)) want |= CLOG_SIGT_XFSZ_BLOCKED;
1990 : }
1991 28683 : if ((st & (CLOG_SIGT_PIPE_BLOCKED | CLOG_SIGT_XFSZ_BLOCKED)) == want) return;
1992 343 : clog_thread_set_signal_mask(want);
1993 : }
1994 :
1995 : // Marks the calling thread as one of the module's writer or compressor threads
1996 : // in clog_sig_thread and applies the current policy to its mask; the first
1997 : // statement of those threads.
1998 345 : static __attribute__((noinline, cold)) void clog_thread_signal_init(void) {
1999 345 : unsigned char st = CLOG_SIGT_OWN;
2000 345 : sigset_t cur;
2001 345 : sigemptyset(&cur);
2002 345 : if (ccol__thread_sigmask(SIG_BLOCK, NULL, &cur) == 0) {
2003 345 : if (sigismember(&cur, SIGPIPE) == 1) st |= CLOG_SIGT_PIPE_INHERITED;
2004 345 : if (sigismember(&cur, SIGXFSZ) == 1) st |= CLOG_SIGT_XFSZ_INHERITED;
2005 : }
2006 345 : clog_sig_thread = st;
2007 345 : clog_thread_sync_signal_mask();
2008 345 : }
2009 :
2010 : // Runs the SIGPIPE ignore once and marks it done, so later pipe writes skip the
2011 : // call. Out of line since it's cold.
2012 6 : static __attribute__((noinline, cold)) void clog_ignore_sigpipe_once(void) {
2013 6 : ccol__call_once(clog_sigpipe_once, clog_ignore_sigpipe);
2014 6 : atomic_store_explicit(&clog_sigpipe_once_done, true, memory_order_relaxed);
2015 6 : }
2016 :
2017 : // Prepares the signal state before every pipe write, so EPIPE can't kill the
2018 : // process: A module thread syncs its own mask, any other thread applies the
2019 : // process-wide SIGPIPE ignore under AUTO.
2020 195 : static inline void clog_pipe_write_prepare(void) {
2021 195 : if (clog_sig_thread != 0) {
2022 62 : clog_thread_sync_signal_mask();
2023 62 : return;
2024 : }
2025 133 : if (atomic_load_explicit(&clog_signal_policy_value, memory_order_relaxed) ==
2026 131 : CLOG_SIGNALS_AUTO &&
2027 131 : !atomic_load_explicit(&clog_sigpipe_once_done, memory_order_relaxed))
2028 6 : clog_ignore_sigpipe_once();
2029 : }
2030 :
2031 : #if defined(F_SETNOSIGPIPE)
2032 :
2033 : // macOS raises a pipe's SIGPIPE on the whole process, so the writer thread sets
2034 : // F_SETNOSIGPIPE on fd for the length of a write under AUTO. begin returns the
2035 : // value to restore, or -1 when it changed nothing; end restores it.
2036 : static int clog_pipe_nosigpipe_begin(int fd) {
2037 : if (clog_sig_thread == 0 ||
2038 : atomic_load_explicit(&clog_signal_policy_value, memory_order_relaxed) !=
2039 : CLOG_SIGNALS_AUTO)
2040 : return -1;
2041 : int prev = fcntl(fd, F_GETNOSIGPIPE);
2042 : if (prev != 0) return -1;
2043 : return fcntl(fd, F_SETNOSIGPIPE, 1) == 0 ? 0 : -1;
2044 : }
2045 :
2046 : static void clog_pipe_nosigpipe_end(int fd, int prev) {
2047 : if (prev < 0) return;
2048 : int saved_errno = errno;
2049 : (void)fcntl(fd, F_SETNOSIGPIPE, prev);
2050 : errno = saved_errno;
2051 : }
2052 : #endif
2053 :
2054 : // After a write that raised sig for this thread (SIGPIPE after EPIPE, SIGXFSZ
2055 : // after EFBIG), takes every pending instance when the module blocked sig here
2056 : // (bit is its CLOG_SIGT_*_BLOCKED bit), so a later unblock can't deliver it.
2057 : // errno is kept for the caller. macOS and OpenBSD have no sigtimedwait(), so
2058 : // there one instance is directed at the thread and taken with sigwait().
2059 1311 : static __attribute__((noinline, cold)) void clog_consume_own_signal(
2060 : int sig, unsigned char bit) {
2061 1311 : if (!(clog_sig_thread & bit)) return;
2062 1165 : int saved_errno = errno;
2063 1165 : sigset_t set;
2064 1165 : sigemptyset(&set);
2065 1165 : sigaddset(&set, sig);
2066 : #if defined(__APPLE__) || defined(__OpenBSD__)
2067 : sigset_t pending;
2068 : sigemptyset(&pending);
2069 : int got;
2070 : if (sigpending(&pending) == 0 && sigismember(&pending, sig) == 1 &&
2071 : ccol__thread_kill(ccol__get_thread_id(), sig) == 0)
2072 : (void)sigwait(&set, &got);
2073 : #else
2074 1165 : const struct timespec zero = {0, 0};
2075 1187 : for (;;) {
2076 1176 : int got = sigtimedwait(&set, NULL, &zero);
2077 1176 : if (got == sig || (got < 0 && errno == EINTR)) continue;
2078 1165 : break;
2079 : }
2080 : #endif
2081 1165 : errno = saved_errno;
2082 : }
2083 :
2084 : // Consume the SIGPIPE or SIGXFSZ the calling module thread's own failed write
2085 : // left pending; the two users of clog_consume_own_signal().
2086 21 : static inline void clog_consume_own_sigpipe(void) {
2087 21 : clog_consume_own_signal(SIGPIPE, CLOG_SIGT_PIPE_BLOCKED);
2088 21 : }
2089 1290 : static inline void clog_consume_own_sigxfsz(void) {
2090 1290 : clog_consume_own_signal(SIGXFSZ, CLOG_SIGT_XFSZ_BLOCKED);
2091 1290 : }
2092 :
2093 : // Sets the process-wide signal policy, which every later write and module
2094 : // thread reads. Returns ccol_invalid_args for a value outside the enum.
2095 11 : ccol_retval clog_set_signal_policy(clog_signal_policy policy) {
2096 11 : if ((int)policy != CLOG_SIGNALS_AUTO && (int)policy != CLOG_SIGNALS_UNTOUCHED)
2097 : return ccol_invalid_args;
2098 7 : atomic_store_explicit(&clog_signal_policy_value, (int)policy,
2099 : memory_order_relaxed);
2100 7 : return ccol_success;
2101 : }
2102 :
2103 : // poll_timeout_ms of a write that may wait without a bound; every write of a
2104 : // record's own bytes passes it. A recovery step (draining a split record,
2105 : // settling a batch at exit or on the fatal path, a loss marker) passes a bound
2106 : // in milliseconds instead. CLOG_SPLIT_RECORD_DRAIN_WAIT_MS is the bound for the
2107 : // continuation of a split record.
2108 : #define CLOG_WRITE_WAIT_FOREVER (-1)
2109 : #define CLOG_SPLIT_RECORD_DRAIN_WAIT_MS 100
2110 :
2111 : // Gives the poll(2) events that wait for room in fd. On OpenBSD a POLLOUT wait
2112 : // on an anonymous pipe never wakes when the reader closes, so POLLIN is added
2113 : // there to get the POLLHUP.
2114 : static short clog_pollout_events(int fd) {
2115 : #if defined(__OpenBSD__)
2116 : struct stat st;
2117 : if (fstat(fd, &st) == 0 && S_ISFIFO(st.st_mode) && st.st_dev == 0 &&
2118 : st.st_ino == 0)
2119 : return POLLOUT | POLLIN;
2120 : #else
2121 : (void)fd;
2122 : #endif
2123 : return POLLOUT;
2124 : }
2125 :
2126 : #ifdef RUNNING_UNIT_TESTS
2127 :
2128 : // Waits for room on the watched output (named by dev/ino, so the logger's own
2129 : // descriptors for the same pipe count too).
2130 : static _Atomic size_t clog_test_writable_waits_state = 0;
2131 : static _Atomic bool clog_test_writable_watch_set = false;
2132 : static _Atomic uint64_t clog_test_writable_watch_dev = 0;
2133 : static _Atomic uint64_t clog_test_writable_watch_ino = 0;
2134 :
2135 : // Starts counting, from zero, the waits for room on the output behind fd, so a
2136 : // test can see a write wait for a full pipe.
2137 2 : void clog__test_watch_writable(int fd) {
2138 2 : struct stat st;
2139 2 : if (fd < 0 || fstat(fd, &st) != 0) {
2140 1 : atomic_store(&clog_test_writable_watch_set, false);
2141 1 : return;
2142 : }
2143 1 : atomic_store(&clog_test_writable_watch_dev, (uint64_t)st.st_dev);
2144 1 : atomic_store(&clog_test_writable_watch_ino, (uint64_t)st.st_ino);
2145 1 : atomic_store(&clog_test_writable_watch_set, true);
2146 : }
2147 :
2148 : // Gives how many waits for room the watched output has had.
2149 2 : size_t clog__test_writable_waits(void) {
2150 2 : return atomic_load(&clog_test_writable_waits_state);
2151 : }
2152 : #endif
2153 :
2154 : // After EAGAIN, waits without a bound until fd is writable; true when the write
2155 : // should be tried again, false on an error or hangup without POLLOUT. Out of
2156 : // line so the write loop keeps no stack canary.
2157 2 : static __attribute__((noinline)) bool clog_wait_writable(int fd) {
2158 : #ifdef RUNNING_UNIT_TESTS
2159 : {
2160 2 : struct stat st;
2161 2 : if (atomic_load(&clog_test_writable_watch_set) && fstat(fd, &st) == 0 &&
2162 1 : (uint64_t)st.st_dev == atomic_load(&clog_test_writable_watch_dev) &&
2163 1 : (uint64_t)st.st_ino == atomic_load(&clog_test_writable_watch_ino))
2164 1 : atomic_fetch_add(&clog_test_writable_waits_state, 1);
2165 : }
2166 : #endif
2167 2 : struct pollfd pfd = {
2168 : .fd = fd, .events = clog_pollout_events(fd), .revents = 0};
2169 2 : int pr = poll(&pfd, 1, -1);
2170 2 : if (pr < 0 && errno == EINTR) return true;
2171 3 : return pr > 0 && (pfd.revents & POLLOUT);
2172 : }
2173 :
2174 : // Pause after ENOBUFS, which FreeBSD gives for an AF_UNIX datagram socket whose
2175 : // receiver is full (poll still reports POLLOUT). *step_us doubles from 50 us to
2176 : // 10 ms; limit_ms bounds the pause when it isn't negative.
2177 0 : static __attribute__((noinline, cold)) void clog_enobufs_backoff(
2178 : unsigned *step_us, int limit_ms) {
2179 0 : unsigned us = *step_us ? *step_us : 50u;
2180 0 : *step_us = us >= 5000u ? 10000u : us * 2u;
2181 0 : if (limit_ms >= 0 && (long long)us > (long long)limit_ms * 1000LL)
2182 0 : us = (unsigned)limit_ms * 1000u;
2183 0 : struct timespec ts = {.tv_sec = 0, .tv_nsec = (long)us * 1000L};
2184 0 : nanosleep(&ts, NULL);
2185 0 : }
2186 :
2187 : // Writes len bytes of data to fd with no time bound, as kind says (send() for a
2188 : // socket, write() otherwise). It retries after EINTR, a partial write, EAGAIN
2189 : // (after a wait) and ENOBUFS (after a backoff). Returns the bytes written,
2190 : // which can be fewer than len after an unrecoverable error or a write of 0;
2191 : // callers that count bytes for rotation use this, not len. errno holds the
2192 : // failure.
2193 : static inline __attribute__((always_inline)) size_t
2194 23357 : write_all_body(int fd, clog_sink_kind kind, const char *data, size_t len) {
2195 23357 : size_t total = 0;
2196 46714 : int forced_err = clog_test_consume_next_write_error();
2197 23357 : if (forced_err != 0) {
2198 16 : errno = forced_err;
2199 16 : return 0;
2200 : }
2201 23341 : size_t forced_cap = clog_test_consume_next_write_cap();
2202 23341 : if (forced_cap > 0 && forced_cap < len) len = forced_cap;
2203 23341 : int room_err;
2204 6148 : len = clog_test_room_clip(len, &room_err);
2205 23341 : unsigned nobufs_step_us = 0;
2206 45581 : while (len > 0) {
2207 22327 : ssize_t w;
2208 : #if CLOG_HAS_MSG_NOSIGNAL
2209 22327 : if (kind == CLOG_SINK_SOCKET)
2210 6148 : w = send(fd, data, len, MSG_NOSIGNAL);
2211 : else
2212 : #endif
2213 16179 : w = write(fd, data, len);
2214 22317 : if (w < 0) {
2215 78 : if (errno == EINTR) continue;
2216 10 : if (kind == CLOG_SINK_SOCKET && errno == ENOBUFS) {
2217 0 : clog_enobufs_backoff(&nobufs_step_us, -1);
2218 0 : continue;
2219 : }
2220 21 : if (kind == CLOG_SINK_PIPE && errno == EPIPE) {
2221 19 : clog_consume_own_sigpipe();
2222 19 : break;
2223 : }
2224 47 : if (kind == CLOG_SINK_PLAIN && errno == EFBIG) {
2225 47 : clog_consume_own_sigxfsz();
2226 47 : break;
2227 : }
2228 12 : if ((errno == EAGAIN || errno == EWOULDBLOCK) && clog_wait_writable(fd))
2229 1 : continue;
2230 : break;
2231 : }
2232 22239 : if (w == 0) break;
2233 22239 : data += (size_t)w;
2234 22239 : len -= (size_t)w;
2235 22239 : total += (size_t)w;
2236 : }
2237 23331 : if (room_err != 0) errno = room_err;
2238 : return total;
2239 : }
2240 :
2241 : // Writes data to a regular file or any other sink that can't raise SIGPIPE, the
2242 : // common path of write_all(). Returns the bytes written. A regular file can
2243 : // raise SIGXFSZ, which the policy handles.
2244 17026 : static __attribute__((noinline)) size_t write_all_plain(int fd,
2245 : const char *data,
2246 : size_t len) {
2247 17026 : return write_all_body(fd, CLOG_SINK_PLAIN, data, len);
2248 : }
2249 :
2250 : // Set once a CLOG_FATAL call starts, after clog_fatal_deadline is written. A
2251 : // bounded write reads the deadline under the target's mutex.
2252 : static _Atomic bool clog_fatal_bound_armed;
2253 : static struct timespec clog_fatal_deadline;
2254 :
2255 : static __attribute__((noinline, cold)) size_t
2256 : write_all_fatal_bound(clog_shared *sh, const char *data, size_t len);
2257 :
2258 : // Writes data to a pipe or socket sink, or to a sink with
2259 : // CLOG_SINK_FATAL_BOUND, handling the signals each raises, and returns the
2260 : // bytes written. The flag test sits behind the pipe test, so a pipe doesn't pay
2261 : // for it.
2262 6342 : static __attribute__((noinline)) size_t write_all_nonplain(clog_shared *sh,
2263 : const char *data,
2264 : size_t len) {
2265 6342 : if (sh->sink_kind == CLOG_SINK_PIPE) {
2266 181 : clog_pipe_write_prepare();
2267 : #if defined(F_SETNOSIGPIPE)
2268 : int nosig = clog_pipe_nosigpipe_begin(sh->fd);
2269 : size_t n = write_all_body(sh->fd, CLOG_SINK_PIPE, data, len);
2270 : clog_pipe_nosigpipe_end(sh->fd, nosig);
2271 : return n;
2272 : #else
2273 353 : return write_all_body(sh->fd, CLOG_SINK_PIPE, data, len);
2274 : #endif
2275 : }
2276 6161 : if (__builtin_expect(sh->sink_kind != CLOG_SINK_SOCKET, 0))
2277 11 : return write_all_fatal_bound(sh, data, len);
2278 12299 : return write_all_body(sh->fd, CLOG_SINK_SOCKET, data, len);
2279 : }
2280 :
2281 : // Gives the milliseconds until deadline for a poll(2) of a bounded write,
2282 : // rounded up so a wait never ends early, and 0 once it passed.
2283 77 : static int clog_ms_until(const struct timespec *deadline) {
2284 77 : struct timespec now;
2285 77 : clock_gettime(CLOCK_MONOTONIC, &now);
2286 77 : long long ns = (long long)(deadline->tv_sec - now.tv_sec) * 1000000000LL +
2287 77 : (long long)(deadline->tv_nsec - now.tv_nsec);
2288 77 : if (ns <= 0) return 0;
2289 69 : long long ms = (ns + 999999LL) / 1000000LL;
2290 69 : return ms > INT_MAX ? INT_MAX : (int)ms;
2291 : }
2292 :
2293 : // Most a write after POLLOUT gives a terminal that couldn't be reopened
2294 : // non-blocking; a pseudo-terminal takes that much at once.
2295 : #define CLOG_TTY_FALLBACK_CHUNK 128
2296 :
2297 : // Opens the terminal fd again with O_NONBLOCK (through /proc/self/fd, or the
2298 : // ttyname_r() name) and returns the new descriptor, or -1. The flag stays on
2299 : // the new description, so no other holder of the terminal sees it. A pty master
2300 : // is refused, and the device number must match fd's.
2301 3 : static int clog_open_tty_nonblocking(int fd) {
2302 : #if defined(TIOCGPTN)
2303 3 : unsigned int ptn;
2304 3 : if (ioctl(fd, TIOCGPTN, &ptn) == 0) return -1;
2305 : #endif
2306 3 : const int flags = O_WRONLY | O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
2307 3 : char path[sizeof("/proc/self/fd/") + 3 * sizeof(int)];
2308 3 : snprintf(path, sizeof(path), "/proc/self/fd/%d", fd);
2309 3 : int nfd = open(path, flags);
2310 3 : if (nfd >= 0) return nfd;
2311 0 : char name[256];
2312 0 : struct stat want, got;
2313 0 : if (ttyname_r(fd, name, sizeof(name)) != 0 || fstat(fd, &want) != 0)
2314 0 : return -1;
2315 0 : nfd = open(name, flags);
2316 0 : if (nfd < 0) return -1;
2317 0 : if (fstat(nfd, &got) != 0 || got.st_rdev != want.st_rdev) {
2318 0 : close(nfd);
2319 0 : return -1;
2320 : }
2321 : return nfd;
2322 : }
2323 :
2324 : // Writes data for a recovery step, with the contract of write_all_body() but
2325 : // the whole write ends within timeout_ms. A poll timeout alone doesn't bound a
2326 : // blocking write, so a socket is written with ccol_send_nb(), a pipe or FIFO
2327 : // gets at most PIPE_BUF bytes per write after POLLOUT, and a terminal is
2328 : // written through a non-blocking second description. A regular file or block
2329 : // device never waits on a reader and takes the ordinary loop. A message socket
2330 : // gets each record in one write. When the deadline passes, errno is EAGAIN.
2331 79 : static __attribute__((noinline, cold)) size_t write_all_bounded(
2332 : clog_shared *sh, const char *data, size_t len, int timeout_ms) {
2333 79 : int fd = sh->fd;
2334 79 : unsigned char raw_kind = sh->sink_kind;
2335 79 : unsigned char kind = raw_kind & (unsigned char)~CLOG_SINK_FATAL_BOUND;
2336 79 : int wfd = fd;
2337 79 : int own_fd = -1;
2338 79 : size_t chunk = sh->sink_per_record ? SIZE_MAX : PIPE_BUF;
2339 79 : if (kind == CLOG_SINK_PLAIN) {
2340 57 : struct stat st;
2341 57 : if (fstat(fd, &st) == 0) {
2342 57 : if (raw_kind == CLOG_SINK_PLAIN &&
2343 48 : (S_ISREG(st.st_mode) || S_ISBLK(st.st_mode)))
2344 48 : return write_all_plain(fd, data, len);
2345 9 : if (S_ISCHR(st.st_mode) && isatty(fd)) {
2346 3 : own_fd = clog_open_tty_nonblocking(fd);
2347 3 : if (own_fd >= 0) {
2348 : wfd = own_fd;
2349 : chunk = SIZE_MAX;
2350 : } else {
2351 0 : chunk = CLOG_TTY_FALLBACK_CHUNK;
2352 : }
2353 : }
2354 : }
2355 : }
2356 31 : int forced_err = clog_test_consume_next_write_error();
2357 31 : if (forced_err != 0) {
2358 4 : if (own_fd >= 0) close(own_fd);
2359 4 : errno = forced_err;
2360 4 : return 0;
2361 : }
2362 27 : size_t forced_cap = clog_test_consume_next_write_cap();
2363 27 : if (forced_cap > 0 && forced_cap < len) len = forced_cap;
2364 27 : int room_err;
2365 27 : len = clog_test_room_clip(len, &room_err);
2366 27 : if (kind == CLOG_SINK_PIPE) clog_pipe_write_prepare();
2367 : #if defined(F_SETNOSIGPIPE)
2368 : int nosig = kind == CLOG_SINK_PIPE ? clog_pipe_nosigpipe_begin(wfd) : -1;
2369 : #endif
2370 :
2371 27 : struct timespec deadline;
2372 27 : clock_gettime(CLOCK_MONOTONIC, &deadline);
2373 27 : deadline.tv_sec += (time_t)(timeout_ms / 1000);
2374 27 : deadline.tv_nsec += (long)(timeout_ms % 1000) * 1000000L;
2375 27 : if (deadline.tv_nsec >= 1000000000L) {
2376 2 : deadline.tv_sec++;
2377 2 : deadline.tv_nsec -= 1000000000L;
2378 : }
2379 :
2380 27 : size_t total = 0;
2381 27 : unsigned nobufs_step_us = 0;
2382 31 : while (len > 0) {
2383 28 : ssize_t w;
2384 : #if CLOG_HAS_MSG_NOSIGNAL
2385 28 : if (kind == CLOG_SINK_SOCKET) {
2386 8 : w = ccol_send_nb(fd, data, len, MSG_NOSIGNAL);
2387 : } else
2388 : #endif
2389 : {
2390 20 : struct pollfd pfd = {
2391 : .fd = wfd, .events = clog_pollout_events(wfd), .revents = 0};
2392 20 : int pr = poll(&pfd, 1, clog_ms_until(&deadline));
2393 20 : if (pr < 0) {
2394 0 : if (errno == EINTR) continue;
2395 14 : break;
2396 : }
2397 20 : if (pr == 0) {
2398 14 : errno = EAGAIN;
2399 14 : break;
2400 : }
2401 6 : if (pfd.revents & POLLNVAL) {
2402 0 : errno = EBADF;
2403 0 : break;
2404 : }
2405 6 : w = write(wfd, data, len < chunk ? len : chunk);
2406 : }
2407 14 : if (w < 0) {
2408 10 : if (errno == EINTR) continue;
2409 10 : if (kind == CLOG_SINK_PIPE && errno == EPIPE) {
2410 2 : clog_consume_own_sigpipe();
2411 2 : break;
2412 : }
2413 8 : if (kind == CLOG_SINK_SOCKET && errno == ENOBUFS) {
2414 0 : int left = clog_ms_until(&deadline);
2415 0 : if (left > 0) {
2416 0 : clog_enobufs_backoff(&nobufs_step_us, left);
2417 0 : continue;
2418 : }
2419 0 : errno = EAGAIN;
2420 0 : break;
2421 : }
2422 8 : if (errno == EAGAIN || errno == EWOULDBLOCK) {
2423 : #if CLOG_HAS_MSG_NOSIGNAL
2424 8 : if (kind == CLOG_SINK_SOCKET) {
2425 8 : struct pollfd pfd = {.fd = fd, .events = POLLOUT, .revents = 0};
2426 8 : int pr = poll(&pfd, 1, clog_ms_until(&deadline));
2427 8 : if (pr > 0 && (pfd.revents & POLLOUT)) continue;
2428 8 : if (pr < 0 && errno == EINTR) continue;
2429 8 : errno = EAGAIN;
2430 8 : break;
2431 : }
2432 : #endif
2433 0 : if (clog_ms_until(&deadline) > 0) continue;
2434 0 : errno = EAGAIN;
2435 : }
2436 : break;
2437 : }
2438 4 : if (w == 0) break;
2439 4 : data += (size_t)w;
2440 4 : len -= (size_t)w;
2441 4 : total += (size_t)w;
2442 : }
2443 : #if defined(F_SETNOSIGPIPE)
2444 : clog_pipe_nosigpipe_end(wfd, nosig);
2445 : #endif
2446 27 : if (room_err != 0) errno = room_err;
2447 27 : if (own_fd >= 0) {
2448 3 : int saved = errno;
2449 3 : close(own_fd);
2450 3 : errno = saved;
2451 : }
2452 : return total;
2453 : }
2454 :
2455 : // Writes data to a sink with CLOG_SINK_FATAL_BOUND, bounded by
2456 : // clog_fatal_deadline, so a CLOG_FATAL call can't hang on an output that takes
2457 : // nothing. Returns the bytes written.
2458 : static __attribute__((noinline, cold)) size_t
2459 11 : write_all_fatal_bound(clog_shared *sh, const char *data, size_t len) {
2460 11 : return write_all_bounded(sh, data, len, clog_ms_until(&clog_fatal_deadline));
2461 : }
2462 :
2463 : // Writes to sh->fd; see write_all_body() for the contract. The sink kind picks
2464 : // the loop, and a regular file pays one test of a byte next to fd. A bounded
2465 : // write goes to write_all_bounded(); callers on a record's path pass the
2466 : // constant CLOG_WRITE_WAIT_FOREVER, so that test folds away. Needs sh->mutex.
2467 : static inline __attribute__((always_inline)) size_t
2468 23388 : write_all(clog_shared *sh, const char *data, size_t len, int poll_timeout_ms) {
2469 23388 : if (poll_timeout_ms != CLOG_WRITE_WAIT_FOREVER)
2470 68 : return write_all_bounded(sh, data, len, poll_timeout_ms);
2471 1990 : if (__builtin_expect(sh->sink_kind != CLOG_SINK_PLAIN, 0))
2472 6342 : return write_all_nonplain(sh, data, len);
2473 16978 : return write_all_plain(sh->fd, data, len);
2474 : }
2475 :
2476 : // Renders a record the library makes itself (head plus detail at level, in
2477 : // format fmt) into note, with the lead-in nl in front ("\n" when the bytes on
2478 : // disk stop inside a line, else ""), so one write carries both. Returns the
2479 : // length; the text ends with a newline. head and detail are this file's own
2480 : // text and need no escape.
2481 352 : static size_t clog_note_render(const clog_shared *sh, clog_format fmt,
2482 : clog_level level, const char *nl,
2483 : const char *head, const char *detail, char *note,
2484 : size_t cap) {
2485 352 : int n;
2486 352 : if (fmt == CLOG_FMT_JSON) {
2487 6 : n = snprintf(note, cap, "%s{\"level\":\"%s\",\"msg\":\"%s%s\"}\n", nl,
2488 6 : LEVEL_STR[level], head, detail);
2489 346 : } else if (fmt == CLOG_FMT_SYSLOG) {
2490 18 : int pri = (int)sh->syslog_facility * 8 + SYSLOG_SEVERITY[level];
2491 18 : n = snprintf(note, cap, "%s<%d>1 - - - - - - %s%s\n", nl, pri, head,
2492 : detail);
2493 : } else {
2494 328 : n = snprintf(note, cap, "%slevel=%s msg=\"%s%s\"\n", nl, LEVEL_STR[level],
2495 : head, detail);
2496 : }
2497 352 : if (n <= 0) return 0;
2498 352 : if ((size_t)n >= cap) {
2499 0 : note[cap - 2] = '\n';
2500 0 : return cap - 1;
2501 : }
2502 : return (size_t)n;
2503 : }
2504 :
2505 : // Room for a rendered note, and the head of every loss marker.
2506 : #define CLOG_NOTE_CAP 320
2507 :
2508 : #define CLOG_LOSS_HEAD "log record truncated: "
2509 :
2510 : static bool clog_write_error_is_transient(int err);
2511 :
2512 : // Writes what the target owes (see clog_shared.owe_newline) in one write: The
2513 : // newline closing an open line, and one marker naming the unreported losses
2514 : // (the loss's own text for one, totals for more). A partial write is judged by
2515 : // its last byte. It writes nothing while async_buf holds the continuation of a
2516 : // split record. A permanent error such as EPIPE ends the debt. Returns true
2517 : // when the output stands at the start of a line. Needs sh->mutex.
2518 314 : static __attribute__((noinline, cold)) bool clog_pay_owed(clog_shared *sh,
2519 : clog_format fmt,
2520 : int poll_timeout_ms) {
2521 314 : if (!(sh->async_partial_record & CLOG_OWED_REPAIR)) return true;
2522 314 : if (sh->async_partial_record & CLOG_SPLIT_MASK) return !sh->owe_newline;
2523 314 : if (sh->fd < 0) return !sh->owe_newline;
2524 314 : char note[CLOG_NOTE_CAP];
2525 314 : size_t nlen;
2526 314 : const char *nl = sh->owe_newline ? "\n" : "";
2527 314 : if (sh->owed_losses == 0) {
2528 0 : if (!sh->owe_newline) {
2529 0 : sh->async_partial_record &= (unsigned char)~CLOG_OWED_REPAIR;
2530 0 : atomic_store_explicit(&sh->owes_repair, false, memory_order_relaxed);
2531 0 : return true;
2532 : }
2533 0 : note[0] = '\n';
2534 0 : nlen = 1;
2535 314 : } else if (sh->owed_losses == 1) {
2536 94 : nlen = clog_note_render(sh, fmt, CLOG_ERROR, nl, CLOG_LOSS_HEAD,
2537 94 : sh->owed_detail, note, sizeof(note));
2538 : } else {
2539 220 : char detail[160];
2540 220 : if (sh->owed_err != 0)
2541 220 : snprintf(detail, sizeof(detail),
2542 : "%zu earlier losses (records=%zu bytes=%zu): write error %d",
2543 : sh->owed_losses, sh->owed_records, sh->owed_bytes, sh->owed_err);
2544 : else
2545 0 : snprintf(detail, sizeof(detail),
2546 : "%zu earlier losses (records=%zu bytes=%zu)", sh->owed_losses,
2547 : sh->owed_records, sh->owed_bytes);
2548 220 : nlen = clog_note_render(sh, fmt, CLOG_ERROR, nl, CLOG_LOSS_HEAD, detail,
2549 : note, sizeof(note));
2550 : }
2551 314 : if (nlen == 0) return !sh->owe_newline;
2552 314 : errno = 0;
2553 314 : size_t w = write_all(sh, note, nlen, poll_timeout_ms);
2554 313 : int err = errno;
2555 313 : if (sh->rotation_enabled) sh->bytes_written += (off_t)w;
2556 313 : if (w == nlen || !clog_write_error_is_transient(err)) {
2557 43 : sh->owe_newline = false;
2558 43 : sh->owed_losses = 0;
2559 43 : sh->owed_records = 0;
2560 43 : sh->owed_bytes = 0;
2561 43 : sh->owed_err = 0;
2562 43 : sh->async_partial_record &= (unsigned char)~CLOG_OWED_REPAIR;
2563 43 : atomic_store_explicit(&sh->owes_repair, false, memory_order_relaxed);
2564 43 : return true;
2565 : }
2566 270 : if (w > 0) sh->owe_newline = note[w - 1] != '\n';
2567 270 : if (err != 0) sh->owed_err = err;
2568 270 : return !sh->owe_newline;
2569 : }
2570 :
2571 : static void clog_exit_drain_arm(void);
2572 :
2573 : // Adds a loss to the debt (records, bytes, errno, detail text; open_line when
2574 : // the bytes on disk now end inside a line) and tries the repair at once with
2575 : // the bound poll_timeout_ms. It arms the exit drain, so a debt is paid at exit
2576 : // even when nothing writes again. Needs sh->mutex and clear split bits.
2577 108 : static __attribute__((noinline, cold)) void clog_report_loss(
2578 : clog_shared *sh, clog_format fmt, bool open_line, size_t records,
2579 : size_t bytes, int err, const char *detail, int poll_timeout_ms) {
2580 108 : if (open_line) sh->owe_newline = true;
2581 108 : if (sh->owed_losses == 0)
2582 50 : snprintf(sh->owed_detail, sizeof(sh->owed_detail), "%s", detail);
2583 108 : sh->owed_losses++;
2584 108 : sh->owed_records += records;
2585 108 : sh->owed_bytes += bytes;
2586 108 : if (err != 0) sh->owed_err = err;
2587 108 : sh->async_partial_record |= CLOG_OWED_REPAIR;
2588 108 : atomic_store_explicit(&sh->owes_repair, true, memory_order_relaxed);
2589 108 : clog_exit_drain_arm();
2590 108 : (void)clog_pay_owed(sh, fmt, poll_timeout_ms);
2591 107 : }
2592 :
2593 : // Tries the repair the target owes before a record write, and returns false
2594 : // when a newline is still owed. The record must not go out then (it would
2595 : // continue the fragment); the caller counts it as a loss. Needs sh->mutex.
2596 16 : static __attribute__((noinline, cold)) bool clog_owed_gate(
2597 : clog_shared *sh, clog_format fmt, size_t len, int poll_timeout_ms) {
2598 16 : if (clog_pay_owed(sh, fmt, poll_timeout_ms)) return true;
2599 12 : clog_report_loss(sh, fmt, false, 1, len, 0,
2600 : "a record was not written while a line stayed open",
2601 : poll_timeout_ms);
2602 12 : return false;
2603 : }
2604 :
2605 : // Writes a record the library makes itself (head plus detail at level), such as
2606 : // a WARN about rotation, so the operator sees what the logger did. Like any
2607 : // record it waits for an owed repair, and a short write of it is a loss.
2608 : // poll_timeout_ms bounds the write. Needs sh->mutex.
2609 38 : static void clog_note_record(clog_shared *sh, clog_format fmt, clog_level level,
2610 : const char *head, const char *detail,
2611 : int poll_timeout_ms) {
2612 38 : char note[CLOG_NOTE_CAP];
2613 38 : size_t nlen =
2614 38 : clog_note_render(sh, fmt, level, "", head, detail, note, sizeof(note));
2615 38 : if (nlen == 0) return;
2616 38 : if ((sh->async_partial_record & CLOG_OWED_REPAIR) &&
2617 0 : !clog_owed_gate(sh, fmt, nlen, poll_timeout_ms))
2618 : return;
2619 38 : size_t w = write_all(sh, note, nlen, poll_timeout_ms);
2620 38 : int err = errno;
2621 38 : if (sh->rotation_enabled) sh->bytes_written += (off_t)w;
2622 38 : if (w < nlen) {
2623 1 : char d[96];
2624 1 : snprintf(d, sizeof(d), "%zu of %zu bytes written", w, nlen);
2625 1 : clog_report_loss(sh, fmt, w > 0 && note[w - 1] != '\n', 1, nlen - w, err, d,
2626 : poll_timeout_ms);
2627 : }
2628 : }
2629 :
2630 : // After a write the kernel took only in part (ENOSPC, RLIMIT_FSIZE, a peer that
2631 : // left), reports the loss and closes the record's line unless the accepted part
2632 : // ends on a record boundary, so the next record doesn't join it. Needs
2633 : // sh->mutex.
2634 30 : static void clog_note_truncated_record(clog_shared *sh, clog_format fmt,
2635 : const char *data, size_t written,
2636 : size_t len, int err) {
2637 30 : char detail[96];
2638 30 : snprintf(detail, sizeof(detail), "%zu of %zu bytes written", written, len);
2639 53 : clog_report_loss(sh, fmt, written > 0 && data[written - 1] != '\n', 1,
2640 : len - written, err, detail, CLOG_WRITE_WAIT_FOREVER);
2641 29 : }
2642 :
2643 : // Reports that the continuation of a split record is given up, closing the line
2644 : // when the split was mid-line. split is never CLOG_SPLIT_NONE and the caller
2645 : // already cleared the split bits. Needs sh->mutex.
2646 9 : static void clog_note_dropped_continuation(clog_shared *sh, clog_format fmt,
2647 : unsigned char split, size_t dropped,
2648 : int err, int poll_timeout_ms) {
2649 9 : char detail[96];
2650 9 : snprintf(detail, sizeof(detail), "%zu undelivered bytes dropped", dropped);
2651 9 : clog_report_loss(sh, fmt, split == CLOG_SPLIT_MID_LINE, 1, dropped, err,
2652 : detail, poll_timeout_ms);
2653 9 : }
2654 :
2655 : // Reports that len undelivered batch bytes at data are given up, for the reason
2656 : // why. split is where the bytes on disk end (already cleared by the caller).
2657 : // Each line that doesn't start with a tab counts as a record, and a leading
2658 : // continuation counts for the unfinished record. The caller discards the bytes.
2659 : // Needs sh->mutex.
2660 14 : static __attribute__((noinline, cold)) void clog_note_dropped_batch(
2661 : clog_shared *sh, const char *data, size_t len, unsigned char split,
2662 : const char *why, int err, int poll_timeout_ms) {
2663 14 : size_t records = 0;
2664 14 : if (split == CLOG_SPLIT_AT_LINE) records++;
2665 31 : for (size_t i = 0; i < len;) {
2666 17 : if (data[i] != '\t') records++;
2667 17 : const char *nl = memchr(data + i, '\n', len - i);
2668 17 : if (!nl) break;
2669 17 : i = (size_t)(nl - data) + 1;
2670 : }
2671 14 : char detail[128];
2672 14 : snprintf(detail, sizeof(detail),
2673 : "undelivered batch dropped (records=%zu bytes=%zu): %s", records,
2674 : len, why);
2675 14 : clog_report_loss(sh, sh->format, split == CLOG_SPLIT_MID_LINE, records, len,
2676 : err, detail, poll_timeout_ms);
2677 14 : }
2678 :
2679 : // Writes one framed record to sh->fd, counts what the kernel took toward
2680 : // bytes_written, and repairs the framing after a short write. Every synchronous
2681 : // whole-record write goes through here, so none can leave half a record or
2682 : // write onto a fragment while a newline is owed. Out of line so its large
2683 : // callers keep their shape. Needs sh->mutex.
2684 21323 : static __attribute__((noinline)) void clog_write_record(clog_shared *sh,
2685 : clog_format fmt,
2686 : const char *data,
2687 : size_t len) {
2688 21339 : if (__builtin_expect(sh->async_partial_record & CLOG_OWED_REPAIR, 0) &&
2689 16 : !clog_owed_gate(sh, fmt, len, CLOG_WRITE_WAIT_FOREVER))
2690 : return;
2691 21311 : size_t written = write_all(sh, data, len, CLOG_WRITE_WAIT_FOREVER);
2692 21310 : if (sh->rotation_enabled) sh->bytes_written += (off_t)written;
2693 21310 : if (written < len)
2694 25 : clog_note_truncated_record(sh, fmt, data, written, len, errno);
2695 : }
2696 :
2697 : // Appends the timestamp tv to b. It takes a timestamp captured when the record
2698 : // was submitted, since an async record is built much later on the writer
2699 : // thread. Returns 0 or -1.
2700 41538 : static int buf_append_ts_at(clog_buf *b, const struct timeval *tv) {
2701 41538 : struct tm tm;
2702 41538 : gmtime_r(&tv->tv_sec, &tm);
2703 83076 : return buf_appendf(b, "%04d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
2704 41538 : tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour,
2705 41538 : tm.tm_min, tm.tm_sec, (long)tv->tv_usec);
2706 : }
2707 :
2708 : // Flags of the directory descriptor a rotating logger keeps. It only names the
2709 : // directory for the *at() calls, so O_PATH is enough where it exists.
2710 : #if defined(O_PATH)
2711 : #define CLOG_DIR_OPEN_FLAGS (O_PATH | O_DIRECTORY | O_CLOEXEC)
2712 : #else
2713 : #define CLOG_DIR_OPEN_FLAGS (O_RDONLY | O_DIRECTORY | O_CLOEXEC)
2714 : #endif
2715 :
2716 : // Opens the directory part of path ("." without a '/', "/" right under the
2717 : // root) for the directory descriptor a rotating logger keeps. Returns the
2718 : // descriptor, or -1 with errno set.
2719 592 : static int clog_open_log_dir(const char *path) {
2720 592 : const char *slash = strrchr(path, '/');
2721 592 : if (!slash) return open(".", CLOG_DIR_OPEN_FLAGS);
2722 583 : size_t len = (size_t)(slash - path);
2723 583 : if (len == 0) return open("/", CLOG_DIR_OPEN_FLAGS);
2724 583 : char dir[PATH_MAX];
2725 583 : if (len >= sizeof(dir)) {
2726 1 : errno = ENAMETOOLONG;
2727 1 : return -1;
2728 : }
2729 582 : memcpy(dir, path, len);
2730 582 : dir[len] = '\0';
2731 582 : return open(dir, CLOG_DIR_OPEN_FLAGS);
2732 : }
2733 :
2734 : // Opens a listing of the directory dir_fd names, for the passes over rotated
2735 : // files. It uses a descriptor of its own, since closedir() closes what it reads
2736 : // and dir_fd must stay open. Returns NULL on failure.
2737 4350 : static DIR *clog_opendir_at(int dir_fd) {
2738 4350 : int fd = openat(dir_fd, ".", O_RDONLY | O_DIRECTORY | O_CLOEXEC);
2739 4350 : if (fd < 0) return NULL;
2740 4350 : DIR *d = fdopendir(fd);
2741 4350 : if (!d) close(fd);
2742 : return d;
2743 : }
2744 :
2745 : // Gives the part of path after the last '/'.
2746 771 : static const char *path_base(const char *path) {
2747 771 : const char *slash = strrchr(path, '/');
2748 760 : return slash ? slash + 1 : path;
2749 : }
2750 :
2751 : // True when the directory holds an entry name of any type, without following a
2752 : // link. A name that can't be examined gives false; the step that then uses it
2753 : // fails on the same condition.
2754 3751 : static bool clog_entry_exists(int dir_fd, const char *name) {
2755 3751 : struct stat st;
2756 5227 : return fstatat(dir_fd, name, &st, AT_SYMLINK_NOFOLLOW) == 0;
2757 : }
2758 :
2759 : // Removes name only while it still is the file *st describes (same dev/ino, not
2760 : // following a link), so we never remove an entry another program put there.
2761 : // True when the name no longer holds that file, false when the unlink failed.
2762 242 : static bool clog_unlink_if_same(int dir_fd, const char *name,
2763 : const struct stat *st) {
2764 242 : struct stat cur;
2765 242 : if (fstatat(dir_fd, name, &cur, AT_SYMLINK_NOFOLLOW) != 0)
2766 1 : return errno == ENOENT;
2767 241 : if (cur.st_dev != st->st_dev || cur.st_ino != st->st_ino) return true;
2768 482 : return unlinkat(dir_fd, name, 0) == 0 || errno == ENOENT;
2769 : }
2770 :
2771 : // Which entries are generations of a rotating target. A name that parses as a
2772 : // rotated name is one only when the entry (not following a link) is a regular
2773 : // file owned by the effective user or by the live file's owner, and its stamp
2774 : // isn't above limit. Every other entry is never opened, renamed or deleted, so
2775 : // another user of the directory can't steer the logger through links, FIFOs,
2776 : // far-future stamps or planted names.
2777 : typedef struct {
2778 : uid_t euid;
2779 : uid_t live_uid;
2780 : char limit[CLOG_ROTATION_STAMP_DIGITS];
2781 : } clog_gen_filter;
2782 :
2783 : // Tells whether uid may own a generation (the effective user or the live file's
2784 : // owner), the owner test of clog_gen_filter.
2785 16113 : static bool clog_gen_uid_ok(uid_t uid, uid_t euid, uid_t live_uid) {
2786 16113 : return uid == euid || uid == live_uid;
2787 : }
2788 :
2789 : // Parses the 14 stamp digits d (UTC) into *out, so a rotated name can seed the
2790 : // time interval. False when the digits name no representable time.
2791 2095 : static bool clog_stamp_to_time(const char *d, time_t *out) {
2792 2095 : struct tm tm = {0};
2793 2095 : tm.tm_year = (d[0] - '0') * 1000 + (d[1] - '0') * 100 + (d[2] - '0') * 10 +
2794 2095 : (d[3] - '0') - 1900;
2795 2095 : tm.tm_mon = (d[4] - '0') * 10 + (d[5] - '0') - 1;
2796 2095 : tm.tm_mday = (d[6] - '0') * 10 + (d[7] - '0');
2797 2095 : tm.tm_hour = (d[8] - '0') * 10 + (d[9] - '0');
2798 2095 : tm.tm_min = (d[10] - '0') * 10 + (d[11] - '0');
2799 2095 : tm.tm_sec = (d[12] - '0') * 10 + (d[13] - '0');
2800 2095 : time_t t = timegm(&tm);
2801 2095 : if (t == (time_t)-1) return false;
2802 2095 : *out = t;
2803 2095 : return true;
2804 : }
2805 :
2806 : // Writes the 14 stamp digits of time t (UTC) to out, for a rotated name and the
2807 : // plausibility limit. A time past what time_t or the year 9999 holds gives the
2808 : // highest stamp.
2809 2297 : static void clog_time_to_stamp(int64_t t,
2810 : char out[CLOG_ROTATION_STAMP_DIGITS]) {
2811 2297 : time_t tt = (time_t)t;
2812 2297 : struct tm tm;
2813 2297 : char buf[32];
2814 2297 : if ((int64_t)tt != t || !gmtime_r(&tt, &tm) || tm.tm_year > 9999 - 1900 ||
2815 2297 : tm.tm_year < 0 ||
2816 2297 : strftime(buf, sizeof(buf), "%Y%m%d%H%M%S", &tm) !=
2817 : CLOG_ROTATION_STAMP_DIGITS) {
2818 0 : memset(out, '9', CLOG_ROTATION_STAMP_DIGITS);
2819 0 : return;
2820 : }
2821 2297 : memcpy(out, buf, CLOG_ROTATION_STAMP_DIGITS);
2822 : }
2823 :
2824 : // Block size of the gzip copy loop.
2825 : #define GZ_BUF_SIZE 65536U
2826 :
2827 : #ifdef RUNNING_UNIT_TESTS
2828 :
2829 : // Test hooks that widen and report the window between a compression creating
2830 : // its output and finishing it, where no deletion pass may remove that output.
2831 : static _Atomic unsigned int clog_test_pending_compress_delay_us = 0;
2832 : static _Atomic bool clog_test_gz_dest_opened_state = false;
2833 :
2834 : // Sets how long the next compression pauses after creating its output, and
2835 : // clears the opened flag, so a test can race a deletion pass inside that
2836 : // window.
2837 5 : void clog__test_set_pending_compress_delay_us(unsigned int delay_us) {
2838 5 : atomic_store(&clog_test_gz_dest_opened_state, false);
2839 5 : atomic_store(&clog_test_pending_compress_delay_us, delay_us);
2840 5 : }
2841 :
2842 : // Tells whether a compression has created its output since the delay was set.
2843 22 : bool clog__test_gz_dest_opened(void) {
2844 22 : bool opened = atomic_load(&clog_test_gz_dest_opened_state);
2845 22 : return opened;
2846 : }
2847 :
2848 : // While the gate is held, every compression pauses after creating its output,
2849 : // for at most CLOG_TEST_COMPRESS_HOLD_MAX_US. compressions_finished counts
2850 : // every compression that ended. teardown_entered is set by a close about to
2851 : // wait for a running compressor thread.
2852 : #define CLOG_TEST_COMPRESS_HOLD_MAX_US 30000000U
2853 : static _Atomic bool clog_test_compress_hold = false;
2854 : static _Atomic size_t clog_test_compressions_finished_state = 0;
2855 : static _Atomic bool clog_test_compressor_teardown_entered_state = false;
2856 :
2857 : // Holds or releases compressions at the compression gate, so a test can control
2858 : // when one finishes; holding also clears the teardown flag.
2859 24 : void clog__test_hold_compressions(bool hold) {
2860 24 : if (hold) {
2861 12 : atomic_store(&clog_test_gz_dest_opened_state, false);
2862 12 : atomic_store(&clog_test_compressor_teardown_entered_state, false);
2863 : }
2864 24 : atomic_store(&clog_test_compress_hold, hold);
2865 24 : }
2866 :
2867 : // Tells whether a close has asked a running compressor thread to stop, so a
2868 : // test knows the close is waiting for it.
2869 4 : bool clog__test_compressor_teardown_entered(void) {
2870 4 : return atomic_load(&clog_test_compressor_teardown_entered_state);
2871 : }
2872 :
2873 : // How many times an open backed off from a same-file target whose last close is
2874 : // still running.
2875 : static _Atomic size_t clog_test_closing_target_waits_state = 0;
2876 :
2877 : // Gives how many times an open backed off from a target still closing, so a
2878 : // test can check that an open waits for it.
2879 3 : size_t clog__test_closing_target_waits(void) {
2880 3 : return atomic_load(&clog_test_closing_target_waits_state);
2881 : }
2882 :
2883 : // Gives how many compressions have ended, whatever their outcome, so a test can
2884 : // wait for one.
2885 17 : size_t clog__test_compressions_finished(void) {
2886 17 : return atomic_load(&clog_test_compressions_finished_state);
2887 : }
2888 :
2889 : // How many upcoming compressions fail their publish and also leave their
2890 : // temporary output behind.
2891 : static _Atomic unsigned int clog_test_gz_publish_failures = 0;
2892 :
2893 : // Makes the next count compressions fail to publish and keep their temporary
2894 : // output, so a test can check that the output is removed later.
2895 3 : void clog__test_force_gz_publish_failures(unsigned int count) {
2896 3 : atomic_store(&clog_test_gz_publish_failures, count);
2897 3 : }
2898 :
2899 : // Tells whether a forced publish failure is pending, without taking it, so
2900 : // gzip_compress_file() in a test build skips the publish.
2901 240 : static bool clog_test_peek_gz_publish_failure(void) {
2902 240 : return atomic_load(&clog_test_gz_publish_failures) > 0;
2903 : }
2904 :
2905 : // Takes one forced publish failure, for gzip_compress_file() in a test build;
2906 : // true when one was left.
2907 4 : static bool clog_test_consume_gz_publish_failure(void) {
2908 4 : unsigned int n = atomic_load(&clog_test_gz_publish_failures);
2909 4 : while (n > 0) {
2910 2 : if (atomic_compare_exchange_weak(&clog_test_gz_publish_failures, &n, n - 1))
2911 : return true;
2912 : }
2913 : return false;
2914 : }
2915 :
2916 : // A gate like the one above that pauses compression recovery before it lists
2917 : // the directory.
2918 : #define CLOG_TEST_RECOVER_HOLD_MAX_US 3000000U
2919 : static _Atomic bool clog_test_recover_hold = false;
2920 : static _Atomic bool clog_test_recover_entered = false;
2921 :
2922 : // Holds or releases compression recovery at its gate, and clears the entered
2923 : // flag, so a test can race an open against a recovery.
2924 2 : void clog__test_hold_compression_recovery(bool hold) {
2925 2 : if (hold) atomic_store(&clog_test_recover_entered, false);
2926 2 : atomic_store(&clog_test_recover_hold, hold);
2927 2 : }
2928 :
2929 : // Tells whether a recovery has reached its gate.
2930 2 : bool clog__test_compression_recovery_entered(void) {
2931 2 : return atomic_load(&clog_test_recover_entered);
2932 : }
2933 :
2934 : // Waits at the recovery gate while a test holds it, at most
2935 : // CLOG_TEST_RECOVER_HOLD_MAX_US, and records that a recovery got there.
2936 41 : static void clog_test_recover_gate(void) {
2937 41 : if (!atomic_load(&clog_test_recover_hold)) return;
2938 1 : atomic_store(&clog_test_recover_entered, true);
2939 3001 : for (unsigned int waited = 0; atomic_load(&clog_test_recover_hold) &&
2940 : waited < CLOG_TEST_RECOVER_HOLD_MAX_US;
2941 3000 : waited += 1000)
2942 3000 : usleep(1000);
2943 : }
2944 :
2945 : // Reports whether the writer thread of logger's target had SIGPIPE and SIGXFSZ
2946 : // blocked at its last mask sync, so a test can check the signal policy. False
2947 : // for a handle that doesn't resolve or a thread that hasn't synced yet.
2948 2 : bool clog__test_writer_blocked_signals(clog logger, bool *pipe_blocked,
2949 : bool *xfsz_blocked) {
2950 2 : struct clogger *lg = clog_resolve(logger);
2951 2 : if (!lg) return false;
2952 2 : unsigned bits = atomic_load(&lg->shared->test_writer_blocked_signals);
2953 2 : clog_resolve_unpin(lg);
2954 2 : *pipe_blocked = (bits & 1u) != 0;
2955 2 : *xfsz_blocked = (bits & 2u) != 0;
2956 2 : return (bits & 4u) != 0;
2957 : }
2958 :
2959 : // Gives the timed-wait timeouts of the writer thread of logger's target (0 for
2960 : // a handle that doesn't resolve), so a test can check that an idle writer
2961 : // doesn't wake. The count is per target, so other loggers don't add to it.
2962 8 : size_t clog__test_writer_timeout_wakeups(clog logger) {
2963 8 : struct clogger *lg = clog_resolve(logger);
2964 8 : if (!lg) return 0;
2965 8 : size_t n = atomic_load(&lg->shared->test_writer_timeout_wakeups);
2966 8 : clog_resolve_unpin(lg);
2967 8 : return n;
2968 : }
2969 :
2970 : // Gives the interval flushes of the writer thread of logger's target, or 0, so
2971 : // a test can check the flush interval under load.
2972 2 : size_t clog__test_writer_interval_flushes(clog logger) {
2973 2 : struct clogger *lg = clog_resolve(logger);
2974 2 : if (!lg) return 0;
2975 2 : size_t n = atomic_load(&lg->shared->test_writer_interval_flushes);
2976 2 : clog_resolve_unpin(lg);
2977 2 : return n;
2978 : }
2979 :
2980 : // Gives the synchronous records of logger's target that wait for its mutex
2981 : // right now, or 0, so a test can line threads up behind the mutex.
2982 2 : size_t clog__test_sync_lock_waiters(clog logger) {
2983 2 : struct clogger *lg = clog_resolve(logger);
2984 2 : if (!lg) return 0;
2985 2 : size_t n = atomic_load(&lg->shared->test_sync_lock_waiters);
2986 2 : clog_resolve_unpin(lg);
2987 2 : return n;
2988 : }
2989 :
2990 : // Gives the synchronous records of logger's target that reached their write
2991 : // under the mutex, or 0.
2992 4 : size_t clog__test_sync_records_locked(clog logger) {
2993 4 : struct clogger *lg = clog_resolve(logger);
2994 4 : if (!lg) return 0;
2995 4 : size_t n = atomic_load(&lg->shared->test_sync_records_locked);
2996 4 : clog_resolve_unpin(lg);
2997 4 : return n;
2998 : }
2999 :
3000 : // Counts real rotate() attempts, so a test can check the retry backoff.
3001 : static _Atomic size_t clog_test_rotate_attempt_count = 0;
3002 :
3003 : // Resets the count of rotate() attempts before a test of the retry backoff.
3004 2 : void clog__test_reset_rotate_attempt_count(void) {
3005 2 : atomic_store(&clog_test_rotate_attempt_count, 0);
3006 2 : }
3007 :
3008 : // Gives the count of rotate() attempts since the last reset.
3009 2 : size_t clog__test_get_rotate_attempt_count(void) {
3010 2 : return atomic_load(&clog_test_rotate_attempt_count);
3011 : }
3012 :
3013 : // Runs sanitize_syslog_printusascii_field() on raw, so a test can check the
3014 : // APP-NAME filter.
3015 8 : void clog__test_sanitize_syslog_appname(const char *raw, char *out,
3016 : size_t outsz) {
3017 8 : sanitize_syslog_printusascii_field(raw, out, outsz);
3018 8 : }
3019 :
3020 : // Escapes raw with buf_append_ctrl_escaped() into out, cut to outsz - 1 bytes,
3021 : // so a test can check the escaper; out is empty when the append fails.
3022 8 : void clog__test_append_ctrl_escaped(const char *raw, char *out, size_t outsz) {
3023 8 : if (outsz == 0) return;
3024 8 : clog_buf b;
3025 8 : if (buf_init(&b, NULL) != 0) {
3026 0 : out[0] = '\0';
3027 0 : return;
3028 : }
3029 8 : if (buf_append_ctrl_escaped(&b, raw) != 0) {
3030 0 : out[0] = '\0';
3031 0 : buf_free(&b);
3032 0 : return;
3033 : }
3034 8 : size_t n = b.len < outsz - 1 ? b.len : outsz - 1;
3035 8 : memcpy(out, b.data, n);
3036 8 : out[n] = '\0';
3037 8 : buf_free(&b);
3038 : }
3039 :
3040 : // Backtrace hooks: Force a failed capture, force every syslog frame append to
3041 : // fail (armed until cleared), or force a real capture clamped to no frames. See
3042 : // test_helpers/clogger.h.
3043 : static _Atomic bool clog_test_force_bt_capture_failure = false;
3044 :
3045 : // Makes every backtrace capture fail while force is true, so a test can check
3046 : // the missing-backtrace markers on any platform.
3047 16 : void clog__test_force_backtrace_capture_failure(bool force) {
3048 16 : atomic_store(&clog_test_force_bt_capture_failure, force);
3049 16 : }
3050 :
3051 : static _Atomic bool clog_test_force_all_syslog_bt_frames_fail = false;
3052 :
3053 : // Makes every syslog backtrace frame fail to append while force is true, so a
3054 : // test can reach the marker for frames that all failed.
3055 2 : void clog__test_force_all_syslog_backtrace_frames_failure(bool force) {
3056 2 : atomic_store(&clog_test_force_all_syslog_bt_frames_fail, force);
3057 2 : }
3058 :
3059 : static _Atomic bool clog_test_force_shallow_bt_depth = false;
3060 :
3061 : // Makes every backtrace capture report no frame past the first two while force
3062 : // is true, so a test can check that an empty but real capture writes no marker.
3063 6 : void clog__test_force_shallow_backtrace_depth(bool force) {
3064 6 : atomic_store(&clog_test_force_shallow_bt_depth, force);
3065 6 : }
3066 :
3067 : // Tells whether this build can capture backtraces, so a test of a real capture
3068 : // can skip on musl.
3069 9 : bool clog__test_backtrace_supported(void) { return CLOG_HAS_BACKTRACE != 0; }
3070 : #endif
3071 :
3072 : // Gives fd, a file this module created with mode 0600, the owner, group and
3073 : // permission bits of *like. Owner and group go first and the bits are widened
3074 : // after, so the file is never more readable than *like. Like logrotate it's
3075 : // best effort: Without the owner it still tries the group, and without the
3076 : // group it clears the group bits. Used for a new live file and a .gz.
3077 2274 : static void clog_copy_owner_and_mode(int fd, const struct stat *like) {
3078 2274 : mode_t mode = like->st_mode & 0777;
3079 2274 : struct stat cur;
3080 2274 : if (fstat(fd, &cur) == 0 &&
3081 2274 : (cur.st_uid != like->st_uid || cur.st_gid != like->st_gid)) {
3082 1 : if (fchown(fd, like->st_uid, like->st_gid) != 0 &&
3083 0 : fchown(fd, (uid_t)-1, like->st_gid) != 0)
3084 0 : mode &= ~(mode_t)0070;
3085 : }
3086 2274 : if (fchmod(fd, mode) != 0) {
3087 2274 : }
3088 2274 : }
3089 :
3090 : #ifdef RUNNING_UNIT_TESTS
3091 :
3092 : // The errno the next fsync() of a compressed output reports instead of the real
3093 : // call; it disarms itself.
3094 : static _Atomic int clog_test_next_fsync_error = 0;
3095 :
3096 : // Makes the next fsync() of a compressed output report err, so a test can check
3097 : // which errors fail a compression.
3098 6 : void clog__test_force_next_fsync_error(int err) {
3099 6 : atomic_store(&clog_test_next_fsync_error, err);
3100 6 : }
3101 : #endif
3102 :
3103 : // fsync()s fd. Returns 0 when the data is on disk, or when the filesystem can't
3104 : // do it (EINVAL, ENOSYS), since failing on that would leave every rotated file
3105 : // uncompressed there. Any other failure gives -1.
3106 241 : static int clog_sync_output(int fd) {
3107 241 : int rc;
3108 : #ifdef RUNNING_UNIT_TESTS
3109 241 : int forced = atomic_exchange(&clog_test_next_fsync_error, 0);
3110 241 : if (forced != 0) {
3111 3 : errno = forced;
3112 3 : rc = -1;
3113 : } else
3114 : #endif
3115 238 : rc = fsync(fd);
3116 241 : if (rc == 0 || errno == EINVAL || errno == ENOSYS) return 0;
3117 : return -1;
3118 : }
3119 :
3120 : // A compression writes "<rotated>.gz.tmp" until the output is complete. That
3121 : // name never parses as a rotated name, so retention and naming never see it.
3122 : #define CLOG_GZ_TMP_SUFFIX ".tmp"
3123 :
3124 : // Renames tmp to dst (both relative to dir_fd) without ever replacing a file at
3125 : // dst: RENAME_NOREPLACE, else a hard link plus unlink, else a check and a
3126 : // rename (two steps, only on a filesystem without hard links). Returns 0 on
3127 : // success.
3128 2269 : static int clog_publish_no_replace(int dir_fd, const char *tmp,
3129 : const char *dst) {
3130 : #if defined(RENAME_NOREPLACE) && defined(__linux__)
3131 2269 : if (renameat2(dir_fd, tmp, dir_fd, dst, RENAME_NOREPLACE) == 0) return 0;
3132 1 : if (errno != EINVAL && errno != ENOSYS) return -1;
3133 : #endif
3134 0 : if (linkat(dir_fd, tmp, dir_fd, dst, 0) == 0) {
3135 0 : unlinkat(dir_fd, tmp, 0);
3136 0 : return 0;
3137 : }
3138 0 : if (errno == EEXIST) return -1;
3139 0 : if (clog_entry_exists(dir_fd, dst)) {
3140 0 : errno = EEXIST;
3141 0 : return -1;
3142 : }
3143 0 : return renameat(dir_fd, tmp, dir_fd, dst);
3144 : }
3145 :
3146 : // Compresses src into dst (src plus ".gz"), names relative to dir_fd. The
3147 : // output goes to dst plus CLOG_GZ_TMP_SUFFIX and is flushed, fsync()ed and
3148 : // published without replacing anything, and only then is src unlinked, so a
3149 : // stop partway leaves only the temporary file. The output gets src's owner and
3150 : // mode. Returns 0, or -1 with src untouched and the temporary removed; when
3151 : // that removal fails, *tmp_left gets its dev/ino (st_ino 0 otherwise). A true
3152 : // *abort_flag stops at the next block, as a failure. src is read only when the
3153 : // descriptor, opened without following links or blocking, is a regular file
3154 : // owned by the effective user or live_uid. A leftover temporary is replaced
3155 : // only when it's such a file too; O_EXCL creates the new one.
3156 1485 : static int gzip_compress_file(int dir_fd, const char *src, const char *dst,
3157 : _Atomic bool *abort_flag, uid_t live_uid,
3158 : struct stat *tmp_left) {
3159 1485 : FILE *in = NULL;
3160 1485 : gzFile out = NULL;
3161 1485 : int out_fd = -1;
3162 1485 : int rc = -1;
3163 1485 : bool tmp_created = false;
3164 1485 : struct stat st;
3165 1485 : struct stat tmp_st;
3166 :
3167 1485 : if (tmp_left) tmp_left->st_ino = 0;
3168 1485 : char tmp[PATH_MAX + 8];
3169 1485 : size_t dlen = strlen(dst);
3170 1485 : if (dlen + sizeof(CLOG_GZ_TMP_SUFFIX) > sizeof(tmp)) return -1;
3171 1485 : memcpy(tmp, dst, dlen);
3172 1485 : memcpy(tmp + dlen, CLOG_GZ_TMP_SUFFIX, sizeof(CLOG_GZ_TMP_SUFFIX));
3173 :
3174 1485 : int in_fd =
3175 1485 : openat(dir_fd, src, O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
3176 1485 : if (in_fd < 0) goto done;
3177 244 : int in_flags;
3178 244 : if (fstat(in_fd, &st) != 0 || !S_ISREG(st.st_mode) ||
3179 244 : !clog_gen_uid_ok(st.st_uid, geteuid(), live_uid) ||
3180 488 : (in_flags = fcntl(in_fd, F_GETFL)) == -1 ||
3181 244 : fcntl(in_fd, F_SETFL, in_flags & ~O_NONBLOCK) == -1) {
3182 0 : close(in_fd);
3183 0 : goto done;
3184 : }
3185 244 : in = fdopen(in_fd, "rb");
3186 244 : if (!in) {
3187 0 : close(in_fd);
3188 0 : goto done;
3189 : }
3190 :
3191 244 : if (clog_entry_exists(dir_fd, dst)) goto done;
3192 :
3193 244 : out_fd = openat(dir_fd, tmp,
3194 : O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
3195 244 : if (out_fd < 0 && errno == EEXIST) {
3196 2 : struct stat old_tmp;
3197 2 : if (fstatat(dir_fd, tmp, &old_tmp, AT_SYMLINK_NOFOLLOW) == 0 &&
3198 2 : S_ISREG(old_tmp.st_mode) &&
3199 2 : clog_gen_uid_ok(old_tmp.st_uid, geteuid(), live_uid) &&
3200 1 : unlinkat(dir_fd, tmp, 0) == 0)
3201 1 : out_fd =
3202 1 : openat(dir_fd, tmp,
3203 : O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0600);
3204 : }
3205 2 : if (out_fd < 0) goto done;
3206 243 : if (fstat(out_fd, &tmp_st) != 0) {
3207 0 : (void)unlinkat(dir_fd, tmp, 0);
3208 0 : goto done;
3209 : }
3210 243 : tmp_created = true;
3211 243 : clog_copy_owner_and_mode(out_fd, &st);
3212 243 : out = gzdopen(out_fd, "wb");
3213 243 : if (!out) goto done;
3214 :
3215 : #ifdef RUNNING_UNIT_TESTS
3216 : {
3217 243 : unsigned int delay = atomic_load(&clog_test_pending_compress_delay_us);
3218 243 : atomic_store(&clog_test_gz_dest_opened_state, true);
3219 243 : if (delay) usleep(delay);
3220 207 : for (unsigned int waited = 0; atomic_load(&clog_test_compress_hold) &&
3221 655 : !(abort_flag && atomic_load(abort_flag)) &&
3222 : waited < CLOG_TEST_COMPRESS_HOLD_MAX_US;
3223 205 : waited += 1000)
3224 206 : usleep(1000);
3225 : }
3226 : #endif
3227 :
3228 : unsigned char buf[GZ_BUF_SIZE];
3229 : size_t n;
3230 483 : while ((n = fread(buf, 1, sizeof(buf), in)) > 0) {
3231 242 : if (abort_flag && atomic_load_explicit(abort_flag, memory_order_relaxed))
3232 1 : goto done;
3233 241 : if (gzwrite(out, buf, (unsigned)n) != (int)n) goto done;
3234 : }
3235 241 : if (ferror(in)) goto done;
3236 :
3237 241 : if (gzflush(out, Z_FINISH) != Z_OK || clog_sync_output(out_fd) != 0)
3238 1 : goto done;
3239 240 : int close_rc = gzclose(out);
3240 240 : out = NULL;
3241 240 : out_fd = -1;
3242 240 : if (close_rc != Z_OK) goto done;
3243 : #ifdef RUNNING_UNIT_TESTS
3244 240 : if (clog_test_peek_gz_publish_failure()) goto done;
3245 : #endif
3246 238 : if (clog_publish_no_replace(dir_fd, tmp, dst) != 0) goto done;
3247 : tmp_created = false;
3248 : rc = 0;
3249 :
3250 1484 : done:
3251 1484 : if (in) fclose(in);
3252 1484 : if (out)
3253 2 : gzclose(out);
3254 1482 : else if (out_fd >= 0)
3255 0 : close(out_fd);
3256 1484 : if (tmp_left) tmp_left->st_ino = 0;
3257 1484 : if (tmp_created) {
3258 4 : bool removed;
3259 : #ifdef RUNNING_UNIT_TESTS
3260 8 : if (clog_test_consume_gz_publish_failure())
3261 : removed = false;
3262 : else
3263 : #endif
3264 2 : removed = clog_unlink_if_same(dir_fd, tmp, &tmp_st);
3265 4 : if (!removed && tmp_left) *tmp_left = tmp_st;
3266 : }
3267 1484 : if (rc == 0) (void)clog_unlink_if_same(dir_fd, src, &st);
3268 : #ifdef RUNNING_UNIT_TESTS
3269 1484 : atomic_fetch_add(&clog_test_compressions_finished_state, 1);
3270 : #endif
3271 1484 : return rc;
3272 : }
3273 :
3274 : #ifdef RUNNING_UNIT_TESTS
3275 :
3276 : // Run gzip_compress_file() directly on paths relative to the working directory,
3277 : // with the effective user (or the given owner) allowed to own src, so a test
3278 : // can check the compression alone. True on success.
3279 6 : bool clog__test_gzip_compress_file(const char *src, const char *dst) {
3280 6 : return gzip_compress_file(AT_FDCWD, src, dst, NULL, geteuid(), NULL) == 0;
3281 : }
3282 :
3283 1 : bool clog__test_gzip_compress_file_for_owner(const char *src, const char *dst,
3284 : uid_t live_uid) {
3285 1 : return gzip_compress_file(AT_FDCWD, src, dst, NULL, live_uid, NULL) == 0;
3286 : }
3287 : #endif
3288 :
3289 : // Parses what follows "<base>." in a candidate rotated name: 14 stamp digits,
3290 : // an optional "_<seq>" (at least 4 digits, zero-padded, no leading zero beyond
3291 : // that, never 0) and an optional ".gz". On a match, *stamp points at the digits
3292 : // and *seq gets the number (0 without a suffix). Anything else is refused, so
3293 : // prune_rotated() never deletes a file that only looks similar.
3294 30556 : static bool rotated_name_parse(const char *rest, const char **stamp,
3295 : unsigned long *seq) {
3296 458340 : for (int i = 0; i < CLOG_ROTATION_STAMP_DIGITS; i++)
3297 427784 : if (!isdigit((unsigned char)rest[i])) return false;
3298 30556 : const char *p = rest + CLOG_ROTATION_STAMP_DIGITS;
3299 30556 : unsigned long s = 0;
3300 30556 : if (*p == '_') {
3301 29355 : p++;
3302 29355 : int nd = 0;
3303 146772 : while (nd <= CLOG_ROTATION_SEQ_MAX_DIGITS && isdigit((unsigned char)p[nd]))
3304 117417 : nd++;
3305 29355 : if (nd < 4 || nd > CLOG_ROTATION_SEQ_MAX_DIGITS) return false;
3306 29274 : if (nd > 4 && p[0] == '0') return false;
3307 146691 : for (int i = 0; i < nd; i++) s = s * 10 + (unsigned long)(p[i] - '0');
3308 29274 : if (s == 0) return false;
3309 29274 : p += nd;
3310 : }
3311 30475 : if (*p != '\0' && strcmp(p, ".gz") != 0) return false;
3312 30256 : *stamp = rest;
3313 30256 : *seq = s;
3314 30256 : return true;
3315 : }
3316 :
3317 : // Matches the directory entry d_name against "<base>.<rotated name>" for the
3318 : // passes over rotated files; on a match it fills the stamp and sequence through
3319 : // rotated_name_parse().
3320 43454 : static bool rotated_entry_match(const char *d_name, const char *base,
3321 : size_t base_len, const char **stamp,
3322 : unsigned long *seq) {
3323 43454 : if (strncmp(d_name, base, base_len) != 0 || d_name[base_len] != '.')
3324 : return false;
3325 30556 : return rotated_name_parse(d_name + base_len + 1, stamp, seq);
3326 : }
3327 :
3328 : // Compares two rotated names by (stamp, sequence), the order of rotations, for
3329 : // naming and retention. Returns below, at or above zero.
3330 424191 : static int rotated_key_cmp(const char *stamp_a, unsigned long seq_a,
3331 : const char *stamp_b, unsigned long seq_b) {
3332 424191 : int c = memcmp(stamp_a, stamp_b, CLOG_ROTATION_STAMP_DIGITS);
3333 424191 : if (c != 0) return c;
3334 355942 : return (seq_a > seq_b) - (seq_a < seq_b);
3335 : }
3336 :
3337 : // Fills *f for one pass over sh's directory. The stamp limit is the tolerance
3338 : // above the later of the clock and rot_last_stamp, so a clock step back never
3339 : // turns one of sh's own generations into an ignored entry. Needs sh->mutex or
3340 : // sole ownership of sh.
3341 2297 : static void clog_gen_filter_init(const clog_shared *sh, clog_gen_filter *f) {
3342 2297 : f->euid = geteuid();
3343 2297 : struct stat st;
3344 2297 : f->live_uid = (sh->fd >= 0 && fstat(sh->fd, &st) == 0) ? st.st_uid : f->euid;
3345 2297 : int64_t ref = (int64_t)clog_wall_now();
3346 2297 : time_t last;
3347 2297 : if (sh->rot_name_known && clog_stamp_to_time(sh->rot_last_stamp, &last) &&
3348 2094 : (int64_t)last > ref)
3349 2297 : ref = (int64_t)last;
3350 2297 : clog_time_to_stamp(ref + CLOG_ROTATION_FUTURE_TOLERANCE_SECS, f->limit);
3351 2297 : }
3352 :
3353 : // What a rotated-looking entry is: A generation, something else, or gone.
3354 : typedef enum {
3355 : CLOG_ENTRY_GENERATION,
3356 : CLOG_ENTRY_IGNORED,
3357 : CLOG_ENTRY_GONE
3358 : } clog_entry_kind;
3359 :
3360 : // Classifies the entry name (its stamp digits at stamp) against filter f, so
3361 : // only generations get renamed, compressed or deleted. It never follows a link
3362 : // and never opens the entry.
3363 15937 : static clog_entry_kind clog_entry_classify(int dir_fd, const char *name,
3364 : const char *stamp,
3365 : const clog_gen_filter *f) {
3366 15937 : struct stat st;
3367 15937 : if (fstatat(dir_fd, name, &st, AT_SYMLINK_NOFOLLOW) != 0)
3368 6 : return errno == ENOENT ? CLOG_ENTRY_GONE : CLOG_ENTRY_IGNORED;
3369 15931 : if (!S_ISREG(st.st_mode) || !clog_gen_uid_ok(st.st_uid, f->euid, f->live_uid))
3370 : return CLOG_ENTRY_IGNORED;
3371 15867 : if (memcmp(stamp, f->limit, CLOG_ROTATION_STAMP_DIGITS) > 0)
3372 64 : return CLOG_ENTRY_IGNORED;
3373 : return CLOG_ENTRY_GENERATION;
3374 : }
3375 :
3376 : // Writes the WARN about an entry that looks like a rotated file but isn't a
3377 : // generation, rate-limited by CLOG_IGNORED_NOTE_BURST per window. Anyone with
3378 : // write access to the directory picks the name, so bytes outside printable
3379 : // ASCII, quotes and backslashes become '?' and a long name is cut. Needs
3380 : // sh->mutex (or sole ownership) and no half-written record.
3381 128 : static void clog_note_ignored_entry(clog_shared *sh, const char *name) {
3382 128 : time_t now = time(NULL);
3383 128 : if (now < sh->ignored_note_window ||
3384 128 : now - sh->ignored_note_window >= CLOG_IGNORED_NOTE_WINDOW_SECS) {
3385 7 : sh->ignored_note_window = now;
3386 7 : sh->ignored_note_count = 0;
3387 : }
3388 128 : if (sh->ignored_note_count >= CLOG_IGNORED_NOTE_BURST) return;
3389 37 : sh->ignored_note_count++;
3390 37 : enum { SHOWN = 96 };
3391 37 : char safe[SHOWN + 4];
3392 37 : size_t i = 0;
3393 965 : for (; name[i] != '\0' && i < SHOWN; i++) {
3394 928 : unsigned char c = (unsigned char)name[i];
3395 928 : safe[i] = (c > 0x20 && c < 0x7f && c != '"' && c != '\\') ? (char)c : '?';
3396 : }
3397 37 : if (name[i] != '\0') {
3398 1 : memcpy(safe + i, "...", 3);
3399 1 : i += 3;
3400 : }
3401 37 : safe[i] = '\0';
3402 37 : clog_note_record(sh, sh->format, CLOG_WARN,
3403 : "log rotation: ignored an entry that is not a rotated "
3404 : "file of this log: ",
3405 : safe, CLOG_WRITE_WAIT_FOREVER);
3406 : }
3407 :
3408 : // Classifies name like clog_entry_classify() and writes the WARN for an ignored
3409 : // entry when may_note is true, so an operator learns about entries the logger
3410 : // leaves alone.
3411 15937 : static clog_entry_kind clog_entry_check(clog_shared *sh, const char *name,
3412 : const char *stamp,
3413 : const clog_gen_filter *f,
3414 : bool may_note) {
3415 15937 : clog_entry_kind k = clog_entry_classify(sh->dir_fd, name, stamp, f);
3416 15937 : if (k == CLOG_ENTRY_IGNORED && may_note) clog_note_ignored_entry(sh, name);
3417 15937 : return k;
3418 : }
3419 :
3420 : // Finds sh's newest generation on disk and fills stamp_out and *seq_out; false
3421 : // when there's none. rotate() calls it before a target's first rotation, so a
3422 : // restart in the same directory numbers its rotations above the old ones. Needs
3423 : // sh->mutex (or sole ownership).
3424 75 : static bool rotated_newest_on_disk(clog_shared *sh, bool may_note,
3425 : char stamp_out[CLOG_ROTATION_STAMP_DIGITS],
3426 : unsigned long *seq_out) {
3427 75 : const char *base = sh->file_base;
3428 75 : size_t base_len = strlen(base);
3429 75 : clog_gen_filter f;
3430 75 : clog_gen_filter_init(sh, &f);
3431 :
3432 75 : DIR *d = clog_opendir_at(sh->dir_fd);
3433 75 : if (!d) return false;
3434 : bool found = false;
3435 : struct dirent *e;
3436 324 : while ((e = readdir(d)) != NULL) {
3437 249 : const char *stamp;
3438 249 : unsigned long seq;
3439 253 : if (!rotated_entry_match(e->d_name, base, base_len, &stamp, &seq)) continue;
3440 20 : if (clog_entry_check(sh, e->d_name, stamp, &f, may_note) !=
3441 : CLOG_ENTRY_GENERATION)
3442 4 : continue;
3443 21 : if (!found || rotated_key_cmp(stamp, seq, stamp_out, *seq_out) > 0) {
3444 10 : memcpy(stamp_out, stamp, CLOG_ROTATION_STAMP_DIGITS);
3445 10 : *seq_out = seq;
3446 10 : found = true;
3447 : }
3448 : }
3449 75 : closedir(d);
3450 75 : return found;
3451 : }
3452 :
3453 : // One rotated file prune_rotated() found; stamp points into path.
3454 : typedef struct {
3455 : char *path;
3456 : const char *stamp;
3457 : unsigned long seq;
3458 : bool is_protected;
3459 : } clog_rotated_file;
3460 :
3461 : // Compares two rotated files for qsort(), oldest first by (stamp, sequence),
3462 : // the order rotations happened in. The mtime can't be used: A compression
3463 : // rewrites the file, so a big old generation can finish later than a newer one.
3464 51491 : static int cmp_rotated_oldest_first(const void *a, const void *b) {
3465 51491 : const clog_rotated_file *x = (const clog_rotated_file *)a;
3466 51491 : const clog_rotated_file *y = (const clog_rotated_file *)b;
3467 51491 : int c = rotated_key_cmp(x->stamp, x->seq, y->stamp, y->seq);
3468 51491 : if (c != 0) return c;
3469 5 : return strcmp(x->path, y->path);
3470 : }
3471 :
3472 : #ifdef RUNNING_UNIT_TESTS
3473 :
3474 : // Since the last reset: The most generations a pass left on disk (counted from
3475 : // a listing of its own), the most compressions in flight a pass saw, and the
3476 : // most generations left beyond those kept only for a running compression.
3477 : static _Atomic int clog_test_max_rotated_generations = 0;
3478 : static _Atomic int clog_test_max_compressions_in_flight = 0;
3479 : static _Atomic int clog_test_max_generations_beyond_old_compressions = 0;
3480 :
3481 : // Counts base's distinct generations from a listing of its own, so the test
3482 : // maxima don't depend on what the deletion pass listed.
3483 2053 : static int clog_test_count_generations_on_disk(int dir_fd, const char *base) {
3484 2053 : size_t base_len = strlen(base);
3485 2053 : DIR *d = clog_opendir_at(dir_fd);
3486 2053 : if (!d) return 0;
3487 : struct {
3488 : char stamp[CLOG_ROTATION_STAMP_DIGITS];
3489 : unsigned long seq;
3490 : } seen[256];
3491 : int n = 0;
3492 : struct dirent *e;
3493 21830 : while ((e = readdir(d)) != NULL) {
3494 19777 : const char *stamp;
3495 19777 : unsigned long seq;
3496 19778 : if (!rotated_entry_match(e->d_name, base, base_len, &stamp, &seq)) continue;
3497 : bool dup = false;
3498 369497 : for (int i = 0; i < n && !dup; i++)
3499 712020 : dup = rotated_key_cmp(seen[i].stamp, seen[i].seq, stamp, seq) == 0;
3500 13414 : if (dup || n == (int)(sizeof(seen) / sizeof(seen[0]))) continue;
3501 13413 : memcpy(seen[n].stamp, stamp, CLOG_ROTATION_STAMP_DIGITS);
3502 13413 : seen[n].seq = seq;
3503 13413 : n++;
3504 : }
3505 2053 : closedir(d);
3506 2053 : return n;
3507 : }
3508 :
3509 : // Raises the maximum *slot to value when value is larger, for the test maxima
3510 : // of the deletion pass.
3511 6159 : static void clog_test_raise_to(_Atomic int *slot, int value) {
3512 6159 : int prev = atomic_load(slot);
3513 1234 : while (value > prev && !atomic_compare_exchange_weak(slot, &prev, value)) {
3514 6159 : }
3515 : }
3516 :
3517 : // Resets the three maxima the deletion passes record, before a retention test.
3518 2 : void clog__test_reset_max_rotated_generations(void) {
3519 2 : atomic_store(&clog_test_max_rotated_generations, 0);
3520 2 : atomic_store(&clog_test_max_compressions_in_flight, 0);
3521 2 : atomic_store(&clog_test_max_generations_beyond_old_compressions, 0);
3522 2 : }
3523 :
3524 : // Give the three maxima the deletion passes recorded since the last reset, so a
3525 : // test can check the retention bound.
3526 1 : int clog__test_get_max_rotated_generations(void) {
3527 1 : return atomic_load(&clog_test_max_rotated_generations);
3528 : }
3529 :
3530 1 : int clog__test_get_max_compressions_in_flight(void) {
3531 1 : return atomic_load(&clog_test_max_compressions_in_flight);
3532 : }
3533 :
3534 1 : int clog__test_get_max_generations_beyond_old_compressions(void) {
3535 1 : return atomic_load(&clog_test_max_generations_beyond_old_compressions);
3536 : }
3537 : #endif
3538 :
3539 : #ifdef RUNNING_UNIT_TESTS
3540 :
3541 : // While set, a deletion pass doesn't see the running compression's files in its
3542 : // listing, as a readdir() racing the compressor can.
3543 : static _Atomic bool clog_test_prune_misses_running = false;
3544 :
3545 : // Turns on or off the hiding of the running compression's names from deletion
3546 : // passes, so a test can reproduce a readdir() that misses them.
3547 2 : void clog__test_set_prune_misses_running(bool miss) {
3548 2 : atomic_store(&clog_test_prune_misses_running, miss);
3549 2 : }
3550 : #endif
3551 :
3552 : // Deletes sh's oldest generations beyond max_rotated_files. A generation is one
3553 : // rotation: One file, or two (source and .gz) while it's being compressed. The
3554 : // pass keeps the newest max_keep generations and deletes the older ones, except
3555 : // the running compression and just_rotated (the file this rotation just moved
3556 : // aside), which are never deleted. When it keeps an old generation only because
3557 : // it's being compressed, it sets compress_prune_deferred so the compressor runs
3558 : // the pass again afterwards; at most max_keep plus one generations stay. The
3559 : // running job's names are added from the job when readdir() missed them, since
3560 : // the compressor renames them without the mutex. A pass that can't list
3561 : // everything for lack of memory deletes nothing. Only generations count; others
3562 : // get a WARN when may_note is true (the compressor's pass passes false, because
3563 : // a record can be half written then). Needs sh->mutex.
3564 2093 : static void prune_rotated(clog_shared *sh, const char *just_rotated,
3565 : bool may_note) {
3566 2093 : int max_keep = sh->rotation.max_rotated_files;
3567 2093 : if (max_keep <= 0) return;
3568 :
3569 2093 : const ccol_memmgmt_procs *m_procs = sh->m_procs;
3570 2093 : const clog_compress_job *running = sh->compress_running;
3571 2093 : const char *base = sh->file_base;
3572 2093 : size_t base_len = strlen(base);
3573 :
3574 2093 : clog_gen_filter f;
3575 2093 : clog_gen_filter_init(sh, &f);
3576 2093 : DIR *d = clog_opendir_at(sh->dir_fd);
3577 2093 : if (!d) return;
3578 :
3579 2093 : clog_rotated_file *files = NULL;
3580 2093 : int fc = 0, cap = 0;
3581 2093 : bool complete = true;
3582 2093 : size_t just_rotated_len = just_rotated ? strlen(just_rotated) : 0;
3583 2093 : bool running_listed = false;
3584 2093 : struct dirent *e;
3585 :
3586 24423 : while ((e = readdir(d)) != NULL) {
3587 22370 : const char *n = e->d_name;
3588 22370 : const char *name_stamp;
3589 22370 : unsigned long seq;
3590 22479 : if (!rotated_entry_match(n, base, base_len, &name_stamp, &seq)) continue;
3591 : #ifdef RUNNING_UNIT_TESTS
3592 15890 : if (running && atomic_load(&clog_test_prune_misses_running) &&
3593 15 : (strcmp(running->src, n) == 0 || strcmp(running->dst, n) == 0))
3594 4 : continue;
3595 : #endif
3596 15886 : if (clog_entry_check(sh, n, name_stamp, &f, may_note) !=
3597 : CLOG_ENTRY_GENERATION)
3598 105 : continue;
3599 :
3600 15781 : size_t n_len = strlen(n);
3601 15781 : char *name = ccol__mem_alloc(m_procs, n_len + 1);
3602 15781 : if (!name) {
3603 : complete = false;
3604 40 : break;
3605 : }
3606 15744 : memcpy(name, n, n_len + 1);
3607 :
3608 15744 : bool is_protected = running && (strcmp(running->src, name) == 0 ||
3609 6960 : strcmp(running->dst, name) == 0);
3610 15744 : if (is_protected) running_listed = true;
3611 15744 : if (just_rotated && (strcmp(name, just_rotated) == 0 ||
3612 13530 : (strncmp(name, just_rotated, just_rotated_len) == 0 &&
3613 0 : strcmp(name + just_rotated_len, ".gz") == 0)))
3614 15744 : is_protected = true;
3615 :
3616 15744 : if (fc >= cap) {
3617 2393 : int nc = cap ? cap * 2 : 16;
3618 2393 : clog_rotated_file *nf =
3619 2393 : ccol__mem_realloc(m_procs, files, (size_t)nc * sizeof(*files));
3620 2393 : if (!nf) {
3621 3 : ccol__mem_free(m_procs, name);
3622 : complete = false;
3623 : break;
3624 : }
3625 : files = nf;
3626 : cap = nc;
3627 : }
3628 15741 : files[fc].path = name;
3629 15741 : files[fc].stamp = name + (size_t)(name_stamp - n);
3630 15741 : files[fc].seq = seq;
3631 15741 : files[fc].is_protected = is_protected;
3632 15741 : fc++;
3633 : }
3634 2093 : closedir(d);
3635 :
3636 2093 : const char *running_stamp;
3637 2093 : unsigned long running_seq;
3638 2994 : if (complete && running && !running_listed &&
3639 901 : rotated_entry_match(running->src, base, base_len, &running_stamp,
3640 : &running_seq)) {
3641 901 : size_t r_len = strlen(running->src);
3642 901 : char *name = ccol__mem_alloc(m_procs, r_len + 1);
3643 1802 : clog_rotated_file *nf =
3644 901 : name && fc >= cap
3645 0 : ? ccol__mem_realloc(m_procs, files,
3646 : (size_t)(cap ? cap * 2 : 16) * sizeof(*files))
3647 901 : : files;
3648 901 : if (!name || !nf) {
3649 0 : ccol__mem_free(m_procs, name);
3650 : complete = false;
3651 : } else {
3652 901 : if (fc >= cap) cap = cap ? cap * 2 : 16;
3653 901 : files = nf;
3654 901 : memcpy(name, running->src, r_len + 1);
3655 901 : files[fc].path = name;
3656 901 : files[fc].stamp = name + (size_t)(running_stamp - running->src);
3657 901 : files[fc].seq = running_seq;
3658 901 : files[fc].is_protected = true;
3659 901 : fc++;
3660 : }
3661 : }
3662 :
3663 2093 : if (complete) {
3664 2053 : if (fc > 1)
3665 1987 : qsort(files, (size_t)fc, sizeof(*files), cmp_rotated_oldest_first);
3666 :
3667 : int generations = 0;
3668 17981 : for (int i = 0; i < fc; i++)
3669 29797 : if (i == 0 || rotated_key_cmp(files[i].stamp, files[i].seq,
3670 13877 : files[i - 1].stamp, files[i - 1].seq) != 0)
3671 15923 : generations++;
3672 :
3673 2053 : int delete_below = generations - max_keep;
3674 2053 : int g = 0;
3675 : #ifdef RUNNING_UNIT_TESTS
3676 2053 : int old_under_compression = 0;
3677 : #endif
3678 4780 : for (int start = 0; start < fc && g < delete_below; g++) {
3679 2727 : int end = start + 1;
3680 2731 : while (end < fc &&
3681 2726 : rotated_key_cmp(files[end].stamp, files[end].seq,
3682 2731 : files[start].stamp, files[start].seq) == 0)
3683 4 : end++;
3684 2727 : bool is_protected = false;
3685 5458 : for (int i = start; i < end; i++)
3686 2731 : if (files[i].is_protected) is_protected = true;
3687 2727 : if (!is_protected) {
3688 3431 : for (int i = start; i < end; i++)
3689 1716 : unlinkat(sh->dir_fd, files[i].path, 0);
3690 : } else {
3691 1012 : sh->compress_prune_deferred = true;
3692 : #ifdef RUNNING_UNIT_TESTS
3693 1012 : old_under_compression++;
3694 : #endif
3695 : }
3696 2727 : start = end;
3697 : }
3698 : #ifdef RUNNING_UNIT_TESTS
3699 2053 : int in_flight = running ? 1 : 0;
3700 412505 : for (const clog_compress_job *j = sh->compress_head; j; j = j->next)
3701 410452 : in_flight++;
3702 2053 : int on_disk = clog_test_count_generations_on_disk(sh->dir_fd, base);
3703 2053 : clog_test_raise_to(&clog_test_max_rotated_generations, on_disk);
3704 2053 : clog_test_raise_to(&clog_test_max_compressions_in_flight, in_flight);
3705 2053 : clog_test_raise_to(&clog_test_max_generations_beyond_old_compressions,
3706 : on_disk - old_under_compression);
3707 : #endif
3708 : }
3709 :
3710 18735 : for (int i = 0; i < fc; i++) ccol__mem_free(m_procs, files[i].path);
3711 2093 : ccol__mem_free(m_procs, files);
3712 : }
3713 :
3714 : // True when candidate can't be a new rotation destination: The name exists, or
3715 : // (with check_gz) its .gz form exists. The second test matters because a
3716 : // finished compression unlinks its source, so the bare name of an earlier
3717 : // rotation in the same second looks free while its .gz holds the content.
3718 2031 : static bool rotated_name_taken(int dir_fd, const char *candidate,
3719 : bool check_gz) {
3720 2031 : if (clog_entry_exists(dir_fd, candidate)) return true;
3721 2031 : if (!check_gz) return false;
3722 1476 : char gz[PATH_MAX + 8];
3723 1476 : size_t clen = strlen(candidate);
3724 1476 : memcpy(gz, candidate, clen);
3725 1476 : memcpy(gz + clen, ".gz", 4);
3726 1476 : return clog_entry_exists(dir_fd, gz);
3727 : }
3728 :
3729 : // Background compression: A target that compresses owns one compressor thread,
3730 : // started by its first rotation that needs one. rotate() only queues a job, so
3731 : // no log call ever waits for gzip. Jobs run one at a time, oldest first, which
3732 : // is what bounds the files on disk to max_rotated_files plus one. The last
3733 : // close stops the thread after the queue is empty; the exit drain waits for it
3734 : // within its budget.
3735 : //
3736 : // The target whose writer or compressor thread the calling thread is. The exit
3737 : // drain skips it, since that thread can't serve the drain it would wait for and
3738 : // may hold the target's mutex.
3739 : static __thread const clog_shared *clog_thread_serves;
3740 :
3741 : // True once there's work for the exit drain: A writer or compressor thread
3742 : // started, or a debt was left.
3743 : static _Atomic bool clog_exit_drain_armed;
3744 :
3745 : // Arms the exit drain, which has nothing to do until a writer or compressor
3746 : // thread starts or a debt is left.
3747 453 : static void clog_exit_drain_arm(void) {
3748 108 : atomic_store_explicit(&clog_exit_drain_armed, true, memory_order_relaxed);
3749 : }
3750 :
3751 : // Tries again to remove the temporary output of each job in left (only while
3752 : // the name still holds that file) and frees the jobs that succeed. Returns the
3753 : // ones that failed again.
3754 2 : static clog_compress_job *clog_retry_tmp_removals(
3755 : int dir_fd, clog_compress_job *left, const ccol_memmgmt_procs *m_procs) {
3756 2 : clog_compress_job *keep = NULL;
3757 4 : while (left) {
3758 2 : clog_compress_job *job = left;
3759 2 : left = job->next;
3760 2 : char tmp[PATH_MAX + 8];
3761 2 : size_t dlen = strlen(job->dst);
3762 2 : bool gone = true;
3763 2 : if (dlen + sizeof(CLOG_GZ_TMP_SUFFIX) <= sizeof(tmp)) {
3764 2 : memcpy(tmp, job->dst, dlen);
3765 2 : memcpy(tmp + dlen, CLOG_GZ_TMP_SUFFIX, sizeof(CLOG_GZ_TMP_SUFFIX));
3766 2 : struct stat st;
3767 2 : memset(&st, 0, sizeof(st));
3768 2 : st.st_dev = job->tmp_dev;
3769 2 : st.st_ino = job->tmp_ino;
3770 2 : gone = clog_unlink_if_same(dir_fd, tmp, &st);
3771 : }
3772 2 : if (gone) {
3773 2 : ccol__mem_free(m_procs, job);
3774 : } else {
3775 0 : job->next = keep;
3776 0 : keep = job;
3777 : }
3778 : }
3779 2 : return keep;
3780 : }
3781 :
3782 : // Runs sh's compressor thread (arg is sh). It runs jobs until it's asked to
3783 : // stop and the queue is empty, setting compress_running under sh->mutex for
3784 : // each. After a job it reruns a deferred deletion pass and wakes the threads
3785 : // waiting for the queue. Temporary outputs a failed job couldn't remove are
3786 : // retried before each job and at stop; what's left after that the next open's
3787 : // recovery removes.
3788 37 : static void *clog_compressor_main(void *arg) {
3789 37 : clog_shared *sh = (clog_shared *)arg;
3790 37 : clog_thread_serves = sh;
3791 37 : clog_thread_signal_init();
3792 37 : clog_compress_job *left = NULL;
3793 37 : ccol__mutex_lock(sh->mutex);
3794 1475 : for (;;) {
3795 1559 : while (!sh->compress_head && !sh->compressor_stop)
3796 50 : ccol__cond_var_wait(sh->compress_cv, sh->mutex);
3797 1509 : clog_compress_job *job = sh->compress_head;
3798 1509 : if (!job) break;
3799 1478 : sh->compress_head = job->next;
3800 1478 : if (!sh->compress_head) sh->compress_tail = NULL;
3801 1478 : job->next = NULL;
3802 1478 : sh->compress_running = job;
3803 1478 : int dir_fd = sh->dir_fd;
3804 1478 : ccol__mutex_unlock(sh->mutex);
3805 :
3806 1478 : if (left) left = clog_retry_tmp_removals(dir_fd, left, sh->m_procs);
3807 1478 : clog_thread_sync_signal_mask();
3808 1478 : struct stat tmp_left;
3809 1478 : if (gzip_compress_file(dir_fd, job->src, job->dst, &sh->compress_abort,
3810 : job->live_uid, &tmp_left) != 0)
3811 1243 : clog_consume_own_sigxfsz();
3812 :
3813 1477 : ccol__mutex_lock(sh->mutex);
3814 1476 : sh->compress_running = NULL;
3815 1476 : if (tmp_left.st_ino != 0) {
3816 2 : job->tmp_dev = tmp_left.st_dev;
3817 2 : job->tmp_ino = tmp_left.st_ino;
3818 2 : job->next = left;
3819 2 : left = job;
3820 : } else {
3821 1474 : ccol__mem_free(sh->m_procs, job);
3822 : }
3823 1475 : if (sh->compress_prune_deferred) {
3824 62 : sh->compress_prune_deferred = false;
3825 62 : prune_rotated(sh, NULL, false);
3826 : }
3827 1475 : ccol__cond_var_broadcast(sh->compress_cv);
3828 : }
3829 31 : int dir_fd = sh->dir_fd;
3830 31 : ccol__mutex_unlock(sh->mutex);
3831 31 : if (left) left = clog_retry_tmp_removals(dir_fd, left, sh->m_procs);
3832 31 : while (left) {
3833 0 : clog_compress_job *job = left;
3834 0 : left = job->next;
3835 0 : ccol__mem_free(sh->m_procs, job);
3836 : }
3837 31 : return NULL;
3838 : }
3839 :
3840 : // Starts sh's compressor thread. compress_cv uses CLOCK_MONOTONIC so the exit
3841 : // drain's bounded wait ignores wall clock steps. Needs sh->mutex and
3842 : // compressor_live false. Returns false, with nothing left behind, when the
3843 : // thread can't start.
3844 37 : static bool clog_compressor_start(clog_shared *sh) {
3845 37 : ccol__cond_var_attr ca;
3846 37 : if (ccol__cond_var_attr_init(ca) != 0) return false;
3847 37 : int cv_rc = ccol__cond_var_attr_setclock(ca, CLOCK_MONOTONIC);
3848 37 : if (cv_rc == 0) cv_rc = ccol__cond_var_init_ca(sh->compress_cv, ca);
3849 37 : ccol__cond_var_attr_destroy(ca);
3850 37 : if (cv_rc != 0) return false;
3851 37 : clog_exit_drain_arm();
3852 37 : sh->compressor_stop = false;
3853 37 : if (ccol__thread_create(sh->compressor_thread, clog_compressor_main, sh) !=
3854 : 0) {
3855 0 : ccol__cond_var_destroy(sh->compress_cv);
3856 0 : return false;
3857 : }
3858 37 : sh->compressor_live = true;
3859 37 : return true;
3860 : }
3861 :
3862 : // Queues the compression of rotated (relative to dir_fd) as one allocation
3863 : // holding both names. When the allocation or the thread start fails the file
3864 : // stays uncompressed and nothing is lost. live_uid is the live file's owner.
3865 : // Needs sh->mutex.
3866 1478 : static void clog_compress_enqueue(clog_shared *sh, const char *rotated,
3867 : uid_t live_uid) {
3868 1478 : size_t n = strlen(rotated);
3869 2956 : clog_compress_job *job =
3870 1478 : ccol__mem_alloc(sh->m_procs, sizeof(*job) + (n + 1) + (n + 4));
3871 1478 : if (!job) return;
3872 1478 : job->next = NULL;
3873 1478 : job->live_uid = live_uid;
3874 1478 : job->src = (char *)(job + 1);
3875 1478 : memcpy(job->src, rotated, n + 1);
3876 1478 : job->dst = job->src + n + 1;
3877 1478 : memcpy(job->dst, rotated, n);
3878 1478 : memcpy(job->dst + n, ".gz", 4);
3879 :
3880 1478 : if (!sh->compressor_live && !clog_compressor_start(sh)) {
3881 0 : ccol__mem_free(sh->m_procs, job);
3882 0 : return;
3883 : }
3884 1478 : if (sh->compress_tail)
3885 1388 : sh->compress_tail->next = job;
3886 : else
3887 90 : sh->compress_head = job;
3888 1478 : sh->compress_tail = job;
3889 1478 : ccol__cond_var_broadcast(sh->compress_cv);
3890 : }
3891 :
3892 : // Requeues the compressions a stopped process left unfinished. It removes
3893 : // leftover temporary outputs, and a .gz next to its still existing source (a
3894 : // source is removed only after its .gz is complete, so that .gz isn't known to
3895 : // be complete), then queues every uncompressed generation oldest first. It acts
3896 : // on generations only and warns about other entries. Needs sh->mutex; sh
3897 : // rotates and compresses.
3898 41 : static void clog_recover_compressions(clog_shared *sh) {
3899 41 : const ccol_memmgmt_procs *m_procs = sh->m_procs;
3900 41 : const char *base = sh->file_base;
3901 41 : size_t base_len = strlen(base);
3902 41 : static const char tmp_tail[] = ".gz" CLOG_GZ_TMP_SUFFIX;
3903 41 : size_t tmp_tail_len = sizeof(tmp_tail) - 1;
3904 41 : clog_gen_filter f;
3905 41 : clog_gen_filter_init(sh, &f);
3906 :
3907 41 : DIR *d = clog_opendir_at(sh->dir_fd);
3908 41 : if (!d) return;
3909 : clog_rotated_file *files = NULL;
3910 : int fc = 0, cap = 0;
3911 : struct dirent *e;
3912 198 : while ((e = readdir(d)) != NULL) {
3913 157 : const char *n = e->d_name;
3914 157 : size_t n_len = strlen(n);
3915 157 : const char *stamp;
3916 157 : unsigned long seq;
3917 157 : if (n_len > tmp_tail_len &&
3918 36 : strcmp(n + n_len - tmp_tail_len, tmp_tail) == 0) {
3919 2 : char gz_name[sizeof(e->d_name)];
3920 2 : size_t gz_len = n_len - (sizeof(CLOG_GZ_TMP_SUFFIX) - 1);
3921 2 : memcpy(gz_name, n, gz_len);
3922 2 : gz_name[gz_len] = '\0';
3923 4 : if (rotated_entry_match(gz_name, base, base_len, &stamp, &seq) &&
3924 2 : clog_entry_check(sh, n, stamp, &f, true) == CLOG_ENTRY_GENERATION)
3925 2 : unlinkat(sh->dir_fd, n, 0);
3926 2 : continue;
3927 : }
3928 155 : if (!rotated_entry_match(n, base, base_len, &stamp, &seq)) continue;
3929 29 : if (n_len >= 3 && strcmp(n + n_len - 3, ".gz") == 0) continue;
3930 26 : if (clog_entry_check(sh, n, stamp, &f, true) != CLOG_ENTRY_GENERATION)
3931 23 : continue;
3932 3 : if (fc >= cap) {
3933 2 : int nc = cap ? cap * 2 : 16;
3934 2 : clog_rotated_file *nf =
3935 2 : ccol__mem_realloc(m_procs, files, (size_t)nc * sizeof(*files));
3936 2 : if (!nf) break;
3937 : files = nf;
3938 : cap = nc;
3939 : }
3940 3 : char *name = ccol__mem_alloc(m_procs, n_len + 1);
3941 3 : if (!name) break;
3942 3 : memcpy(name, n, n_len + 1);
3943 3 : files[fc].path = name;
3944 3 : files[fc].stamp = name + (size_t)(stamp - n);
3945 3 : files[fc].seq = seq;
3946 3 : files[fc].is_protected = false;
3947 3 : fc++;
3948 : }
3949 41 : closedir(d);
3950 :
3951 41 : if (fc > 1)
3952 1 : qsort(files, (size_t)fc, sizeof(*files), cmp_rotated_oldest_first);
3953 44 : for (int i = 0; i < fc; i++) {
3954 3 : char gz[PATH_MAX + 8];
3955 3 : size_t plen = strlen(files[i].path);
3956 3 : if (plen + 4 <= sizeof(gz)) {
3957 3 : memcpy(gz, files[i].path, plen);
3958 3 : memcpy(gz + plen, ".gz", 4);
3959 3 : clog_entry_kind gz_kind =
3960 3 : clog_entry_check(sh, gz, files[i].stamp, &f, true);
3961 3 : if (gz_kind == CLOG_ENTRY_GENERATION) unlinkat(sh->dir_fd, gz, 0);
3962 3 : if (gz_kind != CLOG_ENTRY_IGNORED)
3963 3 : clog_compress_enqueue(sh, files[i].path, f.live_uid);
3964 : }
3965 3 : ccol__mem_free(m_procs, files[i].path);
3966 : }
3967 41 : ccol__mem_free(m_procs, files);
3968 : }
3969 :
3970 : // Stops and joins sh's compressor thread after it finishes its queue. The
3971 : // caller must not hold sh->mutex and no handle that can rotate may remain (the
3972 : // last close calls it after the writer thread stopped). Does nothing when no
3973 : // thread runs.
3974 1447 : static void shared_compressor_teardown(clog_shared *sh) {
3975 1447 : ccol__mutex_lock(sh->mutex);
3976 1447 : bool live = sh->compressor_live;
3977 1447 : if (live) {
3978 31 : sh->compressor_stop = true;
3979 31 : ccol__cond_var_broadcast(sh->compress_cv);
3980 : }
3981 1447 : ccol__mutex_unlock(sh->mutex);
3982 1447 : if (!live) return;
3983 : #ifdef RUNNING_UNIT_TESTS
3984 31 : atomic_store(&clog_test_compressor_teardown_entered_state, true);
3985 : #endif
3986 31 : ccol__thread_join(sh->compressor_thread);
3987 31 : ccol__cond_var_destroy(sh->compress_cv);
3988 31 : sh->compressor_live = false;
3989 : }
3990 :
3991 : // Mixes the bits of x with the splitmix64 finalizer, for the fallback of
3992 : // clog_random64().
3993 0 : static uint64_t clog_mix64(uint64_t x) {
3994 0 : x ^= x >> 30;
3995 0 : x *= UINT64_C(0xbf58476d1ce4e5b9);
3996 0 : x ^= x >> 27;
3997 0 : x *= UINT64_C(0x94d049bb133111eb);
3998 0 : x ^= x >> 31;
3999 0 : return x;
4000 : }
4001 :
4002 : // Gives 64 bits another user can't predict, for the private name of a new live
4003 : // file. Without getrandom() it mixes clocks, the pid, a counter and an address;
4004 : // the O_EXCL creation stays correct either way.
4005 2032 : static uint64_t clog_random64(void) {
4006 2032 : uint64_t r;
4007 2032 : if (ccol_random_bytes(&r, sizeof(r))) return r;
4008 0 : static _Atomic uint64_t counter;
4009 0 : struct timespec rt = {0}, mt = {0};
4010 0 : clock_gettime(CLOCK_REALTIME, &rt);
4011 0 : clock_gettime(CLOCK_MONOTONIC, &mt);
4012 0 : r = clog_mix64(atomic_fetch_add(&counter, 1) ^ (uint64_t)getpid());
4013 0 : r = clog_mix64(r ^
4014 0 : ((uint64_t)rt.tv_sec * 1000000000ULL + (uint64_t)rt.tv_nsec));
4015 0 : r = clog_mix64(r ^
4016 0 : ((uint64_t)mt.tv_sec * 1000000000ULL + (uint64_t)mt.tv_nsec));
4017 0 : r = clog_mix64(r ^ (uint64_t)(uintptr_t)&r);
4018 0 : return r;
4019 : }
4020 :
4021 : // Tells whether name is "<base>.tmp" plus 11 lowercase hex digits, the private
4022 : // name of a new live file, so a leftover one can be recognized and removed.
4023 319 : static bool clog_is_live_tmp_name(const char *name, const char *base,
4024 : size_t base_len) {
4025 319 : static const char tag[] = CLOG_ROTATION_TMP_TAG;
4026 319 : if (strncmp(name, base, base_len) != 0) return false;
4027 142 : const char *p = name + base_len;
4028 142 : if (strncmp(p, tag, sizeof(tag) - 1) != 0) return false;
4029 36 : p += sizeof(tag) - 1;
4030 36 : for (int i = 0; i < CLOG_ROTATION_TMP_HEX_DIGITS; i++)
4031 33 : if (!isdigit((unsigned char)p[i]) && !(p[i] >= 'a' && p[i] <= 'f'))
4032 : return false;
4033 3 : return p[CLOG_ROTATION_TMP_HEX_DIGITS] == '\0';
4034 : }
4035 :
4036 : // Creates a rotation's next live file under a private random name (written to
4037 : // tmp) with O_EXCL and O_NOFOLLOW, so it's always a new regular file of ours.
4038 : // With old set it gets the owner, group and mode of the file it replaces, so a
4039 : // restricted log stays restricted; otherwise it's 0644 under the umask. Returns
4040 : // the descriptor and fills *st_out, or -1.
4041 2032 : static int clog_create_fresh(int dir_fd, const char *base,
4042 : const struct stat *old, char *tmp, size_t tmp_size,
4043 : struct stat *st_out) {
4044 2032 : size_t blen = strlen(base);
4045 2032 : if (blen + CLOG_ROTATION_TMP_LEN + 1 > tmp_size) {
4046 0 : errno = ENAMETOOLONG;
4047 0 : return -1;
4048 : }
4049 2032 : for (int attempt = 0; attempt < 8; attempt++) {
4050 2032 : uint64_t r = clog_random64() &
4051 : ((UINT64_C(1) << (4 * CLOG_ROTATION_TMP_HEX_DIGITS)) - 1);
4052 2032 : snprintf(tmp, tmp_size, "%s" CLOG_ROTATION_TMP_TAG "%0*llx", base,
4053 : CLOG_ROTATION_TMP_HEX_DIGITS, (unsigned long long)r);
4054 2032 : int fd =
4055 2032 : openat(dir_fd, tmp,
4056 : O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_APPEND | O_CLOEXEC,
4057 : old ? 0600 : 0644);
4058 2032 : if (fd < 0) {
4059 1 : if (errno == EEXIST) continue;
4060 : return -1;
4061 : }
4062 2031 : if (old) clog_copy_owner_and_mode(fd, old);
4063 2031 : if (fstat(fd, st_out) != 0) {
4064 0 : int saved = errno;
4065 0 : (void)unlinkat(dir_fd, tmp, 0);
4066 0 : close(fd);
4067 0 : errno = saved;
4068 0 : return -1;
4069 : }
4070 : return fd;
4071 : }
4072 0 : errno = EEXIST;
4073 0 : return -1;
4074 : }
4075 :
4076 : // Removes a private live-file name a rotation left when its process stopped
4077 : // before the final rename. Only an empty regular file owned by the effective
4078 : // user or the live file's owner, with exactly that name shape, goes. Needs
4079 : // sh->mutex (or sole ownership); sh rotates.
4080 88 : static void clog_remove_stale_live_tmps(clog_shared *sh) {
4081 88 : const char *base = sh->file_base;
4082 88 : size_t base_len = strlen(base);
4083 88 : clog_gen_filter f;
4084 88 : clog_gen_filter_init(sh, &f);
4085 88 : DIR *d = clog_opendir_at(sh->dir_fd);
4086 88 : if (!d) return;
4087 : struct dirent *e;
4088 407 : while ((e = readdir(d)) != NULL) {
4089 319 : if (!clog_is_live_tmp_name(e->d_name, base, base_len)) continue;
4090 3 : struct stat st;
4091 3 : if (fstatat(sh->dir_fd, e->d_name, &st, AT_SYMLINK_NOFOLLOW) == 0 &&
4092 3 : S_ISREG(st.st_mode) && st.st_size == 0 &&
4093 1 : clog_gen_uid_ok(st.st_uid, f.euid, f.live_uid))
4094 1 : (void)unlinkat(sh->dir_fd, e->d_name, 0);
4095 : }
4096 88 : closedir(d);
4097 : }
4098 :
4099 : #ifdef RUNNING_UNIT_TESTS
4100 :
4101 : // Called by rotate() while the live name names no file, so a test can plant an
4102 : // entry there and check that the rotation replaces it.
4103 : static void (*_Atomic clog_test_rotate_window_hook)(int dir_fd,
4104 : const char *base);
4105 :
4106 : // Sets the function rotate() calls while the live name names no file, so a test
4107 : // can plant an entry there.
4108 4 : void clog__test_set_rotate_window_hook(void (*hook)(int dir_fd,
4109 : const char *base)) {
4110 4 : atomic_store(&clog_test_rotate_window_hook, hook);
4111 4 : }
4112 : #endif
4113 :
4114 : // Ends the file a rotation retires with a newline, so every generation does. It
4115 : // writes the newline, and when the file refuses it (size limit, full disk) cuts
4116 : // the file back to its last whole line, scanning backward through a read-only
4117 : // open of rotated that must still match old_st's dev/ino. The cut bytes join
4118 : // the owed loss. Only a regular file is handled. True when the file ends with a
4119 : // newline, is empty, or can't be reached by name. Needs sh->mutex.
4120 2 : static __attribute__((noinline, cold)) bool clog_close_retired_line(
4121 : clog_shared *sh, int old_fd, const struct stat *old_st,
4122 : const char *rotated) {
4123 2 : if (!S_ISREG(old_st->st_mode)) return false;
4124 2 : ssize_t w;
4125 2 : do {
4126 2 : w = write(old_fd, "\n", 1);
4127 2 : } while (w < 0 && errno == EINTR);
4128 2 : if (w == 1) return true;
4129 0 : if (w < 0 && errno == EFBIG) clog_consume_own_sigxfsz();
4130 0 : if (rotated == NULL) return true;
4131 0 : int rfd = openat(sh->dir_fd, rotated,
4132 : O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC | O_NOCTTY);
4133 0 : if (rfd < 0) return false;
4134 0 : struct stat st;
4135 0 : if (fstat(rfd, &st) != 0 || st.st_dev != old_st->st_dev ||
4136 0 : st.st_ino != old_st->st_ino) {
4137 0 : close(rfd);
4138 0 : return false;
4139 : }
4140 0 : off_t end = st.st_size;
4141 0 : off_t pos = end;
4142 0 : off_t cut = 0;
4143 0 : char block[4096];
4144 0 : bool read_ok = true;
4145 0 : while (pos > 0) {
4146 0 : size_t n = pos < (off_t)sizeof(block) ? (size_t)pos : sizeof(block);
4147 0 : pos -= (off_t)n;
4148 0 : ssize_t r;
4149 0 : do {
4150 0 : r = pread(rfd, block, n, pos);
4151 0 : } while (r < 0 && errno == EINTR);
4152 0 : if (r != (ssize_t)n) {
4153 : read_ok = false;
4154 : break;
4155 : }
4156 : size_t k = n;
4157 0 : while (k > 0 && block[k - 1] != '\n') k--;
4158 0 : if (k > 0) {
4159 0 : cut = pos + (off_t)k;
4160 0 : break;
4161 : }
4162 : }
4163 0 : close(rfd);
4164 0 : if (!read_ok) return false;
4165 0 : if (cut == end) return true;
4166 0 : int rv;
4167 0 : do {
4168 0 : rv = ftruncate(old_fd, cut);
4169 0 : } while (rv != 0 && errno == EINTR);
4170 0 : if (rv != 0) return false;
4171 0 : sh->owed_bytes += (size_t)(end - cut);
4172 0 : return true;
4173 : }
4174 :
4175 : // Rotates the live file, for the size and time rotation checks; all names are
4176 : // relative to sh->dir_fd. It creates the next live file under a private name,
4177 : // picks a destination whose (stamp, sequence) sorts above every earlier name (a
4178 : // clock step back keeps the newest stamp and continues its sequence, so a freed
4179 : // name never comes back), renames the live file there without replacing
4180 : // anything, renames the new file onto the live name and only then switches fds.
4181 : // It never opens the live name or a rotated name, so an entry planted at the
4182 : // live name in between is simply replaced. A failed step puts the original name
4183 : // back and writes continue in the old file; ENOENT (the file was deleted)
4184 : // counts as a clean slate. After success it closes the old file's open line,
4185 : // runs the deletion pass and queues the compression (or warns when the name is
4186 : // too long for one). Needs sh->mutex. Returns 0 or -1.
4187 2033 : static int rotate(clog_shared *sh) {
4188 : #ifdef RUNNING_UNIT_TESTS
4189 2033 : atomic_fetch_add(&clog_test_rotate_attempt_count, 1);
4190 : #endif
4191 :
4192 2033 : if (sh->dir_fd < 0 || sh->fd < 0) {
4193 : return 0;
4194 : }
4195 4066 : if (clog_test_consume_rotate_failure()) return -1;
4196 :
4197 2032 : time_t now = clog_wall_now();
4198 2032 : struct tm tm;
4199 2032 : gmtime_r(&now, &tm);
4200 :
4201 2032 : size_t plen = strlen(sh->file_base);
4202 2032 : char rotated[PATH_MAX];
4203 :
4204 2032 : if (plen + CLOG_ROTATION_FMT_LEN + CLOG_ROTATION_EXTRA + 1 >
4205 : sizeof(rotated)) {
4206 : return -1;
4207 : }
4208 :
4209 2032 : memcpy(rotated, sh->file_base, plen);
4210 2032 : size_t slen =
4211 2032 : strftime(rotated + plen, sizeof(rotated) - plen, CLOG_ROTATION_FMT, &tm);
4212 2032 : if (slen != CLOG_ROTATION_FMT_LEN) {
4213 : return -1;
4214 : }
4215 2032 : char *stamp = rotated + plen + 1;
4216 :
4217 2032 : if (!sh->rot_name_known)
4218 72 : sh->rot_name_known =
4219 72 : rotated_newest_on_disk(sh, true, sh->rot_last_stamp, &sh->rot_last_seq);
4220 2032 : unsigned long seq = 0;
4221 2032 : if (sh->rot_name_known &&
4222 1966 : memcmp(stamp, sh->rot_last_stamp, CLOG_ROTATION_STAMP_DIGITS) <= 0) {
4223 1963 : memcpy(stamp, sh->rot_last_stamp, CLOG_ROTATION_STAMP_DIGITS);
4224 1963 : seq = sh->rot_last_seq + 1;
4225 : }
4226 :
4227 2032 : struct stat old_st;
4228 2032 : bool have_old_st = fstat(sh->fd, &old_st) == 0;
4229 2032 : char tmp[PATH_MAX];
4230 2032 : struct stat new_st;
4231 2032 : int new_fd =
4232 2032 : clog_create_fresh(sh->dir_fd, sh->file_base, have_old_st ? &old_st : NULL,
4233 : tmp, sizeof(tmp), &new_st);
4234 2032 : if (new_fd < 0) return -1;
4235 :
4236 2031 : bool check_gz = sh->rotation.compress_rotated;
4237 2031 : size_t base = plen + slen;
4238 2031 : int rename_rv = -1;
4239 2031 : int rename_errno = 0;
4240 0 : for (;; seq++) {
4241 2031 : if (seq > CLOG_ROTATION_SEQ_LIMIT) {
4242 : rename_errno = EEXIST;
4243 : break;
4244 : }
4245 2031 : rotated[base] = '\0';
4246 2031 : if (seq > 0 &&
4247 1963 : snprintf(rotated + base, sizeof(rotated) - base, "_%04lu", seq) < 0) {
4248 : rename_errno = EINVAL;
4249 : break;
4250 : }
4251 2031 : if (rotated_name_taken(sh->dir_fd, rotated, check_gz)) continue;
4252 2031 : rename_rv = clog_publish_no_replace(sh->dir_fd, sh->file_base, rotated);
4253 2031 : rename_errno = errno;
4254 2031 : if (rename_rv == 0 || rename_errno != EEXIST) break;
4255 : }
4256 2031 : if (rename_rv != 0 && rename_errno != ENOENT) {
4257 0 : (void)clog_unlink_if_same(sh->dir_fd, tmp, &new_st);
4258 0 : close(new_fd);
4259 0 : return -1;
4260 : }
4261 2031 : bool did_rename = (rename_rv == 0);
4262 :
4263 : #ifdef RUNNING_UNIT_TESTS
4264 : {
4265 2031 : void (*hook)(int, const char *) =
4266 2031 : atomic_load(&clog_test_rotate_window_hook);
4267 2031 : if (hook) hook(sh->dir_fd, sh->file_base);
4268 : }
4269 : #endif
4270 :
4271 2031 : if (renameat(sh->dir_fd, tmp, sh->dir_fd, sh->file_base) != 0) {
4272 0 : if (did_rename)
4273 0 : (void)clog_publish_no_replace(sh->dir_fd, rotated, sh->file_base);
4274 0 : (void)clog_unlink_if_same(sh->dir_fd, tmp, &new_st);
4275 0 : close(new_fd);
4276 0 : return -1;
4277 : }
4278 :
4279 2031 : int old_fd = sh->fd;
4280 2031 : bool old_line_open = sh->owe_newline;
4281 2031 : sh->fd = new_fd;
4282 2031 : sh->sink_kind = clog_classify_sink(new_fd);
4283 2031 : sh->sink_per_record = clog_sink_is_message(new_fd);
4284 2031 : sh->bytes_written = 0;
4285 2031 : sh->last_rotation = now;
4286 2031 : if (old_line_open) sh->owe_newline = false;
4287 2031 : memcpy(sh->rot_last_stamp, stamp, CLOG_ROTATION_STAMP_DIGITS);
4288 2031 : sh->rot_last_seq = seq;
4289 2031 : sh->rot_name_known = true;
4290 :
4291 2031 : if (sh->rotation.max_rotated_files > 0) {
4292 2032 : prune_rotated(sh, did_rename ? rotated : NULL, true);
4293 : }
4294 2031 : if (old_line_open &&
4295 2 : !(have_old_st && clog_close_retired_line(sh, old_fd, &old_st,
4296 : did_rename ? rotated : NULL))) {
4297 0 : sh->owe_newline = true;
4298 : }
4299 2031 : if (!(sh->owe_newline || sh->owed_losses > 0)) {
4300 2029 : sh->async_partial_record &= (unsigned char)~CLOG_OWED_REPAIR;
4301 2029 : atomic_store_explicit(&sh->owes_repair, false, memory_order_relaxed);
4302 : }
4303 2031 : close(old_fd);
4304 :
4305 2031 : if (did_rename && sh->rotation.compress_rotated) {
4306 1476 : long name_max = fpathconf(sh->dir_fd, _PC_NAME_MAX);
4307 1476 : size_t gz_tmp_len = strlen(rotated) + sizeof(".gz" CLOG_GZ_TMP_SUFFIX) - 1;
4308 1476 : if (name_max > 0 && gz_tmp_len > (size_t)name_max)
4309 1 : clog_note_record(sh, sh->format, CLOG_WARN,
4310 : "log rotation: a rotated file stays uncompressed: ",
4311 : "its compressed name exceeds the name length limit "
4312 : "of the directory",
4313 : CLOG_WRITE_WAIT_FOREVER);
4314 : else
4315 1475 : clog_compress_enqueue(sh, rotated, new_st.st_uid);
4316 : }
4317 :
4318 : return 0;
4319 : }
4320 :
4321 : // True when the time interval is over at now. The difference is taken in 64
4322 : // bits (time_t can be 32), compared in microseconds, and a negative one (a
4323 : // clock step back) is never due.
4324 12 : static inline bool clog_time_rotation_elapsed(const clog_shared *sh,
4325 : time_t now) {
4326 12 : int64_t since = (int64_t)now - (int64_t)sh->last_rotation;
4327 0 : return since >= 0 && ((uint64_t)since >= UINT64_MAX / UINT64_C(1000000) ||
4328 12 : (uint64_t)since * UINT64_C(1000000) >=
4329 12 : sh->rotation.rotation_interval_us);
4330 : }
4331 :
4332 : // Tells whether the retry backoff allows a rotation at now, so a failing
4333 : // rotation isn't retried on every write. A backoff ending more than one backoff
4334 : // period ahead was set before a clock step back and doesn't count.
4335 2248 : static inline bool clog_rotate_retry_allowed(const clog_shared *sh,
4336 : time_t now) {
4337 2248 : int64_t left = (int64_t)sh->rotate_retry_after - (int64_t)now;
4338 2248 : return left <= 0 || left > (int64_t)CLOG_ROTATE_RETRY_BACKOFF_SECS;
4339 : }
4340 :
4341 : // The time rotation check every path runs before writing a record. It waits
4342 : // while a split record's halves would land in two files, restarts the interval
4343 : // when the clock stepped back before it, and sets the backoff after a failed
4344 : // rotation. Needs sh->mutex.
4345 16817 : static void clog_time_rotate_if_due(clog_shared *sh) {
4346 16817 : if (!(sh->rotation_enabled && sh->rotation.time_rotation_enabled)) return;
4347 13 : if (sh->async_partial_record & CLOG_SPLIT_MASK) return;
4348 13 : time_t now = clog_wall_now();
4349 13 : if (now < sh->last_rotation) {
4350 1 : sh->last_rotation = now;
4351 1 : return;
4352 : }
4353 12 : if (clog_time_rotation_elapsed(sh, now) &&
4354 6 : clog_rotate_retry_allowed(sh, now)) {
4355 6 : int rrv = rotate(sh);
4356 6 : if (rrv != 0) sh->rotate_retry_after = now + CLOG_ROTATE_RETRY_BACKOFF_SECS;
4357 : }
4358 : }
4359 :
4360 : // The size rotation check every path runs after a write, once bytes_written
4361 : // covers it. Like the time check it waits while a record is split; the flush
4362 : // that rejoins it runs the check again. Needs sh->mutex.
4363 16832 : static void clog_size_rotate_if_due(clog_shared *sh) {
4364 16832 : if (!(sh->rotation_enabled && sh->rotation.size_rotation_enabled &&
4365 8881 : (int64_t)sh->bytes_written >= sh->rotation.max_file_size))
4366 : return;
4367 2047 : if (sh->async_partial_record & CLOG_SPLIT_MASK) return;
4368 2046 : time_t now = clog_wall_now();
4369 2046 : if (clog_rotate_retry_allowed(sh, now)) {
4370 2027 : int rrv = rotate(sh);
4371 2027 : if (rrv != 0) sh->rotate_retry_after = now + CLOG_ROTATE_RETRY_BACKOFF_SECS;
4372 : }
4373 : }
4374 :
4375 : // Tells whether a size or time rotation is due now and the backoff allows it,
4376 : // ignoring the split bits; a flush uses it to decide whether to give up a
4377 : // continuation so the rotation can run. Needs sh->mutex.
4378 208 : static bool clog_rotation_due(const clog_shared *sh) {
4379 208 : if (!sh->rotation_enabled) return false;
4380 196 : time_t now = clog_wall_now();
4381 196 : if (!clog_rotate_retry_allowed(sh, now)) return false;
4382 196 : if (sh->rotation.size_rotation_enabled &&
4383 196 : (int64_t)sh->bytes_written >= sh->rotation.max_file_size)
4384 : return true;
4385 194 : return sh->rotation.time_rotation_enabled &&
4386 194 : clog_time_rotation_elapsed(sh, now);
4387 : }
4388 :
4389 : // Frames 0 and 1 are capture_backtrace and clog__write; frame 2 is the caller.
4390 : #define CLOG_BT_INITIAL_FRAME 2
4391 :
4392 : // Captures the calling thread's backtrace for a record that asks for one. It's
4393 : // noinline and clog__write calls it directly on every path, which is what keeps
4394 : // CLOG_BT_INITIAL_FRAME right. On success it stores the backtrace_symbols()
4395 : // array in *out_syms and the depth in *out_depth and returns true. It returns
4396 : // false and leaves both alone without backtrace support or when
4397 : // backtrace_symbols() fails; callers treat that as no frames. The test hooks
4398 : // can force a failure or a capture with no user frame.
4399 389 : static bool __attribute__((noinline)) capture_backtrace(char ***out_syms,
4400 : int *out_depth) {
4401 : #ifdef RUNNING_UNIT_TESTS
4402 389 : if (atomic_load(&clog_test_force_bt_capture_failure)) return false;
4403 : #endif
4404 : #if CLOG_HAS_BACKTRACE
4405 381 : void *ptrs[CLOG_BACKTRACE_DEPTH];
4406 381 : int depth = backtrace(ptrs, CLOG_BACKTRACE_DEPTH);
4407 381 : char **syms = backtrace_symbols(ptrs, depth);
4408 381 : if (!syms) return false;
4409 : #ifdef RUNNING_UNIT_TESTS
4410 381 : if (atomic_load(&clog_test_force_shallow_bt_depth) &&
4411 : depth > CLOG_BT_INITIAL_FRAME)
4412 381 : depth = CLOG_BT_INITIAL_FRAME;
4413 : #endif
4414 381 : *out_syms = syms;
4415 381 : *out_depth = depth;
4416 381 : return true;
4417 : #else
4418 : (void)out_syms;
4419 : (void)out_depth;
4420 : return false;
4421 : #endif
4422 : }
4423 :
4424 : // The logfmt line written instead of the frames when no backtrace could be
4425 : // captured, so a reader can tell a missing backtrace from one nobody asked for.
4426 : // BT_JSON_ERROR_MARKER does the same for JSON.
4427 : static const char BT_LINE_ERROR_MARKER[] = "\t#error backtrace unavailable\n";
4428 :
4429 : // Appends the frames as tab-indented continuation lines after a logfmt record,
4430 : // so the backtrace lands in the same write as the record. Each frame goes
4431 : // through the control escaper and is rolled back when it doesn't fit, so later
4432 : // shorter frames still get in. A NULL syms appends BT_LINE_ERROR_MARKER.
4433 : // Returns true when out shows the backtrace accurately: Some frames went in, no
4434 : // frame existed (depth at most CLOG_BT_INITIAL_FRAME), or the marker stands in
4435 : // for frames that all failed to fit. False only when not even the marker fits.
4436 239 : static bool emit_backtrace_lines(clog_buf *out, char *const *syms, int depth) {
4437 239 : if (!syms)
4438 4 : return buf_append(out, BT_LINE_ERROR_MARKER,
4439 4 : sizeof(BT_LINE_ERROR_MARKER) - 1) == 0;
4440 :
4441 : bool any_frame_written = false;
4442 1913 : for (int i = CLOG_BT_INITIAL_FRAME; i < depth; i++) {
4443 1678 : size_t entry_start = out->len;
4444 1678 : bool ok = buf_appendf(out, "\t#%d ", i - CLOG_BT_INITIAL_FRAME) == 0;
4445 1678 : ok = ok && buf_append_ctrl_escaped(out, syms[i]) == 0;
4446 1651 : ok = ok && buf_append(out, "\n", 1) == 0;
4447 1678 : if (!ok) {
4448 27 : out->len = entry_start;
4449 27 : continue;
4450 : }
4451 : any_frame_written = true;
4452 : }
4453 235 : if (any_frame_written || depth <= CLOG_BT_INITIAL_FRAME) return true;
4454 :
4455 3 : return buf_append(out, BT_LINE_ERROR_MARKER,
4456 3 : sizeof(BT_LINE_ERROR_MARKER) - 1) == 0;
4457 : }
4458 :
4459 : // The JSON key written instead of the "bt" array when the backtrace can't go
4460 : // into the record, so a reader can tell it was left out and the record itself
4461 : // isn't replaced by the oversized-record fallback.
4462 : static const char BT_JSON_ERROR_MARKER[] = ",\"bt_error\":\"unavailable\"";
4463 :
4464 : // Appends ,"bt":["#0 sym",...] while the JSON object is still open, because
4465 : // JSON carries its backtrace inside the record. A frame that doesn't fit is
4466 : // skipped and later ones still tried. An empty array is written only when no
4467 : // frame existed; a NULL syms, or real frames none of which fit, give
4468 : // BT_JSON_ERROR_MARKER instead. Returns true when the record can be closed as
4469 : // it is, false when not even the marker fits and the caller must fall back.
4470 138 : static bool emit_backtrace_json(clog_buf *b, char *const *syms, int depth) {
4471 138 : if (!syms)
4472 2 : return buf_append(b, BT_JSON_ERROR_MARKER,
4473 2 : sizeof(BT_JSON_ERROR_MARKER) - 1) == 0;
4474 :
4475 136 : size_t bt_start = b->len;
4476 136 : if (buf_append(b, ",\"bt\":[", 7) != 0) {
4477 1 : return buf_append(b, BT_JSON_ERROR_MARKER,
4478 1 : sizeof(BT_JSON_ERROR_MARKER) - 1) == 0;
4479 : }
4480 :
4481 : bool first = true;
4482 : bool any_frame_written = false;
4483 1075 : for (int i = CLOG_BT_INITIAL_FRAME; i < depth; i++) {
4484 940 : size_t entry_start = b->len;
4485 940 : char prefix[20];
4486 940 : int pl =
4487 940 : snprintf(prefix, sizeof(prefix), "#%d ", i - CLOG_BT_INITIAL_FRAME);
4488 940 : if ((!first && buf_append(b, ",", 1) != 0) || buf_append(b, "\"", 1) != 0 ||
4489 1880 : (pl > 0 && buf_append(b, prefix, (size_t)pl) != 0) ||
4490 1871 : buf_append_json_content(b, syms[i]) != 0 ||
4491 931 : buf_append(b, "\"", 1) != 0) {
4492 9 : b->len = entry_start;
4493 9 : continue;
4494 : }
4495 931 : first = false;
4496 931 : any_frame_written = true;
4497 : }
4498 :
4499 135 : bool array_content_is_accurate =
4500 135 : any_frame_written || depth <= CLOG_BT_INITIAL_FRAME;
4501 135 : if (array_content_is_accurate && buf_append(b, "]", 1) == 0) return true;
4502 :
4503 1 : b->len = bt_start;
4504 1 : return buf_append(b, BT_JSON_ERROR_MARKER,
4505 1 : sizeof(BT_JSON_ERROR_MARKER) - 1) == 0;
4506 : }
4507 :
4508 : // Gives the HOSTNAME field of sh's syslog records, the cached name or "-" when
4509 : // it's empty, so the record headers and the backtrace lines agree.
4510 57 : static inline const char *clog_syslog_hostname(const clog_shared *sh) {
4511 57 : return sh->syslog_hostname[0] ? sh->syslog_hostname : "-";
4512 : }
4513 :
4514 : // Writes the one syslog record that says a requested backtrace is missing, used
4515 : // by emit_backtrace_syslog_lines() for a failed capture and for frames that all
4516 : // failed to append. It builds the record in out, and when not even that fits it
4517 : // writes a fixed line from a stack buffer straight to the fd, so the loss is
4518 : // never silent. out is left reset on every path, since out can be the async
4519 : // batch and stale bytes there would be written again. Needs sh->mutex.
4520 4 : static void write_backtrace_unavailable_syslog_marker(
4521 : clog_buf *out, clog_shared *sh, clog_level level,
4522 : const struct timeval *ts) {
4523 4 : int pri = (int)sh->syslog_facility * 8 + SYSLOG_SEVERITY[level];
4524 4 : const char *hostname = clog_syslog_hostname(sh);
4525 4 : const char *appname = sh->syslog_appname;
4526 4 : const char *msgid = LEVEL_STR[level];
4527 :
4528 4 : buf_reset(out);
4529 4 : bool ok = buf_appendf(out, "<%d>1 ", pri) == 0;
4530 4 : ok = ok && buf_append_ts_at(out, ts) == 0;
4531 6 : ok = ok &&
4532 3 : buf_appendf(out,
4533 : " %s %s %d %s - #error backtrace "
4534 : "unavailable\n",
4535 3 : hostname, appname, (int)clog_tident_get()->pid, msgid) == 0;
4536 4 : if (ok) {
4537 3 : clog_write_record(sh, CLOG_FMT_SYSLOG, out->data, out->len);
4538 : } else {
4539 1 : struct tm tm;
4540 1 : gmtime_r(&ts->tv_sec, &tm);
4541 1 : char fallback[512];
4542 1 : int n = snprintf(fallback, sizeof(fallback),
4543 : "<%d>1 %04d-%02d-%02dT%02d:%02d:%02d.%06ldZ %s %s %d %s - "
4544 : "#error backtrace unavailable\n",
4545 1 : pri, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
4546 1 : tm.tm_hour, tm.tm_min, tm.tm_sec, (long)ts->tv_usec,
4547 1 : hostname, appname, (int)clog_tident_get()->pid, msgid);
4548 1 : if (n > 0) {
4549 2 : size_t len =
4550 1 : (size_t)n < sizeof(fallback) ? (size_t)n : sizeof(fallback) - 1;
4551 1 : clog_write_record(sh, CLOG_FMT_SYSLOG, fallback, len);
4552 : }
4553 : }
4554 4 : buf_reset(out);
4555 4 : }
4556 :
4557 : // Writes the frames of a syslog record as separate RFC 5424 messages, one write
4558 : // each, never batched, because one write is one datagram. out is scratch space,
4559 : // reset before each frame and left reset at the end; a frame whose appends fail
4560 : // partway is skipped rather than written in part. ts is the primary record's
4561 : // own timestamp, captured at submission. A NULL syms, or real frames that all
4562 : // failed, write the "backtrace unavailable" marker; a capture with no user
4563 : // frame writes nothing. Needs sh->mutex.
4564 12 : static void emit_backtrace_syslog_lines(clog_buf *out, clog_shared *sh,
4565 : clog_level level,
4566 : const struct timeval *ts,
4567 : char *const *syms, int depth) {
4568 12 : int pri = (int)sh->syslog_facility * 8 + SYSLOG_SEVERITY[level];
4569 12 : const char *hostname = clog_syslog_hostname(sh);
4570 12 : const char *appname = sh->syslog_appname;
4571 12 : const char *msgid = LEVEL_STR[level];
4572 :
4573 12 : if (!syms) {
4574 3 : write_backtrace_unavailable_syslog_marker(out, sh, level, ts);
4575 3 : return;
4576 : }
4577 :
4578 : bool any_frame_written = false;
4579 65 : for (int i = CLOG_BT_INITIAL_FRAME; i < depth; i++) {
4580 56 : buf_reset(out);
4581 56 : bool ok = buf_appendf(out, "<%d>1 ", pri) == 0;
4582 56 : ok = ok && buf_append_ts_at(out, ts) == 0;
4583 112 : ok = ok && buf_appendf(out, " %s %s %d %s - #%d ", hostname, appname,
4584 56 : (int)clog_tident_get()->pid, msgid,
4585 : i - CLOG_BT_INITIAL_FRAME) == 0;
4586 56 : ok = ok && buf_append_ctrl_escaped(out, syms[i]) == 0;
4587 56 : ok = ok && buf_append(out, "\n", 1) == 0;
4588 : #ifdef RUNNING_UNIT_TESTS
4589 56 : if (atomic_load(&clog_test_force_all_syslog_bt_frames_fail)) ok = false;
4590 : #endif
4591 56 : if (!ok) continue;
4592 49 : clog_write_record(sh, CLOG_FMT_SYSLOG, out->data, out->len);
4593 49 : any_frame_written = true;
4594 : }
4595 9 : buf_reset(out);
4596 :
4597 9 : if (!any_frame_written && depth > CLOG_BT_INITIAL_FRAME) {
4598 1 : write_backtrace_unavailable_syslog_marker(out, sh, level, ts);
4599 : }
4600 : }
4601 :
4602 : #ifdef RUNNING_UNIT_TESTS
4603 :
4604 : // Runs the failed-capture branch of emit_backtrace_syslog_lines() against
4605 : // logger's target under its mutex, so a test can reach its last-resort
4606 : // fallback.
4607 1 : void clog__test_emit_backtrace_syslog_unavailable_marker(clog logger,
4608 : clog_level level) {
4609 1 : struct clogger *lg = clog_resolve(logger);
4610 1 : if (!lg) return;
4611 1 : struct timeval ts;
4612 1 : gettimeofday(&ts, NULL);
4613 1 : ccol__mutex_lock(lg->shared->mutex);
4614 1 : if (lg->shared->fd >= 0)
4615 1 : emit_backtrace_syslog_lines(&lg->buf, lg->shared, level, &ts, NULL, 0);
4616 1 : ccol__mutex_unlock(lg->shared->mutex);
4617 1 : clog_resolve_unpin(lg);
4618 : }
4619 : #endif
4620 :
4621 : // What an async queue message carries: A record job, a flush request, or a wake
4622 : // (a plain flush with nothing attached, see clog_wake_writer()).
4623 : typedef enum {
4624 : CLOG_ASYNC_MSG_JOB,
4625 : CLOG_ASYNC_MSG_FLUSH,
4626 : CLOG_ASYNC_MSG_WAKE
4627 : } clog_async_msg_kind;
4628 :
4629 : // One field of a job's snapshot, as offsets into field_pool. Offsets, because
4630 : // the pool can move while snapshot_fields() builds it.
4631 : typedef struct {
4632 : size_t key_offset;
4633 : size_t value_offset;
4634 : } clog_field_view;
4635 :
4636 : // One record for the writer thread, complete in itself: Everything
4637 : // clog_build_record() needs, captured by the submitting thread at submission,
4638 : // since the writer may build it much later on another thread.
4639 : typedef struct clog_async_job {
4640 : clog_level level;
4641 : const char *file;
4642 : int line;
4643 : const char *func;
4644 : // Timestamp and identity of the submitting thread, captured at submission.
4645 : bool with_backtrace;
4646 : struct timeval ts;
4647 : char proc_val[CLOG_PROC_VAL_LEN];
4648 :
4649 : // The message: msg points at msg_inline, or at msg_heap when it spilled.
4650 : char msg_inline[256];
4651 : char *msg_heap;
4652 : const char *msg;
4653 :
4654 : // The field snapshot: field_count views into field_pool.
4655 : // fields_snapshot_failed is true only when the snapshot couldn't be taken,
4656 : // which differs from a logger with no fields.
4657 : clog_field_view *fields;
4658 : size_t field_count;
4659 : ccol_growbuf field_pool;
4660 : bool fields_snapshot_failed;
4661 :
4662 : // The backtrace captured on the calling thread.
4663 : char **bt_syms;
4664 : int bt_depth;
4665 : } clog_async_job;
4666 :
4667 : // The rendezvous of a flush request. The asking thread waits on cv until the
4668 : // writer thread, having flushed everything queued before the request, sets
4669 : // done. It lives on the asking thread's stack (the exit drain keeps its own on
4670 : // the heap); the writer never frees it.
4671 : typedef struct {
4672 : ccol__mutex mutex;
4673 : ccol__cond_var cv;
4674 : bool done;
4675 : } clog_async_ctrl;
4676 :
4677 : // The envelope that goes through the queue, with an explicit kind. A job sits
4678 : // in it by value, so the envelope is the job's only allocation; the writer
4679 : // frees it, or clog_write_async() when the send fails. ctrl points at the
4680 : // asker's clog_async_ctrl and is never freed by the writer.
4681 : typedef struct clog_async_msg {
4682 : clog_async_msg_kind kind;
4683 : union {
4684 : clog_async_job job;
4685 : clog_async_ctrl *ctrl;
4686 : } u;
4687 : } clog_async_msg;
4688 :
4689 : // Where a record's fields come from: A logger's live map read under its
4690 : // fields_mutex (synchronous and fatal paths), or a snapshot taken at submission
4691 : // (async path). failed marks a snapshot that couldn't be taken. One loop,
4692 : // clog_emit_fields(), serves both.
4693 : typedef struct {
4694 : bool is_live;
4695 : union {
4696 : struct {
4697 : chmap fields;
4698 : ccol__mutex *mutex;
4699 : } live;
4700 : struct {
4701 : const clog_field_view *views;
4702 : size_t count;
4703 : const char *pool;
4704 : bool failed;
4705 : } snap;
4706 : } u;
4707 : } clog_field_source;
4708 :
4709 : // Appends one field as " k=v", the logfmt primitive of clog_emit_fields(); the
4710 : // value goes through the logfmt escaper. Returns 0 or -1.
4711 1539 : static int append_field_logfmt(clog_buf *b, const char *k, const char *v) {
4712 1539 : if (buf_appendf(b, " %s=", k) != 0) return -1;
4713 1539 : return buf_append_lv(b, v);
4714 : }
4715 :
4716 : // Appends one field as an SD-PARAM, the syslog primitive of clog_emit_fields();
4717 : // the name is limited to 32 characters and the value escaped. Returns 0 or -1.
4718 14 : static int append_field_syslog_sd(clog_buf *b, const char *k, const char *v) {
4719 14 : char param_name[33];
4720 14 : sd_param_name(k, param_name);
4721 14 : if (buf_append(b, " ", 1) != 0) return -1;
4722 14 : if (buf_append(b, param_name, strlen(param_name)) != 0) return -1;
4723 14 : if (buf_append(b, "=\"", 2) != 0) return -1;
4724 14 : if (buf_append_sd_value(b, v) != 0) return -1;
4725 14 : return buf_append(b, "\"", 1);
4726 : }
4727 :
4728 : // Appends every field of src to out in fmt's shape, for clog_build_record(). A
4729 : // live source is walked under its mutex with ccol_chmap_walk_next(), which
4730 : // allocates nothing, so a record never loses its fields to an allocation and
4731 : // they come out in the order they were first set. A field that fails partway is
4732 : // rolled back. Returns false when the fields can't all go in;
4733 : // *out_alloc_failure tells an allocation failure from a record that is too
4734 : // large.
4735 41377 : static bool clog_emit_fields(clog_buf *out, clog_format fmt,
4736 : const clog_field_source *src,
4737 : bool *out_alloc_failure) {
4738 41377 : *out_alloc_failure = false;
4739 82754 : int (*append_fn)(clog_buf *, const char *, const char *) =
4740 : (fmt == CLOG_FMT_JSON) ? buf_append_json_kv
4741 41377 : : (fmt == CLOG_FMT_SYSLOG) ? append_field_syslog_sd
4742 34384 : : append_field_logfmt;
4743 :
4744 41377 : if (src->is_live) {
4745 15117 : chmap fields = src->u.live.fields;
4746 15117 : ccol__mutex_lock(*src->u.live.mutex);
4747 15117 : ccol_chmap_walk walk = {0};
4748 15117 : const void *kv;
4749 15117 : const void *vv;
4750 15117 : bool ok = true;
4751 16991 : while (ccol_chmap_walk_next(fields, &walk, &kv, &vv)) {
4752 1875 : size_t field_start = out->len;
4753 1875 : if (append_fn(out, (const char *)kv, (const char *)vv) != 0) {
4754 1 : out->len = field_start;
4755 1 : ok = false;
4756 1 : break;
4757 : }
4758 : }
4759 15117 : ccol__mutex_unlock(*src->u.live.mutex);
4760 15117 : return ok;
4761 : }
4762 :
4763 26260 : if (src->u.snap.failed) {
4764 3 : *out_alloc_failure = true;
4765 3 : return false;
4766 : }
4767 26275 : for (size_t i = 0; i < src->u.snap.count; i++) {
4768 19 : const char *k = src->u.snap.pool + src->u.snap.views[i].key_offset;
4769 19 : const char *v = src->u.snap.pool + src->u.snap.views[i].value_offset;
4770 19 : size_t field_start = out->len;
4771 19 : if (append_fn(out, k, v) != 0) {
4772 1 : out->len = field_start;
4773 1 : return false;
4774 : }
4775 : }
4776 : return true;
4777 : }
4778 :
4779 : // Appends the fixed part of a record (ts, level, proc, src and func) in fmt's
4780 : // shape, the first step of clog_build_record(). For syslog it also writes the
4781 : // RFC 5424 preamble and opens the "[ccol ..." element, which the fields then
4782 : // fill and clog_build_msg_and_close() closes. A src too long for the stack
4783 : // buffer goes through a heap copy so it's still escaped; a failed allocation
4784 : // there sets out->oom. Returns false on failure. Needs sh->mutex.
4785 41379 : static bool clog_build_header(clog_buf *out, clog_shared *sh, clog_format fmt,
4786 : clog_level level, const struct timeval *ts,
4787 : const char *proc_val, const char *file, int line,
4788 : const char *func) {
4789 41379 : bool ok = true;
4790 :
4791 41379 : if (fmt == CLOG_FMT_JSON) {
4792 6993 : ok = ok && buf_append(out, "{\"ts\":\"", 7) == 0;
4793 6993 : ok = ok && buf_append_ts_at(out, ts) == 0;
4794 6993 : ok = ok && buf_append(out, "\"", 1) == 0;
4795 6993 : ok = ok && buf_appendf(out, ",\"level\":\"%s\"", LEVEL_STR[level]) == 0;
4796 6993 : ok = ok && buf_append(out, ",\"proc\":\"", 9) == 0;
4797 6993 : ok = ok && buf_append_json_content(out, proc_val) == 0;
4798 6993 : ok = ok && buf_append(out, "\"", 1) == 0;
4799 6993 : ok = ok && buf_append(out, ",\"src\":\"", 8) == 0;
4800 6993 : ok = ok && buf_append_json_content(out, file) == 0;
4801 6993 : ok = ok && buf_appendf(out, ":%d\"", line) == 0;
4802 6993 : ok = ok && buf_append(out, ",\"func\":\"", 9) == 0;
4803 6993 : ok = ok && buf_append_json_content(out, func) == 0;
4804 6993 : ok = ok && buf_append(out, "\"", 1) == 0;
4805 34386 : } else if (fmt == CLOG_FMT_SYSLOG) {
4806 39 : int pri = (int)sh->syslog_facility * 8 + SYSLOG_SEVERITY[level];
4807 39 : const char *hostname = clog_syslog_hostname(sh);
4808 39 : const char *appname = sh->syslog_appname;
4809 39 : ok = ok && buf_appendf(out, "<%d>1 ", pri) == 0;
4810 39 : ok = ok && buf_append_ts_at(out, ts) == 0;
4811 39 : ok = ok && buf_appendf(out, " %s %s %d %s", hostname, appname,
4812 78 : (int)clog_tident_get()->pid, LEVEL_STR[level]) == 0;
4813 39 : ok = ok && buf_append(out, " [ccol proc=\"", 13) == 0;
4814 39 : ok = ok && buf_append_sd_value(out, proc_val) == 0;
4815 39 : ok = ok && buf_append(out, "\" src=\"", 7) == 0;
4816 39 : ok = ok && buf_append_sd_value(out, file) == 0;
4817 39 : ok = ok && buf_appendf(out, ":%d\" func=\"", line) == 0;
4818 39 : ok = ok && buf_append_sd_value(out, func) == 0;
4819 39 : ok = ok && buf_append(out, "\"", 1) == 0;
4820 : } else {
4821 34347 : ok = ok && buf_append(out, "ts=", 3) == 0;
4822 34347 : ok = ok && buf_append_ts_at(out, ts) == 0;
4823 34346 : ok = ok && buf_appendf(out, " level=%s", LEVEL_STR[level]) == 0;
4824 34346 : ok = ok && buf_append(out, " proc=", 6) == 0;
4825 34346 : ok = ok && buf_append_lv(out, proc_val) == 0;
4826 34346 : ok = ok && buf_append(out, " src=", 5) == 0;
4827 : {
4828 34347 : char src_stack[512];
4829 34347 : char *src_val = src_stack;
4830 34347 : char *src_heap = NULL;
4831 34347 : int slen = snprintf(src_stack, sizeof(src_stack), "%s:%d", file, line);
4832 34347 : if (slen < 0) {
4833 : ok = false;
4834 34347 : } else if ((size_t)slen >= sizeof(src_stack)) {
4835 2 : src_heap = ccol__mem_alloc(sh->m_procs, (size_t)slen + 1);
4836 2 : if (!src_heap) {
4837 1 : out->oom = true;
4838 1 : ok = false;
4839 1 : } else if (snprintf(src_heap, (size_t)slen + 1, "%s:%d", file, line) <
4840 : 0) {
4841 : ok = false;
4842 : } else {
4843 1 : src_val = src_heap;
4844 : }
4845 : }
4846 34347 : ok = ok && buf_append_lv(out, src_val) == 0;
4847 34347 : ccol__mem_free(sh->m_procs, src_heap);
4848 : }
4849 34347 : ok = ok && buf_append(out, " func=", 6) == 0;
4850 34347 : ok = ok && buf_append_lv(out, func) == 0;
4851 : }
4852 :
4853 41379 : return ok;
4854 : }
4855 :
4856 : // Appends the message and the punctuation that ends the record, plus the JSON
4857 : // backtrace array when with_backtrace is set; the last step of
4858 : // clog_build_record(). logfmt and syslog frames are added by their callers
4859 : // after the record. Returns false on failure. Needs sh->mutex.
4860 41372 : static bool clog_build_msg_and_close(clog_buf *out, clog_format fmt,
4861 : const char *msg, bool with_backtrace,
4862 : char *const *bt_syms, int bt_depth) {
4863 41372 : bool ok = true;
4864 :
4865 41372 : if (fmt == CLOG_FMT_JSON) {
4866 6993 : ok = ok && buf_append(out, ",\"msg\":\"", 8) == 0;
4867 6993 : ok = ok && buf_append_json_content(out, msg) == 0;
4868 6991 : ok = ok && buf_append(out, "\"", 1) == 0;
4869 6993 : if (ok && with_backtrace) ok = emit_backtrace_json(out, bt_syms, bt_depth);
4870 6996 : ok = ok && buf_append(out, "}\n", 2) == 0;
4871 34379 : } else if (fmt == CLOG_FMT_SYSLOG) {
4872 39 : ok = ok && buf_append(out, "] ", 2) == 0;
4873 39 : ok = ok && buf_append_ctrl_escaped(out, msg) == 0;
4874 39 : ok = ok && buf_append(out, "\n", 1) == 0;
4875 : } else {
4876 34340 : ok = ok && buf_append(out, " msg=", 5) == 0;
4877 34340 : ok = ok && buf_append_lv(out, msg) == 0;
4878 34340 : ok = ok && buf_append(out, "\n", 1) == 0;
4879 : }
4880 :
4881 41372 : return ok;
4882 : }
4883 :
4884 : // Appends a small placeholder record in place of one that couldn't be built, so
4885 : // nothing vanishes silently. alloc_failure picks the message: An allocation
4886 : // failure, or a record larger than out->cap_limit. It starts at out->len (the
4887 : // caller already rolled back) and never resets out, because out can be a batch
4888 : // holding other records. With with_backtrace it adds the JSON marker. Returns
4889 : // false, leaving out as it was, when even the placeholder doesn't fit (only
4890 : // possible in a nearly full batch).
4891 100 : static bool clog_build_fallback_record(clog_buf *out, clog_shared *sh,
4892 : clog_format fmt, clog_level level,
4893 : const struct timeval *ts,
4894 : const char *msg, const char *proc_val,
4895 : bool alloc_failure,
4896 : bool with_backtrace) {
4897 100 : size_t fallback_start = out->len;
4898 100 : char note[160];
4899 100 : if (alloc_failure) {
4900 8 : snprintf(note, sizeof(note),
4901 : "log record dropped: a transient allocation failure prevented "
4902 : "it from being fully built");
4903 : } else {
4904 92 : snprintf(note, sizeof(note),
4905 : "log record too large to emit (%zu byte message; %zu byte "
4906 : "limit)",
4907 : strlen(msg), out->cap_limit);
4908 : }
4909 :
4910 100 : bool ok = true;
4911 100 : if (fmt == CLOG_FMT_JSON) {
4912 3 : ok = ok && buf_append(out, "{\"ts\":\"", 7) == 0;
4913 3 : ok = ok && buf_append_ts_at(out, ts) == 0;
4914 3 : ok = ok && buf_appendf(out, "\",\"level\":\"%s\"", LEVEL_STR[level]) == 0;
4915 3 : ok = ok && buf_append(out, ",\"proc\":\"", 9) == 0;
4916 3 : ok = ok && buf_append_json_content(out, proc_val) == 0;
4917 3 : ok = ok && buf_append(out, "\",\"msg\":\"", 9) == 0;
4918 3 : ok = ok && buf_append_json_content(out, note) == 0;
4919 3 : ok = ok && buf_append(out, "\"", 1) == 0;
4920 3 : if (ok && with_backtrace)
4921 2 : ok = buf_append(out, BT_JSON_ERROR_MARKER,
4922 : sizeof(BT_JSON_ERROR_MARKER) - 1) == 0;
4923 3 : ok = ok && buf_append(out, "}\n", 2) == 0;
4924 97 : } else if (fmt == CLOG_FMT_SYSLOG) {
4925 2 : int pri = (int)sh->syslog_facility * 8 + SYSLOG_SEVERITY[level];
4926 2 : const char *hostname = clog_syslog_hostname(sh);
4927 2 : const char *appname = sh->syslog_appname;
4928 2 : ok = ok && buf_appendf(out, "<%d>1 ", pri) == 0;
4929 2 : ok = ok && buf_append_ts_at(out, ts) == 0;
4930 2 : ok = ok && buf_appendf(out, " %s %s %d %s [ccol proc=\"", hostname, appname,
4931 4 : (int)clog_tident_get()->pid, LEVEL_STR[level]) == 0;
4932 2 : ok = ok && buf_append_sd_value(out, proc_val) == 0;
4933 2 : ok = ok && buf_append(out, "\"] ", 3) == 0;
4934 2 : ok = ok && buf_append_ctrl_escaped(out, note) == 0;
4935 2 : ok = ok && buf_append(out, "\n", 1) == 0;
4936 : } else {
4937 95 : ok = ok && buf_append(out, "ts=", 3) == 0;
4938 95 : ok = ok && buf_append_ts_at(out, ts) == 0;
4939 94 : ok = ok && buf_appendf(out, " level=%s proc=", LEVEL_STR[level]) == 0;
4940 94 : ok = ok && buf_append_lv(out, proc_val) == 0;
4941 94 : ok = ok && buf_append(out, " msg=", 5) == 0;
4942 94 : ok = ok && buf_append_lv(out, note) == 0;
4943 94 : ok = ok && buf_append(out, "\n", 1) == 0;
4944 : }
4945 :
4946 1 : if (!ok) out->len = fallback_start;
4947 100 : return ok;
4948 : }
4949 :
4950 : // Builds one complete record into out: Header, fields, message and close, and
4951 : // for logfmt the backtrace lines too, falling back to a placeholder on any
4952 : // failure. It's the one record builder of the synchronous, fatal and async
4953 : // paths; syslog frames are written by the caller afterwards. It resets out->oom
4954 : // first so an earlier build can't skew the verdict. Returns true once the
4955 : // record or its placeholder is in out; false, with out untouched, when even the
4956 : // placeholder doesn't fit, and the caller must empty out and retry.
4957 : // *out_used_fallback (may be NULL) says whether the placeholder stood in; a
4958 : // batch caller uses it to retry a small record in an empty buffer instead of
4959 : // calling it too large. Needs sh->mutex.
4960 41379 : static bool clog_build_record(clog_buf *out, clog_shared *sh, clog_format fmt,
4961 : clog_level level, const struct timeval *ts,
4962 : const char *proc_val, const char *file, int line,
4963 : const char *func, const char *msg,
4964 : const clog_field_source *field_src,
4965 : bool with_backtrace, char *const *bt_syms,
4966 : int bt_depth, bool *out_used_fallback) {
4967 41379 : size_t record_start = out->len;
4968 41379 : out->oom = false;
4969 41379 : bool ok =
4970 41379 : clog_build_header(out, sh, fmt, level, ts, proc_val, file, line, func);
4971 41379 : bool alloc_failure = false;
4972 41379 : if (ok) ok = clog_emit_fields(out, fmt, field_src, &alloc_failure);
4973 41377 : if (ok)
4974 41372 : ok = clog_build_msg_and_close(out, fmt, msg, with_backtrace, bt_syms,
4975 : bt_depth);
4976 41379 : if (!alloc_failure) alloc_failure = out->oom;
4977 :
4978 41379 : bool logfmt_bt = with_backtrace && fmt == CLOG_FMT_LOGFMT;
4979 41379 : if (ok && logfmt_bt && !emit_backtrace_lines(out, bt_syms, bt_depth)) {
4980 1 : ok = false;
4981 1 : if (!alloc_failure) alloc_failure = out->oom;
4982 : }
4983 :
4984 41379 : if (out_used_fallback) *out_used_fallback = !ok;
4985 41379 : if (!ok) {
4986 100 : out->len = record_start;
4987 100 : if (!clog_build_fallback_record(out, sh, fmt, level, ts, msg, proc_val,
4988 : alloc_failure, with_backtrace)) {
4989 1 : out->len = record_start;
4990 1 : return false;
4991 : }
4992 99 : if (logfmt_bt) {
4993 2 : (void)emit_backtrace_lines(out, bt_syms, bt_depth);
4994 : }
4995 : }
4996 : return true;
4997 : }
4998 :
4999 : // Writes a minimal record straight to the fd from a stack buffer, the last
5000 : // resort when not even clog_build_record()'s placeholder fits. With the current
5001 : // buffer sizes that can't happen; the function keeps a future change from
5002 : // turning it into a silent loss. It allocates nothing and can't fail the same
5003 : // way. With with_backtrace, JSON gets its marker inside the line and logfmt
5004 : // gets a marker line; syslog callers write their frames separately. Needs
5005 : // sh->mutex and sh->fd >= 0.
5006 6 : static void clog_write_unrepresentable_record(clog_shared *sh, clog_format fmt,
5007 : clog_level level,
5008 : bool with_backtrace) {
5009 6 : static const char note[] =
5010 : "log record dropped: could not be represented within the buffer size "
5011 : "limit";
5012 6 : char line[256];
5013 6 : int n;
5014 6 : if (fmt == CLOG_FMT_JSON) {
5015 1 : n = with_backtrace ? snprintf(line, sizeof(line),
5016 : "{\"level\":\"%s\",\"msg\":\"%s\","
5017 : "\"bt_error\":\"unavailable\"}\n",
5018 1 : LEVEL_STR[level], note)
5019 2 : : snprintf(line, sizeof(line),
5020 : "{\"level\":\"%s\",\"msg\":\"%s\"}\n",
5021 1 : LEVEL_STR[level], note);
5022 4 : } else if (fmt == CLOG_FMT_SYSLOG) {
5023 2 : int pri = (int)sh->syslog_facility * 8 + SYSLOG_SEVERITY[level];
5024 2 : n = snprintf(line, sizeof(line), "<%d>1 - - - - - - %s\n", pri, note);
5025 : } else {
5026 2 : n = snprintf(line, sizeof(line), "level=%s msg=\"%s\"\n", LEVEL_STR[level],
5027 : note);
5028 : }
5029 6 : if (n > 0) {
5030 6 : size_t len = (size_t)n < sizeof(line) ? (size_t)n : sizeof(line) - 1;
5031 6 : clog_write_record(sh, fmt, line, len);
5032 : }
5033 :
5034 6 : if (with_backtrace && fmt == CLOG_FMT_LOGFMT) {
5035 1 : clog_write_record(sh, fmt, BT_LINE_ERROR_MARKER,
5036 : sizeof(BT_LINE_ERROR_MARKER) - 1);
5037 : }
5038 6 : }
5039 :
5040 : #ifdef RUNNING_UNIT_TESTS
5041 :
5042 : // Runs clog_write_unrepresentable_record() against logger's target under its
5043 : // mutex, so a test can check it; the ordinary path can't reach it with the
5044 : // current buffer sizes.
5045 5 : void clog__test_write_unrepresentable_record(clog logger, clog_format fmt,
5046 : clog_level level,
5047 : bool with_backtrace) {
5048 5 : struct clogger *lg = clog_resolve(logger);
5049 5 : if (!lg) return;
5050 5 : ccol__mutex_lock(lg->shared->mutex);
5051 5 : if (lg->shared->fd >= 0)
5052 5 : clog_write_unrepresentable_record(lg->shared, fmt, level, with_backtrace);
5053 5 : ccol__mutex_unlock(lg->shared->mutex);
5054 5 : clog_resolve_unpin(lg);
5055 : }
5056 : #endif
5057 :
5058 : // Creates a logger's field map (string to string) with m_procs, for
5059 : // logger_alloc(). Returns the map or NULL.
5060 3720 : static chmap fields_create(ccol_memmgmt_procs *m_procs) {
5061 3720 : char *err = NULL;
5062 7440 : chmap m = chashmap_create_mp(CHMAP_DEFAULT_INITIAL_BUCKET_ARRAY_SIZE,
5063 : ccol_string, ccol_string, m_procs, &err);
5064 3720 : return m;
5065 : }
5066 :
5067 : // Frees a clog_shared that has no live mutex and no loggers, used by the
5068 : // constructors' rollback paths and the final teardown. It's safe at any point
5069 : // after shared_alloc() set m_procs. It never closes sh->fd, because on an early
5070 : // failure the constructor's caller still owns it; callers that own the fd close
5071 : // it first with shared_close_owned_fd().
5072 1471 : static void shared_free_partial(clog_shared *sh) {
5073 1471 : ccol__mem_free(sh->m_procs, sh->file_path);
5074 1471 : ccol_memmgmt_procs *mp = sh->m_procs;
5075 1471 : if (mp) {
5076 497 : ccol_free free_fn = mp->free;
5077 497 : free_fn(mp);
5078 497 : free_fn(sh);
5079 : } else {
5080 974 : free(sh);
5081 : }
5082 1471 : }
5083 :
5084 : // Closes sh->fd when sh owns it (a file logger) and it's open, and always
5085 : // closes dir_fd, then marks both closed. clog_close() and every constructor
5086 : // rollback use it so a later failed step doesn't leak the fd just opened. An fd
5087 : // the caller owns (clog_create_from_fd_mp()) is left alone.
5088 1457 : static void shared_close_owned_fd(clog_shared *sh) {
5089 1457 : if (sh->owns_fd && sh->fd >= 0) {
5090 566 : close(sh->fd);
5091 566 : sh->fd = -1;
5092 : }
5093 1457 : if (sh->dir_fd >= 0) {
5094 169 : close(sh->dir_fd);
5095 169 : sh->dir_fd = -1;
5096 : }
5097 1457 : }
5098 :
5099 : // Allocates and initializes a clog_shared for the constructors: Copies the
5100 : // procs and the path, creates the mutex, classifies the sink and caches the
5101 : // sanitized hostname and APP-NAME (the raw hostname may hold bytes that would
5102 : // split a syslog record). fd and dir_fd stay owned by the caller until it
5103 : // succeeds. Returns NULL on failure.
5104 1528 : static clog_shared *shared_alloc(int fd, bool owns_fd, const char *file_path,
5105 : int dir_fd, ccol_memmgmt_procs *m_procs) {
5106 1528 : clog_shared *sh = ccol__mem_calloc(m_procs, 1, sizeof(*sh));
5107 1528 : if (!sh) return NULL;
5108 :
5109 1524 : sh->fd = fd;
5110 1524 : sh->owns_fd = owns_fd;
5111 1524 : sh->sink_kind = clog_classify_sink(fd);
5112 1524 : sh->sink_per_record = clog_sink_is_message(fd);
5113 1524 : sh->ref_count = 1;
5114 1524 : sh->dir_fd = -1;
5115 :
5116 1524 : if (m_procs) {
5117 504 : sh->m_procs = (ccol_memmgmt_procs *)m_procs->malloc(sizeof(*m_procs));
5118 504 : if (!sh->m_procs) {
5119 4 : m_procs->free(sh);
5120 4 : return NULL;
5121 : }
5122 500 : memcpy(sh->m_procs, m_procs, sizeof(*m_procs));
5123 : }
5124 :
5125 1520 : if (file_path) {
5126 593 : size_t len = strlen(file_path) + 1;
5127 593 : sh->file_path = ccol__mem_alloc(sh->m_procs, len);
5128 593 : if (!sh->file_path) {
5129 2 : shared_free_partial(sh);
5130 2 : return NULL;
5131 : }
5132 591 : memcpy(sh->file_path, file_path, len);
5133 1173 : sh->file_base = path_base(sh->file_path);
5134 : }
5135 :
5136 1518 : if (ccol__mutex_init(sh->mutex) != 0) {
5137 0 : shared_free_partial(sh);
5138 0 : return NULL;
5139 : }
5140 :
5141 1518 : sh->dir_fd = dir_fd;
5142 1518 : sh->last_rotation = clog_wall_now();
5143 :
5144 1518 : sh->syslog_facility = CLOG_SYSLOG_USER;
5145 :
5146 1518 : char raw_hostname[256];
5147 1518 : if (gethostname(raw_hostname, sizeof(raw_hostname)) != 0)
5148 0 : raw_hostname[0] = '\0';
5149 1518 : raw_hostname[sizeof(raw_hostname) - 1] = '\0';
5150 1518 : sanitize_syslog_printusascii_field(raw_hostname, sh->syslog_hostname,
5151 : sizeof(sh->syslog_hostname));
5152 :
5153 3036 : sanitize_syslog_printusascii_field(
5154 1518 : syslog_appname_compute(), sh->syslog_appname, sizeof(sh->syslog_appname));
5155 :
5156 1518 : return sh;
5157 : }
5158 :
5159 : // Allocates a logger on shared at min_level, with its field map, fields_mutex
5160 : // and record buffer, for alloc() and clog_derive(). It doesn't touch shared's
5161 : // reference count. Returns NULL on failure.
5162 3733 : static struct clogger *logger_alloc(clog_shared *shared, clog_level min_level) {
5163 3733 : struct clogger *lg = ccol__mem_calloc(shared->m_procs, 1, sizeof(*lg));
5164 3733 : if (!lg) return NULL;
5165 :
5166 3726 : if (buf_init(&lg->buf, shared->m_procs) != 0) {
5167 6 : ccol__mem_free(shared->m_procs, lg);
5168 6 : return NULL;
5169 : }
5170 :
5171 3720 : lg->fields = fields_create(shared->m_procs);
5172 3720 : if (!lg->fields) {
5173 6 : buf_free(&lg->buf);
5174 6 : ccol__mem_free(shared->m_procs, lg);
5175 6 : return NULL;
5176 : }
5177 :
5178 3714 : if (ccol__mutex_init(lg->fields_mutex) != 0) {
5179 0 : chashmap__destroy(lg->fields);
5180 0 : buf_free(&lg->buf);
5181 0 : ccol__mem_free(shared->m_procs, lg);
5182 0 : return NULL;
5183 : }
5184 :
5185 3714 : lg->shared = shared;
5186 3714 : lg->min_level = min_level;
5187 3714 : return lg;
5188 : }
5189 :
5190 : // Frees a fully built logger (field map, buffer, fields_mutex) without touching
5191 : // the shared store, for clog_close() and the rollback paths.
5192 3669 : static void logger_free(struct clogger *lg) {
5193 3669 : ccol__mutex_destroy(lg->fields_mutex);
5194 3669 : chashmap__destroy(lg->fields);
5195 3669 : lg->fields = NULL;
5196 3669 : buf_free(&lg->buf);
5197 3669 : ccol__mem_free(lg->shared->m_procs, lg);
5198 3669 : }
5199 :
5200 : // Builds a new shared store and its first logger, the common start of both
5201 : // public constructors. On failure it frees what it built and returns NULL; the
5202 : // caller still owns fd and dir_fd.
5203 1528 : static struct clogger *alloc(int fd, bool owns_fd, const char *file_path,
5204 : int dir_fd, clog_level min_level,
5205 : ccol_memmgmt_procs *m_procs) {
5206 1528 : clog_shared *sh = shared_alloc(fd, owns_fd, file_path, dir_fd, m_procs);
5207 1528 : if (!sh) return NULL;
5208 :
5209 1518 : struct clogger *lg = logger_alloc(sh, min_level);
5210 1518 : if (!lg) {
5211 12 : ccol__mutex_destroy(sh->mutex);
5212 12 : shared_free_partial(sh);
5213 12 : return NULL;
5214 : }
5215 :
5216 : return lg;
5217 : }
5218 :
5219 : // Copies lg's fields under fields_mutex into *out_fields, *out_count and
5220 : // *out_pool, so a later change on lg can't alter a job already submitted; used
5221 : // by clog_write_async(). A logger without fields gets an empty pool with no
5222 : // allocation. *out_failed is set only on an allocation failure, with
5223 : // *out_fields NULL. The pool is never destroyed here; the job release does it
5224 : // on every path.
5225 26391 : static void snapshot_fields(struct clogger *lg, clog_field_view **out_fields,
5226 : size_t *out_count, ccol_growbuf *out_pool,
5227 : bool *out_failed) {
5228 26391 : *out_fields = NULL;
5229 26391 : *out_count = 0;
5230 26391 : *out_failed = false;
5231 :
5232 26391 : ccol__mutex_lock(lg->fields_mutex);
5233 26428 : size_t n = chashmap_size(lg->fields);
5234 26424 : if (n == 0) {
5235 26402 : ccol__mutex_unlock(lg->fields_mutex);
5236 26393 : out_pool->buf = NULL;
5237 26393 : out_pool->len = 0;
5238 26393 : out_pool->cap = 0;
5239 26393 : out_pool->oom = false;
5240 26393 : out_pool->m_procs = lg->shared->m_procs;
5241 26396 : return;
5242 : }
5243 22 : ccol_growbuf_init(out_pool, lg->shared->m_procs);
5244 :
5245 44 : clog_field_view *views =
5246 22 : ccol__mem_calloc(lg->shared->m_procs, n, sizeof(*views));
5247 22 : if (!views) {
5248 1 : ccol__mutex_unlock(lg->fields_mutex);
5249 1 : *out_failed = true;
5250 1 : return;
5251 : }
5252 :
5253 21 : ccol_chmap_walk walk = {0};
5254 21 : const void *kv;
5255 21 : const void *vv;
5256 21 : size_t i = 0;
5257 42 : while (i < n && ccol_chmap_walk_next(lg->fields, &walk, &kv, &vv)) {
5258 21 : views[i].key_offset = out_pool->len;
5259 21 : ccol_growbuf_append_cstr(out_pool, (const char *)kv);
5260 21 : ccol_growbuf_append_c(out_pool, '\0');
5261 21 : views[i].value_offset = out_pool->len;
5262 21 : ccol_growbuf_append_cstr(out_pool, (const char *)vv);
5263 21 : ccol_growbuf_append_c(out_pool, '\0');
5264 21 : i++;
5265 : }
5266 21 : ccol__mutex_unlock(lg->fields_mutex);
5267 :
5268 21 : if (out_pool->oom) {
5269 2 : ccol__mem_free(lg->shared->m_procs, views);
5270 2 : *out_failed = true;
5271 2 : return;
5272 : }
5273 :
5274 19 : *out_fields = views;
5275 19 : *out_count = n;
5276 : }
5277 :
5278 : // Tells whether a later attempt on the same descriptor can outlast write error
5279 : // err, which decides if undelivered bytes are kept or dropped. True for a
5280 : // resource that is used up for now (ENOSPC, EDQUOT, EFBIG, ENOBUFS, ENOMEM),
5281 : // for EAGAIN and EINTR, and for 0 (a write that made no progress); false for
5282 : // errors such as EPIPE, ECONNRESET, EBADF or EMSGSIZE.
5283 1131 : static bool clog_write_error_is_transient(int err) {
5284 285 : switch (err) {
5285 : case 0:
5286 : case EINTR:
5287 : case EAGAIN:
5288 : #if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
5289 : case EWOULDBLOCK:
5290 : #endif
5291 : case ENOSPC:
5292 : #if defined(EDQUOT)
5293 : case EDQUOT:
5294 : #endif
5295 : case EFBIG:
5296 : case ENOBUFS:
5297 : case ENOMEM:
5298 : return true;
5299 : default:
5300 6 : return false;
5301 : }
5302 : }
5303 :
5304 : // Tells where the first written bytes of data end, as a split value of
5305 : // async_partial_record, so a flush knows what a short write left open. The
5306 : // caller guarantees 0 < written < len.
5307 19 : static unsigned char clog_split_after(const char *data, size_t written) {
5308 19 : if (data[written - 1] != '\n') return CLOG_SPLIT_MID_LINE;
5309 1 : return data[written] == '\t' ? CLOG_SPLIT_AT_LINE : CLOG_SPLIT_NONE;
5310 : }
5311 :
5312 : static void clog_repair_split_record(clog_shared *sh, clog_format fmt,
5313 : int poll_timeout_ms);
5314 :
5315 : // Tells whether write error err means the output has no room (full disk, quota,
5316 : // RLIMIT_FSIZE), the case where a due rotation must not wait for a continuation
5317 : // that only the room it frees can deliver.
5318 220 : static bool clog_write_error_is_no_room(int err) {
5319 220 : switch (err) {
5320 : case ENOSPC:
5321 : #if defined(EDQUOT)
5322 : case EDQUOT:
5323 : #endif
5324 : case EFBIG:
5325 : return true;
5326 : default:
5327 : return false;
5328 : }
5329 : }
5330 :
5331 : // Gives the length of the next piece of a large backlog, so a flush can rotate
5332 : // between pieces: Up to the first record boundary where the file reaches
5333 : // max_file_size, or all n bytes when it doesn't or the backoff blocks the
5334 : // rotation. A boundary is a newline not followed by a tab. Needs sh->mutex;
5335 : // rotation is on.
5336 : static __attribute__((noinline, cold)) size_t
5337 947 : clog_backlog_piece(const clog_shared *sh, const char *data, size_t n) {
5338 947 : if (!sh->rotation.size_rotation_enabled) return n;
5339 947 : int64_t room = sh->rotation.max_file_size - (int64_t)sh->bytes_written;
5340 947 : if (room >= (int64_t)n) return n;
5341 601 : size_t from = 0;
5342 601 : if (room > 0)
5343 601 : from = (size_t)room - 1;
5344 0 : else if (!clog_rotate_retry_allowed(sh, clog_wall_now()))
5345 : return n;
5346 601 : const char *p = data + from;
5347 906 : while ((p = memchr(p, '\n', n - (size_t)(p - data))) != NULL) {
5348 906 : size_t b = (size_t)(p - data) + 1;
5349 906 : if (b == n || data[b] != '\t') return b;
5350 305 : p++;
5351 : }
5352 : return n;
5353 : }
5354 :
5355 : // Writes sh->async_buf to the fd with the time rotation check before and the
5356 : // size check after, the flush of every async path; poll_timeout_ms bounds the
5357 : // write. After a transient error the unwritten bytes stay at the front for the
5358 : // next flush, and async_partial_record records whether the written part split a
5359 : // record (no rotation and no other record then until the rest goes out). Any
5360 : // other error drops them with a marker. When the output is out of room and a
5361 : // rotation is due, a split continuation is given up so the rotation can free
5362 : // room, and the kept bytes get one more try in the new file. A backlog that
5363 : // would pass max_file_size goes out in pieces with rotation checks between.
5364 : // Nothing is written while a newline is owed; an owed repair with an empty
5365 : // batch is paid here. It never touches last_flush_monotonic. Needs sh->mutex;
5366 : // not for syslog targets.
5367 8138 : static void writer_flush_buffer(clog_shared *sh, int poll_timeout_ms) {
5368 8138 : bool may_retry = true;
5369 8140 : again:
5370 8140 : if (__builtin_expect(sh->async_buf.len == 0 &&
5371 6459 : (sh->async_partial_record & CLOG_OWED_REPAIR),
5372 : 0)) {
5373 23 : if (sh->fd >= 0) (void)clog_pay_owed(sh, sh->format, poll_timeout_ms);
5374 : }
5375 8140 : if (sh->async_buf.len > 0) {
5376 1681 : bool retained = false;
5377 1681 : int fd_before = sh->fd;
5378 1681 : if (sh->fd >= 0) {
5379 1681 : clog_time_rotate_if_due(sh);
5380 :
5381 1775 : if (__builtin_expect(sh->async_partial_record & CLOG_OWED_REPAIR, 0) &&
5382 94 : !clog_pay_owed(sh, sh->format, poll_timeout_ms)) {
5383 : retained = true;
5384 : } else {
5385 1679 : char *data = sh->async_buf.data;
5386 1679 : size_t len = sh->async_buf.len;
5387 1679 : size_t off = 0;
5388 1706 : int write_err;
5389 27 : for (;;) {
5390 1706 : size_t piece = len - off;
5391 1706 : if (__builtin_expect(sh->rotation_enabled, 0) &&
5392 965 : piece > sh->async_cfg.flush_buffer_size)
5393 947 : piece = clog_backlog_piece(sh, data + off, piece);
5394 1706 : errno = 0;
5395 1706 : size_t written = write_all(sh, data + off, piece, poll_timeout_ms);
5396 1698 : write_err = errno;
5397 1698 : if (sh->rotation_enabled) sh->bytes_written += (off_t)written;
5398 1698 : off += written;
5399 1698 : if (written < piece || off == len) break;
5400 27 : sh->async_partial_record &= (unsigned char)~CLOG_SPLIT_MASK;
5401 27 : clog_size_rotate_if_due(sh);
5402 : }
5403 :
5404 1671 : if (off < len) {
5405 846 : unsigned char split =
5406 : off > 0
5407 846 : ? clog_split_after(data, off)
5408 827 : : (unsigned char)(sh->async_partial_record & CLOG_SPLIT_MASK);
5409 846 : if (clog_write_error_is_transient(write_err)) {
5410 840 : sh->async_partial_record =
5411 840 : (unsigned char)((sh->async_partial_record & ~CLOG_SPLIT_MASK) |
5412 : split);
5413 840 : sh->retain_err = write_err;
5414 840 : memmove(data, data + off, len - off);
5415 840 : sh->async_buf.len = len - off;
5416 840 : retained = true;
5417 840 : if (split != CLOG_SPLIT_NONE &&
5418 208 : clog_write_error_is_no_room(write_err) &&
5419 208 : clog_rotation_due(sh)) {
5420 2 : clog_repair_split_record(sh, sh->format, poll_timeout_ms);
5421 2 : clog_time_rotate_if_due(sh);
5422 : }
5423 : } else {
5424 6 : char why[48];
5425 6 : snprintf(why, sizeof(why), "write error %d", write_err);
5426 6 : sh->async_partial_record &= (unsigned char)~CLOG_SPLIT_MASK;
5427 6 : clog_note_dropped_batch(sh, data + off, len - off, split, why,
5428 : write_err, poll_timeout_ms);
5429 : }
5430 : }
5431 : }
5432 : }
5433 8 : if (!retained) {
5434 831 : buf_reset(&sh->async_buf);
5435 831 : sh->async_partial_record &= (unsigned char)~CLOG_SPLIT_MASK;
5436 : }
5437 1673 : if (sh->fd >= 0) clog_size_rotate_if_due(sh);
5438 1673 : if (retained && may_retry && sh->fd >= 0 && sh->fd != fd_before) {
5439 2 : may_retry = false;
5440 2 : goto again;
5441 : }
5442 : }
5443 8130 : }
5444 :
5445 : // The writer thread's flush: writer_flush_buffer() plus advancing
5446 : // last_flush_monotonic, even when there was nothing to write, so the thread's
5447 : // next wait is a full interval and an idle logger doesn't spin. Only the writer
5448 : // thread calls it, since only it writes that field. Needs sh->mutex.
5449 8109 : static void writer_flush_now(clog_shared *sh, int poll_timeout_ms) {
5450 8109 : writer_flush_buffer(sh, poll_timeout_ms);
5451 6778 : clock_gettime(CLOCK_MONOTONIC, &sh->last_flush_monotonic);
5452 1323 : }
5453 :
5454 : // Gives up the continuation of a split record at the front of async_buf and
5455 : // writes, in one write, the newline the first half left open and a marker for
5456 : // the bytes dropped, so the file reads as whole lines again. The continuation
5457 : // runs to the newline of the record's last line, through tab-indented lines.
5458 : // Whole records behind it stay for a later flush. Needs sh->mutex, a usable fd
5459 : // and the split bits set.
5460 9 : static void clog_repair_split_record(clog_shared *sh, clog_format fmt,
5461 : int poll_timeout_ms) {
5462 9 : size_t len = sh->async_buf.len;
5463 9 : const char *data = sh->async_buf.data;
5464 9 : size_t dropped = 0;
5465 24 : do {
5466 24 : const char *nl = memchr(data + dropped, '\n', len - dropped);
5467 24 : dropped = nl ? (size_t)(nl - data) + 1 : len;
5468 24 : } while (dropped < len && data[dropped] == '\t');
5469 :
5470 9 : unsigned char split =
5471 9 : (unsigned char)(sh->async_partial_record & CLOG_SPLIT_MASK);
5472 9 : sh->async_buf.len = len - dropped;
5473 9 : if (sh->async_buf.len > 0)
5474 9 : memmove(sh->async_buf.data, sh->async_buf.data + dropped,
5475 : sh->async_buf.len);
5476 : else
5477 0 : buf_reset(&sh->async_buf);
5478 9 : sh->async_partial_record &= (unsigned char)~CLOG_SPLIT_MASK;
5479 :
5480 9 : clog_note_dropped_continuation(sh, fmt, split, dropped, sh->retain_err,
5481 : poll_timeout_ms);
5482 9 : }
5483 :
5484 : // Drops every record async_buf still holds and writes a marker naming them, for
5485 : // the close and exit paths where no later flush will retry them. The caller
5486 : // already settled any split record. Needs sh->mutex.
5487 281 : static __attribute__((noinline, cold)) void clog_drop_undelivered(
5488 : clog_shared *sh, const char *why, int poll_timeout_ms) {
5489 281 : if (sh->async_buf.len == 0) return;
5490 8 : sh->async_partial_record &= (unsigned char)~CLOG_SPLIT_MASK;
5491 8 : if (sh->fd >= 0)
5492 8 : clog_note_dropped_batch(sh, sh->async_buf.data, sh->async_buf.len,
5493 : CLOG_SPLIT_NONE, why, 0, poll_timeout_ms);
5494 8 : buf_reset(&sh->async_buf);
5495 : }
5496 :
5497 : // Repairs a record still split after a flush, and then pays an owed repair, so
5498 : // a record written straight to the fd next lands on a line of its own and not
5499 : // between the halves of another. Used by every path that writes past the batch;
5500 : // it gives the continuation no further wait. Needs sh->mutex.
5501 6495 : static void clog_settle_after_flush(clog_shared *sh, clog_format fmt,
5502 : int poll_timeout_ms) {
5503 6495 : if (sh->async_partial_record & CLOG_SPLIT_MASK)
5504 7 : clog_repair_split_record(sh, fmt, poll_timeout_ms);
5505 6495 : if (sh->async_partial_record & CLOG_OWED_REPAIR)
5506 58 : (void)clog_pay_owed(sh, fmt, poll_timeout_ms);
5507 6495 : }
5508 :
5509 : // Flushes async_buf (bounded by poll_timeout_ms) and settles what's left, for
5510 : // the two write paths that don't belong to the writer thread. Out of line so
5511 : // the ordinary log path keeps its shape. Needs sh->mutex.
5512 22 : static __attribute__((noinline)) void clog_flush_and_settle(
5513 : clog_shared *sh, clog_format fmt, int poll_timeout_ms) {
5514 22 : writer_flush_buffer(sh, poll_timeout_ms);
5515 22 : clog_settle_after_flush(sh, fmt, poll_timeout_ms);
5516 22 : }
5517 :
5518 : // Frees a job envelope and everything it owns: The message spill, the field
5519 : // snapshot and the backtrace (with free(), since backtrace_symbols() used
5520 : // malloc). Used by the writer thread after each job and by clog_write_async()
5521 : // when the send fails.
5522 26235 : static void clog_async_job_release(clog_shared *sh, clog_async_msg *envelope) {
5523 26235 : clog_async_job *job = &envelope->u.job;
5524 26235 : if (job->bt_syms) free(job->bt_syms);
5525 26235 : ccol_growbuf_destroy(&job->field_pool);
5526 26234 : ccol__mem_free(sh->m_procs, job->fields);
5527 26235 : ccol__mem_free(sh->m_procs, job->msg_heap);
5528 26235 : ccol__mem_free(sh->m_procs, envelope);
5529 26235 : }
5530 :
5531 : #ifdef RUNNING_UNIT_TESTS
5532 :
5533 : // How long the writer thread holds each job under the mutex, for tests of a
5534 : // slow output.
5535 : static _Atomic unsigned int clog_test_writer_job_delay_us = 0;
5536 :
5537 : // Sets how long the writer thread holds each job under the mutex, so a test can
5538 : // make a slow output.
5539 6 : void clog__test_set_writer_job_delay_us(unsigned int delay_us) {
5540 6 : atomic_store(&clog_test_writer_job_delay_us, delay_us);
5541 6 : }
5542 :
5543 : // How long the writer thread holds a job before taking the mutex, so a test can
5544 : // put a record between taking a job and locking.
5545 : static _Atomic unsigned int clog_test_writer_unlocked_job_delay_us = 0;
5546 :
5547 : // Sets how long the writer thread holds each job after taking it and before it
5548 : // takes the mutex, so a test can log a record in that window.
5549 2 : void clog__test_set_writer_unlocked_job_delay_us(unsigned int delay_us) {
5550 2 : atomic_store(&clog_test_writer_unlocked_job_delay_us, delay_us);
5551 2 : }
5552 :
5553 : // Holds the writer thread for delay_us, for the job delay hooks. Up to 50 ms it
5554 : // waits on the clock, since a sleep on a busy machine can end far too late for
5555 : // a test bound; longer holds just sleep.
5556 4436 : static void clog_test_writer_job_delay(unsigned int delay_us) {
5557 4436 : if (delay_us > 50000U) {
5558 2 : usleep(delay_us);
5559 1 : return;
5560 : }
5561 4434 : struct timespec start, now;
5562 4434 : clock_gettime(CLOCK_MONOTONIC, &start);
5563 1840261 : do {
5564 1840261 : sched_yield();
5565 1840260 : clock_gettime(CLOCK_MONOTONIC, &now);
5566 1840260 : } while ((long long)(now.tv_sec - start.tv_sec) * 1000000LL +
5567 1840260 : (now.tv_nsec - start.tv_nsec) / 1000L <
5568 1840260 : (long long)delay_us);
5569 : }
5570 : #endif
5571 :
5572 : // Waits, polling, until no CLOG_FATAL call waits for sh's mutex, so the writer
5573 : // thread doesn't keep winning the mutex from a fatal call. The fatal call's own
5574 : // bounded wait lowers the count.
5575 1 : static __attribute__((noinline, cold)) void clog_writer_yield_to_fatal(
5576 : clog_shared *sh) {
5577 2 : while (atomic_load(&sh->fatal_waiters) != 0) {
5578 1 : struct timespec pause = {.tv_sec = 0, .tv_nsec = 200000L};
5579 1 : nanosleep(&pause, NULL);
5580 : }
5581 1 : }
5582 :
5583 : // Locks sh->mutex for a piece of writer thread work, after stepping aside for
5584 : // any waiting CLOG_FATAL call (a mutex goes to whoever asks again first). It
5585 : // also syncs the thread's signal mask with the current policy.
5586 26798 : static inline void clog_writer_lock(clog_shared *sh) {
5587 26798 : clog_thread_sync_signal_mask();
5588 : #ifdef RUNNING_UNIT_TESTS
5589 : {
5590 26798 : sigset_t cur;
5591 26798 : sigemptyset(&cur);
5592 26798 : if (ccol__thread_sigmask(SIG_BLOCK, NULL, &cur) == 0)
5593 26808 : atomic_store(&sh->test_writer_blocked_signals,
5594 : 4u | (sigismember(&cur, SIGPIPE) == 1 ? 1u : 0u) |
5595 : (sigismember(&cur, SIGXFSZ) == 1 ? 2u : 0u));
5596 : }
5597 : #endif
5598 26798 : if (__builtin_expect(
5599 26798 : atomic_load_explicit(&sh->fatal_waiters, memory_order_relaxed) != 0,
5600 : 0))
5601 1 : clog_writer_yield_to_fatal(sh);
5602 26798 : ccol__mutex_lock(sh->mutex);
5603 26798 : }
5604 :
5605 : // Tells whether the writer thread has nothing to deliver (empty batch, no split
5606 : // record, no owed repair), in which case it waits for a message with no time
5607 : // limit. Needs sh->mutex.
5608 26514 : static inline bool clog_writer_has_no_work(const clog_shared *sh) {
5609 6995 : return sh->async_buf.len == 0 && sh->async_partial_record == 0;
5610 : }
5611 :
5612 : // The async writer thread of target arg. It takes messages from the queue and
5613 : // builds each job into async_buf, flushing when the batch reaches
5614 : // flush_buffer_size, when flush_interval_us runs out (checked before every
5615 : // message, so sustained load can't starve it) and on flush or wake requests.
5616 : // With no work it waits without a limit. Syslog and message sockets get one
5617 : // write per record. A record that doesn't fit behind kept bytes goes through a
5618 : // scratch buffer or counts as a loss; a fallback caused by an almost full batch
5619 : // is rolled back and retried after a flush. A failing receive backs off with a
5620 : // sleep. On the shutdown sentinel it settles and drops what's left and exits.
5621 : // The interval arithmetic stays unsigned so UINT64_MAX means no timed flush.
5622 308 : static void *clog_writer_thread_main(void *arg) {
5623 308 : clog_shared *sh = (clog_shared *)arg;
5624 308 : clog_thread_serves = sh;
5625 308 : clog_thread_signal_init();
5626 308 : bool interval_flushed = false;
5627 308 : bool no_work = true;
5628 :
5629 26822 : for (;;) {
5630 26822 : struct timespec now;
5631 26822 : clock_gettime(CLOCK_MONOTONIC, &now);
5632 26822 : long long elapsed_us =
5633 26822 : (long long)(now.tv_sec - sh->last_flush_monotonic.tv_sec) * 1000000LL +
5634 26822 : (now.tv_nsec - sh->last_flush_monotonic.tv_nsec) / 1000L;
5635 26822 : uint64_t interval_us = sh->async_cfg.flush_interval_us;
5636 53644 : uint64_t remaining_us = elapsed_us <= 0 ? interval_us
5637 26822 : : (uint64_t)elapsed_us >= interval_us
5638 : ? 0
5639 25445 : : interval_us - (uint64_t)elapsed_us;
5640 :
5641 26822 : if (remaining_us == 0 && !interval_flushed) {
5642 : #ifdef RUNNING_UNIT_TESTS
5643 21 : atomic_fetch_add(&sh->test_writer_interval_flushes, 1);
5644 : #endif
5645 21 : clog_writer_lock(sh);
5646 21 : writer_flush_now(sh, CLOG_WRITE_WAIT_FOREVER);
5647 21 : no_work = clog_writer_has_no_work(sh);
5648 21 : ccol__mutex_unlock(sh->mutex);
5649 21 : interval_flushed = true;
5650 21 : continue;
5651 : }
5652 26801 : interval_flushed = false;
5653 :
5654 26801 : if (no_work) remaining_us = UINT64_MAX;
5655 26801 : cmessage m = {0};
5656 53578 : ccol_retval rv = sh->is_bounded_queue
5657 9881 : ? ccircq_timed_recv(sh->q.circq, &m, remaining_us)
5658 26801 : : cdynmq_timed_recv(sh->q.dynmq, &m, remaining_us);
5659 :
5660 26777 : if (rv == ccol_timed_out || rv == ccol_container_empty) {
5661 : #ifdef RUNNING_UNIT_TESTS
5662 4 : atomic_fetch_add(&sh->test_writer_timeout_wakeups, 1);
5663 4 : atomic_fetch_add(&sh->test_writer_interval_flushes, 1);
5664 : #endif
5665 4 : clog_writer_lock(sh);
5666 4 : writer_flush_now(sh, CLOG_WRITE_WAIT_FOREVER);
5667 4 : no_work = clog_writer_has_no_work(sh);
5668 4 : ccol__mutex_unlock(sh->mutex);
5669 4 : continue;
5670 : }
5671 26773 : if (rv != ccol_success) {
5672 0 : usleep(1000);
5673 0 : continue;
5674 : }
5675 :
5676 26773 : if (m.data == NULL && m.size == 0) {
5677 274 : clog_writer_lock(sh);
5678 274 : writer_flush_now(sh, CLOG_WRITE_WAIT_FOREVER);
5679 274 : clog_settle_after_flush(sh, sh->format, CLOG_WRITE_WAIT_FOREVER);
5680 274 : clog_drop_undelivered(sh, "the logger closed", CLOG_WRITE_WAIT_FOREVER);
5681 274 : ccol__mutex_unlock(sh->mutex);
5682 274 : return NULL;
5683 : }
5684 :
5685 26499 : clog_async_msg *envelope = (clog_async_msg *)m.data;
5686 :
5687 26499 : if (envelope->kind == CLOG_ASYNC_MSG_WAKE) {
5688 8 : clog_writer_lock(sh);
5689 8 : writer_flush_now(sh, CLOG_WRITE_WAIT_FOREVER);
5690 8 : no_work = clog_writer_has_no_work(sh);
5691 8 : ccol__mutex_unlock(sh->mutex);
5692 8 : continue;
5693 : }
5694 :
5695 26491 : if (envelope->kind == CLOG_ASYNC_MSG_FLUSH) {
5696 287 : clog_async_ctrl *ctrl = envelope->u.ctrl;
5697 287 : clog_writer_lock(sh);
5698 287 : writer_flush_now(sh, CLOG_WRITE_WAIT_FOREVER);
5699 279 : no_work = clog_writer_has_no_work(sh);
5700 279 : ccol__mutex_unlock(sh->mutex);
5701 279 : ccol__mutex_lock(ctrl->mutex);
5702 279 : ctrl->done = true;
5703 279 : ccol__cond_var_broadcast(ctrl->cv);
5704 279 : ccol__mutex_unlock(ctrl->mutex);
5705 279 : continue;
5706 : }
5707 :
5708 26204 : clog_async_job *job = &envelope->u.job;
5709 : #ifdef RUNNING_UNIT_TESTS
5710 : {
5711 26204 : unsigned int delay = atomic_load(&clog_test_writer_unlocked_job_delay_us);
5712 26204 : if (delay) usleep(delay);
5713 : }
5714 : #endif
5715 26204 : clog_writer_lock(sh);
5716 : #ifdef RUNNING_UNIT_TESTS
5717 : {
5718 26204 : unsigned int delay = atomic_load(&clog_test_writer_job_delay_us);
5719 26204 : if (delay) clog_test_writer_job_delay(delay);
5720 : }
5721 : #endif
5722 26202 : if (sh->fd >= 0) {
5723 26202 : clog_format fmt = sh->format;
5724 26202 : clog_field_source fsrc;
5725 26202 : fsrc.is_live = false;
5726 26202 : fsrc.u.snap.views = job->fields;
5727 26202 : fsrc.u.snap.count = job->field_count;
5728 26202 : fsrc.u.snap.pool = job->field_pool.buf;
5729 26202 : fsrc.u.snap.failed = job->fields_snapshot_failed;
5730 :
5731 32351 : if (fmt == CLOG_FMT_SYSLOG || sh->sink_per_record) {
5732 6149 : writer_flush_now(sh, CLOG_WRITE_WAIT_FOREVER);
5733 6149 : clog_settle_after_flush(sh, fmt, CLOG_WRITE_WAIT_FOREVER);
5734 :
5735 6149 : clog_buf scratch;
5736 6149 : clog_buf *rec_buf = &sh->async_buf;
5737 6149 : if (sh->async_buf.len > 0)
5738 5 : rec_buf = buf_init(&scratch, sh->m_procs) == 0 ? &scratch : NULL;
5739 :
5740 1 : if (!rec_buf) {
5741 1 : clog_write_unrepresentable_record(sh, fmt, job->level,
5742 1 : job->with_backtrace);
5743 : } else {
5744 12296 : bool built = clog_build_record(
5745 6148 : rec_buf, sh, fmt, job->level, &job->ts, job->proc_val, job->file,
5746 6148 : job->line, job->func, job->msg, &fsrc, job->with_backtrace,
5747 6148 : job->bt_syms, job->bt_depth, NULL);
5748 6148 : if (built) {
5749 6148 : clog_write_record(sh, fmt, rec_buf->data, rec_buf->len);
5750 : } else {
5751 0 : clog_write_unrepresentable_record(sh, fmt, job->level,
5752 0 : job->with_backtrace);
5753 : }
5754 6148 : buf_reset(rec_buf);
5755 6148 : if (job->with_backtrace && fmt == CLOG_FMT_SYSLOG)
5756 3 : emit_backtrace_syslog_lines(rec_buf, sh, job->level, &job->ts,
5757 3 : job->bt_syms, job->bt_depth);
5758 6148 : if (rec_buf != &sh->async_buf) buf_free(rec_buf);
5759 : }
5760 : } else {
5761 20053 : size_t record_start = sh->async_buf.len;
5762 20053 : bool batch_had_prior_content = record_start > 0;
5763 20053 : bool used_fallback = false;
5764 40106 : bool built = clog_build_record(
5765 20053 : &sh->async_buf, sh, fmt, job->level, &job->ts, job->proc_val,
5766 : job->file, job->line, job->func, job->msg, &fsrc,
5767 20053 : job->with_backtrace, job->bt_syms, job->bt_depth, &used_fallback);
5768 20053 : if (!built || (used_fallback && batch_had_prior_content)) {
5769 43 : sh->async_buf.len = record_start;
5770 43 : writer_flush_now(sh, CLOG_WRITE_WAIT_FOREVER);
5771 43 : clog_settle_after_flush(sh, fmt, CLOG_WRITE_WAIT_FOREVER);
5772 43 : size_t retry_start = sh->async_buf.len;
5773 43 : bool retry_fallback = false;
5774 86 : if (!clog_build_record(&sh->async_buf, sh, fmt, job->level, &job->ts,
5775 : job->proc_val, job->file, job->line, job->func,
5776 43 : job->msg, &fsrc, job->with_backtrace,
5777 43 : job->bt_syms, job->bt_depth,
5778 : retry_start > 0 ? &retry_fallback : NULL)) {
5779 0 : clog_write_unrepresentable_record(sh, fmt, job->level,
5780 0 : job->with_backtrace);
5781 0 : clog_size_rotate_if_due(sh);
5782 43 : } else if (retry_fallback && !sh->async_buf.oom) {
5783 42 : sh->async_buf.len = retry_start;
5784 42 : size_t mlen = strlen(job->msg);
5785 42 : char detail[112];
5786 42 : snprintf(detail, sizeof(detail),
5787 : "a record did not fit behind the undelivered batch "
5788 : "(%zu byte message)",
5789 : mlen);
5790 42 : clog_report_loss(sh, fmt, false, 1, mlen, 0, detail,
5791 : CLOG_WRITE_WAIT_FOREVER);
5792 : }
5793 : }
5794 20053 : if (sh->async_buf.len >= sh->async_cfg.flush_buffer_size)
5795 1323 : writer_flush_now(sh, CLOG_WRITE_WAIT_FOREVER);
5796 : }
5797 : }
5798 26202 : no_work = clog_writer_has_no_work(sh);
5799 26202 : ccol__mutex_unlock(sh->mutex);
5800 :
5801 26202 : clog_async_job_release(sh, envelope);
5802 : }
5803 : }
5804 :
5805 : // Turns async logging on for sh: Resolves the config defaults, creates the
5806 : // queue, sets up async_buf (its limit raised to flush_buffer_size) and starts
5807 : // the writer thread, undoing everything if a step fails. async_enabled is set
5808 : // only at the end. Each constructor calls it last, so the writer thread never
5809 : // sees a half-built sh. Returns false on failure.
5810 318 : static bool shared_async_init(clog_shared *sh,
5811 : const clog_async_cfg *async_cfg) {
5812 318 : sh->async_cfg.queue_size = async_cfg->queue_size;
5813 636 : sh->async_cfg.flush_buffer_size = async_cfg->flush_buffer_size
5814 : ? async_cfg->flush_buffer_size
5815 318 : : CLOG_DEFAULT_ASYNC_FLUSH_BUFFER_SIZE;
5816 636 : sh->async_cfg.flush_interval_us = async_cfg->flush_interval_us
5817 : ? async_cfg->flush_interval_us
5818 318 : : CLOG_DEFAULT_ASYNC_FLUSH_INTERVAL_US;
5819 318 : sh->is_bounded_queue = (async_cfg->queue_size > 0);
5820 :
5821 318 : char *err = NULL;
5822 318 : if (sh->is_bounded_queue) {
5823 90 : sh->q.circq = ccircq_create_mp(async_cfg->queue_size, sh->m_procs, &err);
5824 90 : if (!sh->q.circq) return false;
5825 : } else {
5826 228 : sh->q.dynmq = cdynmq_create_mp(sh->m_procs, &err);
5827 228 : if (!sh->q.dynmq) return false;
5828 : }
5829 :
5830 311 : if (buf_init(&sh->async_buf, sh->m_procs) != 0) {
5831 3 : if (sh->is_bounded_queue)
5832 1 : ccircq_destroy(sh->q.circq);
5833 : else
5834 2 : cdynmq_destroy(sh->q.dynmq);
5835 3 : return false;
5836 : }
5837 308 : buf_raise_cap_limit(&sh->async_buf, sh->async_cfg.flush_buffer_size);
5838 :
5839 308 : clock_gettime(CLOCK_MONOTONIC, &sh->last_flush_monotonic);
5840 :
5841 308 : if (ccol__thread_create(sh->writer_thread, clog_writer_thread_main, sh) !=
5842 : 0) {
5843 0 : buf_free(&sh->async_buf);
5844 0 : if (sh->is_bounded_queue)
5845 0 : ccircq_destroy(sh->q.circq);
5846 : else
5847 0 : cdynmq_destroy(sh->q.dynmq);
5848 0 : return false;
5849 : }
5850 :
5851 308 : sh->async_enabled = true;
5852 308 : clog_exit_drain_arm();
5853 308 : return true;
5854 : }
5855 :
5856 : // Sends the writer thread its shutdown sentinel, retrying with a backoff up to
5857 : // 100 ms until the queue takes it. An unbounded queue can fail a send for lack
5858 : // of memory, and the join that follows would then wait for ever; giving up
5859 : // isn't possible either, because the caller frees what the thread still uses.
5860 274 : static void clog_send_shutdown_sentinel_blocking(clog_shared *sh) {
5861 274 : unsigned int delay_us = 1000;
5862 292 : for (;;) {
5863 283 : cmessage sentinel = {.data = NULL, .size = 0};
5864 75 : ccol_retval rv = sh->is_bounded_queue ? ccircq_send(sh->q.circq, &sentinel)
5865 283 : : cdynmq_send(sh->q.dynmq, &sentinel);
5866 283 : if (rv == ccol_success) return;
5867 9 : usleep(delay_us);
5868 9 : if (delay_us < 100000) delay_us *= 2;
5869 : }
5870 : }
5871 :
5872 : // Stops the writer thread (after re-enabling sends an exit drain may have
5873 : // turned off) and frees the queue and async_buf. Used by the last clog_close()
5874 : // and by a constructor rollback after shared_async_init() succeeded.
5875 274 : static void shared_async_teardown(clog_shared *sh) {
5876 274 : if (sh->is_bounded_queue)
5877 75 : (void)ccircq_enable_sending(sh->q.circq);
5878 : else
5879 199 : (void)cdynmq_enable_sending(sh->q.dynmq);
5880 274 : clog_send_shutdown_sentinel_blocking(sh);
5881 274 : ccol__thread_join(sh->writer_thread);
5882 274 : if (sh->is_bounded_queue)
5883 75 : ccircq_destroy(sh->q.circq);
5884 : else
5885 199 : cdynmq_destroy(sh->q.dynmq);
5886 274 : buf_free(&sh->async_buf);
5887 274 : }
5888 :
5889 : // Validators of the enum setters and the open calls: Each accepts only the
5890 : // values its enum names. They compare through int, since an enum can be
5891 : // unsigned and a negative value would become a large one.
5892 : static bool clog_level_is_valid(clog_level level) {
5893 4044 : int v = (int)level;
5894 : return v >= (int)CLOG_TRACE && v <= (int)CLOG_OFF;
5895 : }
5896 :
5897 : static bool clog_format_is_valid(clog_format fmt) {
5898 178 : int v = (int)fmt;
5899 : return v == (int)CLOG_FMT_LOGFMT || v == (int)CLOG_FMT_JSON ||
5900 : v == (int)CLOG_FMT_SYSLOG;
5901 : }
5902 :
5903 7 : static bool clog_facility_is_valid(clog_syslog_facility facility) {
5904 7 : int v = (int)facility;
5905 7 : return (v >= (int)CLOG_SYSLOG_KERN && v <= (int)CLOG_SYSLOG_FTP) ||
5906 7 : (v >= (int)CLOG_SYSLOG_LOCAL0 && v <= (int)CLOG_SYSLOG_LOCAL7);
5907 : }
5908 :
5909 : // Creates a logger that writes to the caller's fd, the public entry for pipes,
5910 : // sockets and terminals. The caller keeps owning fd. async_cfg turns on async
5911 : // logging and m_procs picks the allocator. Gives the handle, or CLOG_NULL when
5912 : // an argument is invalid or a step fails; every failure rolls back what was
5913 : // built.
5914 936 : clog clog_create_from_fd_mp(int fd, clog_level min_level,
5915 : const clog_async_cfg *async_cfg,
5916 : ccol_memmgmt_procs *mprocs) {
5917 936 : if (fd < 0 || !clog_level_is_valid(min_level)) return CLOG_NULL;
5918 934 : int fd_flags = fcntl(fd, F_GETFL);
5919 934 : if (fd_flags == -1) return CLOG_NULL;
5920 933 : int accmode = fd_flags & O_ACCMODE;
5921 933 : if (accmode != O_WRONLY && accmode != O_RDWR) return CLOG_NULL;
5922 932 : if (!ccol__verify_memmgmt_procs(mprocs, (char **)NULL)) return CLOG_NULL;
5923 931 : struct clogger *lg = alloc(fd, false, NULL, -1, min_level, mprocs);
5924 931 : if (!lg) return CLOG_NULL;
5925 :
5926 921 : if (async_cfg && !shared_async_init(lg->shared, async_cfg)) {
5927 7 : clog_shared *sh = lg->shared;
5928 7 : shared_close_owned_fd(sh);
5929 7 : ccol__mutex_destroy(sh->mutex);
5930 7 : logger_free(lg);
5931 7 : shared_free_partial(sh);
5932 7 : return CLOG_NULL;
5933 : }
5934 :
5935 914 : clog h = clog_handle_acquire(lg);
5936 914 : if (h == CLOG_NULL) {
5937 18 : clog_shared *sh = lg->shared;
5938 18 : if (sh->async_enabled) shared_async_teardown(sh);
5939 18 : shared_compressor_teardown(sh);
5940 18 : shared_close_owned_fd(sh);
5941 18 : ccol__mutex_destroy(sh->mutex);
5942 18 : logger_free(lg);
5943 18 : shared_free_partial(sh);
5944 18 : return CLOG_NULL;
5945 : }
5946 : return h;
5947 : }
5948 :
5949 : // Sets sh->last_rotation for a time-rotating logger that opens a non-empty
5950 : // file, so the interval counts from when the file began and a process that
5951 : // restarts often still rotates. It uses the stamp of the newest generation on
5952 : // disk, else the file's birth time (statx on Linux, struct stat on macOS and
5953 : // FreeBSD), else its mtime; a seed in the future (clock stepped back) becomes
5954 : // the open time. The newest name found is also recorded for rotate(). It writes
5955 : // no WARN, since the open may still join another target.
5956 3 : static void clog_seed_last_rotation(clog_shared *sh, int fd,
5957 : const struct stat *st) {
5958 3 : time_t seed = st->st_mtime;
5959 3 : bool seeded = false;
5960 3 : if (!sh->rot_name_known)
5961 3 : sh->rot_name_known = rotated_newest_on_disk(sh, false, sh->rot_last_stamp,
5962 : &sh->rot_last_seq);
5963 3 : time_t stamp;
5964 3 : if (sh->rot_name_known && clog_stamp_to_time(sh->rot_last_stamp, &stamp)) {
5965 1 : seed = stamp;
5966 1 : seeded = true;
5967 : }
5968 : #if defined(__linux__) && defined(STATX_BTIME)
5969 3 : if (!seeded) {
5970 2 : struct statx stx;
5971 2 : if (statx(fd, "", AT_EMPTY_PATH, STATX_BTIME, &stx) == 0 &&
5972 2 : (stx.stx_mask & STATX_BTIME))
5973 2 : seed = (time_t)stx.stx_btime.tv_sec;
5974 : }
5975 : #elif defined(__APPLE__)
5976 : (void)fd;
5977 : if (!seeded && st->st_birthtimespec.tv_sec > 0)
5978 : seed = st->st_birthtimespec.tv_sec;
5979 : #elif defined(__FreeBSD__)
5980 : (void)fd;
5981 : if (!seeded && st->st_birthtim.tv_sec > 0) seed = st->st_birthtim.tv_sec;
5982 : #else
5983 : (void)fd;
5984 : (void)seeded;
5985 : #endif
5986 3 : if (seed < sh->last_rotation) sh->last_rotation = seed;
5987 3 : }
5988 :
5989 : static clog clog_file_register_or_attach(clog h, clog_shared *sh,
5990 : clog_level min_level);
5991 :
5992 : // Creates a logger that appends to the file at path, the public entry for log
5993 : // files. With rotation on it opens the directory first and the file relative to
5994 : // it, so a later chdir() doesn't move the log, and it removes stale private
5995 : // names, recovers unfinished compressions and seeds the byte count and the time
5996 : // interval from the file. Rotation fields left at 0 get their defaults
5997 : // (max_rotated_files too, so a zeroed config doesn't keep files for ever).
5998 : // Async setup comes last. Finally it joins or refuses another target of the
5999 : // same file (see clog_file_register_or_attach()). Gives the handle or
6000 : // CLOG_NULL.
6001 600 : clog clog_create_from_file_path_mp(const char *path, clog_level min_level,
6002 : const clog_rotation_cfg *cfg,
6003 : const clog_async_cfg *async_cfg,
6004 : ccol_memmgmt_procs *mprocs) {
6005 600 : if (!path || !clog_level_is_valid(min_level)) return CLOG_NULL;
6006 599 : if (!ccol__verify_memmgmt_procs(mprocs, (char **)NULL)) return CLOG_NULL;
6007 :
6008 599 : int dir_fd = -1;
6009 599 : int fd;
6010 599 : if (cfg && (cfg->size_rotation_enabled || cfg->time_rotation_enabled)) {
6011 181 : dir_fd = clog_open_log_dir(path);
6012 181 : if (dir_fd < 0) return CLOG_NULL;
6013 358 : fd = openat(dir_fd, path_base(path),
6014 : O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
6015 : } else {
6016 418 : fd = open(path, O_WRONLY | O_CREAT | O_APPEND | O_CLOEXEC, 0644);
6017 : }
6018 598 : if (fd < 0) {
6019 1 : if (dir_fd >= 0) close(dir_fd);
6020 1 : return CLOG_NULL;
6021 : }
6022 :
6023 597 : struct clogger *lg = alloc(fd, true, path, dir_fd, min_level, mprocs);
6024 597 : if (!lg) {
6025 12 : close(fd);
6026 12 : if (dir_fd >= 0) close(dir_fd);
6027 12 : return CLOG_NULL;
6028 : }
6029 :
6030 : {
6031 585 : int id_fd = dir_fd >= 0 ? dir_fd : clog_open_log_dir(path);
6032 411 : struct stat dir_st;
6033 585 : if (id_fd >= 0 && fstat(id_fd, &dir_st) == 0) {
6034 585 : lg->shared->file_id_known = true;
6035 585 : lg->shared->file_dir_dev = dir_st.st_dev;
6036 585 : lg->shared->file_dir_ino = dir_st.st_ino;
6037 : }
6038 585 : if (id_fd >= 0 && id_fd != dir_fd) close(id_fd);
6039 : }
6040 :
6041 585 : if (cfg) {
6042 348 : lg->shared->rotation_enabled =
6043 174 : cfg->size_rotation_enabled || cfg->time_rotation_enabled;
6044 174 : lg->shared->rotation = *cfg;
6045 :
6046 174 : if (cfg->size_rotation_enabled && cfg->max_file_size <= 0)
6047 1 : lg->shared->rotation.max_file_size = CLOG_DEFAULT_MAX_FILE_SIZE;
6048 :
6049 174 : if (cfg->time_rotation_enabled && cfg->rotation_interval_us == 0)
6050 2 : lg->shared->rotation.rotation_interval_us =
6051 : CLOG_DEFAULT_ROTATION_INTERVAL_US;
6052 :
6053 174 : if (cfg->max_rotated_files <= 0)
6054 9 : lg->shared->rotation.max_rotated_files = CLOG_DEFAULT_MAX_ROTATED_FILES;
6055 :
6056 174 : struct stat st;
6057 174 : bool have_size = false;
6058 174 : if (fstat(fd, &st) == 0) {
6059 174 : lg->shared->bytes_written = st.st_size;
6060 174 : have_size = true;
6061 174 : if (st.st_size > 0 && cfg->time_rotation_enabled)
6062 3 : clog_seed_last_rotation(lg->shared, fd, &st);
6063 : } else {
6064 0 : off_t end = lseek(fd, 0, SEEK_END);
6065 0 : if (end != (off_t)-1) {
6066 0 : lg->shared->bytes_written = end;
6067 0 : have_size = true;
6068 : }
6069 : }
6070 3 : if (!have_size && cfg->size_rotation_enabled) {
6071 0 : clog_shared *sh = lg->shared;
6072 0 : shared_close_owned_fd(sh);
6073 0 : ccol__mutex_destroy(sh->mutex);
6074 0 : logger_free(lg);
6075 0 : shared_free_partial(sh);
6076 0 : return CLOG_NULL;
6077 : }
6078 : }
6079 :
6080 585 : if (async_cfg && !shared_async_init(lg->shared, async_cfg)) {
6081 3 : clog_shared *sh = lg->shared;
6082 3 : shared_close_owned_fd(sh);
6083 3 : ccol__mutex_destroy(sh->mutex);
6084 3 : logger_free(lg);
6085 3 : shared_free_partial(sh);
6086 3 : return CLOG_NULL;
6087 : }
6088 :
6089 582 : clog h = clog_handle_acquire(lg);
6090 582 : if (h == CLOG_NULL) {
6091 9 : clog_shared *sh = lg->shared;
6092 9 : if (sh->async_enabled) shared_async_teardown(sh);
6093 9 : shared_compressor_teardown(sh);
6094 9 : shared_close_owned_fd(sh);
6095 9 : ccol__mutex_destroy(sh->mutex);
6096 9 : logger_free(lg);
6097 9 : shared_free_partial(sh);
6098 9 : return CLOG_NULL;
6099 : }
6100 573 : return clog_file_register_or_attach(h, lg->shared, min_level);
6101 : }
6102 :
6103 : // Tears down a target whose last handle is gone, for clog_close() and for an
6104 : // open that attached and then failed. It leaves live_shareds first (before
6105 : // touching sh->mutex, for the fork walk), stops the writer thread without
6106 : // holding the mutex (the thread needs it to drain) and before the fd closes,
6107 : // then the compressor, pays an owed repair with a bounded write, closes the
6108 : // descriptors, leaves file_shareds and frees sh. The caller holds no lock.
6109 1420 : static void clog_shared_finish_last(clog_shared *sh) {
6110 1420 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6111 1420 : clog_shareds_remove(clog_slot_table.live_shareds, sh);
6112 1420 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6113 :
6114 1420 : if (sh->async_enabled) shared_async_teardown(sh);
6115 :
6116 1420 : shared_compressor_teardown(sh);
6117 :
6118 1420 : ccol__mutex_lock(sh->mutex);
6119 1420 : if (sh->async_partial_record & CLOG_OWED_REPAIR)
6120 0 : (void)clog_pay_owed(sh, sh->format, CLOG_SPLIT_RECORD_DRAIN_WAIT_MS);
6121 1420 : ccol__mutex_unlock(sh->mutex);
6122 :
6123 1420 : shared_close_owned_fd(sh);
6124 1420 : if (sh->file_id_known) {
6125 554 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6126 554 : clog_shareds_remove(clog_slot_table.file_shareds, sh);
6127 554 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6128 : }
6129 1420 : ccol__mutex_destroy(sh->mutex);
6130 1420 : shared_free_partial(sh);
6131 1420 : }
6132 :
6133 : // Tells whether target b may join target a on the same file: The same rotation,
6134 : // async configuration and allocator once defaults are applied. Used by
6135 : // clog_file_register_or_attach().
6136 81 : static bool clog_file_targets_compatible(const clog_shared *a,
6137 : const clog_shared *b) {
6138 81 : if (a->rotation_enabled != b->rotation_enabled) return false;
6139 80 : if (a->rotation_enabled) {
6140 80 : const clog_rotation_cfg *x = &a->rotation, *y = &b->rotation;
6141 80 : if (x->size_rotation_enabled != y->size_rotation_enabled ||
6142 80 : x->time_rotation_enabled != y->time_rotation_enabled ||
6143 80 : x->max_rotated_files != y->max_rotated_files ||
6144 : x->compress_rotated != y->compress_rotated)
6145 : return false;
6146 79 : if (x->size_rotation_enabled && x->max_file_size != y->max_file_size)
6147 : return false;
6148 79 : if (x->time_rotation_enabled &&
6149 3 : x->rotation_interval_us != y->rotation_interval_us)
6150 : return false;
6151 : }
6152 78 : if (a->async_enabled != b->async_enabled) return false;
6153 77 : if (a->async_enabled &&
6154 2 : (a->async_cfg.queue_size != b->async_cfg.queue_size ||
6155 2 : a->async_cfg.flush_buffer_size != b->async_cfg.flush_buffer_size ||
6156 2 : a->async_cfg.flush_interval_us != b->async_cfg.flush_interval_us))
6157 : return false;
6158 78 : if (!a->m_procs || !b->m_procs) return !a->m_procs && !b->m_procs;
6159 140 : return a->m_procs->malloc == b->m_procs->malloc &&
6160 70 : a->m_procs->free == b->m_procs->free &&
6161 209 : a->m_procs->calloc == b->m_procs->calloc &&
6162 69 : a->m_procs->realloc == b->m_procs->realloc;
6163 : }
6164 :
6165 : // Drops one reference to the live target sh and tears it down when it was the
6166 : // last one, for the rollback of an attaching open. The teardown counts as a
6167 : // close in flight, since it uses the table's vectors.
6168 6 : static void clog_shared_unref(clog_shared *sh) {
6169 6 : ccol__mutex_lock(sh->mutex);
6170 6 : int remaining = --sh->ref_count;
6171 6 : ccol__mutex_unlock(sh->mutex);
6172 6 : if (remaining != 0) return;
6173 0 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6174 0 : clog_slot_table.closes_in_flight++;
6175 0 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6176 0 : clog_shared_finish_last(sh);
6177 0 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6178 0 : clog_slot_table.closes_in_flight--;
6179 0 : clog_release_slot_table_if_deferred_locked();
6180 0 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6181 : }
6182 :
6183 : // The last step of clog_create_from_file_path_mp(), which keeps one target per
6184 : // file whenever either open rotates, since two targets renaming and pruning the
6185 : // same file lose records. h is the new logger on its new target sh. With no
6186 : // other target on the same directory entry, sh is registered in file_shareds
6187 : // (after its compression recovery, under the table lock, so no other handle can
6188 : // rotate meanwhile) and h is returned. Otherwise, if either rotates, the new
6189 : // target is closed and the open joins the existing one with a new logger at
6190 : // min_level when the configurations match, or fails with CLOG_NULL. Two targets
6191 : // that don't rotate stay independent. A target whose last close is still
6192 : // running is waited for. Takes the table's write lock.
6193 573 : static clog clog_file_register_or_attach(clog h, clog_shared *sh,
6194 : clog_level min_level) {
6195 573 : if (!sh->file_id_known) return h;
6196 : unsigned int delay_us = 1000;
6197 577 : for (;;) {
6198 575 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6199 575 : clog_shared *match = NULL;
6200 575 : size_t n = cvector_size(clog_slot_table.file_shareds);
6201 660 : for (size_t i = 0; i < n && !match; i++) {
6202 170 : clog_shared *fs =
6203 85 : *(clog_shared **)cvector_at(clog_slot_table.file_shareds, i);
6204 85 : if (fs->file_dir_dev == sh->file_dir_dev &&
6205 85 : fs->file_dir_ino == sh->file_dir_ino &&
6206 85 : strcmp(fs->file_base, sh->file_base) == 0 &&
6207 85 : (fs->rotation_enabled || sh->rotation_enabled))
6208 85 : match = fs;
6209 : }
6210 575 : if (!match) {
6211 492 : if (sh->rotation_enabled) {
6212 88 : ccol__mutex_lock(sh->mutex);
6213 88 : clog_remove_stale_live_tmps(sh);
6214 88 : ccol__mutex_unlock(sh->mutex);
6215 : }
6216 492 : if (sh->rotation_enabled && sh->rotation.compress_rotated) {
6217 : #ifdef RUNNING_UNIT_TESTS
6218 41 : clog_test_recover_gate();
6219 : #endif
6220 41 : ccol__mutex_lock(sh->mutex);
6221 41 : clog_recover_compressions(sh);
6222 41 : ccol__mutex_unlock(sh->mutex);
6223 : }
6224 984 : bool ok =
6225 492 : cvector_push_back(clog_slot_table.file_shareds, &sh) == ccol_success;
6226 492 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6227 492 : if (!ok) {
6228 0 : clog_close(h);
6229 0 : return CLOG_NULL;
6230 : }
6231 : return h;
6232 : }
6233 83 : ccol__mutex_lock(match->mutex);
6234 83 : int refs = match->ref_count;
6235 83 : bool compatible = refs > 0 && clog_file_targets_compatible(match, sh);
6236 73 : if (compatible) match->ref_count++;
6237 83 : ccol__mutex_unlock(match->mutex);
6238 83 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6239 83 : if (refs == 0) {
6240 : #ifdef RUNNING_UNIT_TESTS
6241 2 : atomic_fetch_add(&clog_test_closing_target_waits_state, 1);
6242 : #endif
6243 2 : usleep(delay_us);
6244 2 : if (delay_us < 100000) delay_us *= 2;
6245 2 : continue;
6246 : }
6247 81 : clog_close(h);
6248 81 : if (!compatible) return CLOG_NULL;
6249 73 : struct clogger *joined = logger_alloc(match, min_level);
6250 73 : if (!joined) {
6251 3 : clog_shared_unref(match);
6252 3 : return CLOG_NULL;
6253 : }
6254 70 : clog jh = clog_handle_acquire(joined);
6255 70 : if (jh == CLOG_NULL) {
6256 3 : logger_free(joined);
6257 3 : clog_shared_unref(match);
6258 : }
6259 : return jh;
6260 : }
6261 : }
6262 :
6263 : static bool clog_exit_lock_target(clog_shared *sh,
6264 : const struct timespec *deadline);
6265 : static struct timespec clog_ts_after_ms(const struct timespec *base,
6266 : unsigned int ms);
6267 :
6268 : // Does steps 5 and 6 of clog_close() for a target a drain left because its
6269 : // writer thread didn't answer, which may hold the mutex for ever. It takes the
6270 : // mutex only within a short bound, and the last handle only takes the target
6271 : // out of the module's tables instead of joining the thread; the process is
6272 : // ending anyway.
6273 4 : static void clog_close_left_target(clog_shared *sh) {
6274 4 : struct timespec now;
6275 4 : clock_gettime(CLOCK_MONOTONIC, &now);
6276 4 : struct timespec deadline =
6277 4 : clog_ts_after_ms(&now, CLOG_SPLIT_RECORD_DRAIN_WAIT_MS);
6278 4 : if (!clog_exit_lock_target(sh, &deadline)) return;
6279 0 : int remaining = --sh->ref_count;
6280 0 : ccol__mutex_unlock(sh->mutex);
6281 0 : if (remaining != 0) return;
6282 0 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6283 0 : clog_shareds_remove(clog_slot_table.live_shareds, sh);
6284 0 : if (sh->file_id_known) clog_shareds_remove(clog_slot_table.file_shareds, sh);
6285 0 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6286 : }
6287 :
6288 : // Closes h, the public end of a logger. Steps: Under the write lock it marks
6289 : // the slot not in use (a second close is fatal) and counts a close in flight;
6290 : // it waits, polling without a bound, until no call still pins the handle
6291 : // (giving up would free memory a caller still uses); under the write lock again
6292 : // it frees the logger and retires the slot, so the fork walk never sees a
6293 : // destroyed fields_mutex; it drops the target's reference, and the last handle
6294 : // tears the target down. Last of all it releases the table when the exit
6295 : // destructor deferred that, which is why the close counts in flight until then.
6296 : // A stale handle is fatal.
6297 3579 : void clog_close(clog h) {
6298 3579 : struct clogger *raw;
6299 3579 : clog_shared *sh;
6300 :
6301 : {
6302 3579 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
6303 3579 : if (h == 0)
6304 1 : ccol__fatal_err(
6305 : "clog_close: clog handle is invalid, stale, or already closed");
6306 3578 : uint32_t idx = (uint32_t)(h >> 32);
6307 3578 : uint32_t gen = (uint32_t)(h & 0xFFFFFFFFu);
6308 3578 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6309 3578 : clog_slot *slot = NULL;
6310 7155 : if (clog_slot_table.slots != NULL &&
6311 3577 : idx < cvector_size(clog_slot_table.slots))
6312 3577 : slot = (clog_slot *)cvector_at(clog_slot_table.slots, idx);
6313 3577 : if (!slot || !slot->in_use || slot->generation != gen) {
6314 1 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6315 1 : ccol__fatal_err(
6316 : "clog_close: clog handle is invalid, stale, or already closed");
6317 : }
6318 3577 : raw = slot->ptr;
6319 3577 : sh = raw->shared;
6320 3577 : slot->in_use = false;
6321 3577 : clog_slot_table.closes_in_flight++;
6322 3577 : ccol_pintable_retire(&clog_pintable, idx);
6323 3577 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6324 : }
6325 :
6326 : {
6327 3577 : uint32_t idx = (uint32_t)(h >> 32);
6328 3577 : unsigned int delay_us = 1;
6329 : #ifdef RUNNING_UNIT_TESTS
6330 3577 : if (ccol_pintable_pins(&clog_pintable, idx) > 0)
6331 1 : atomic_fetch_add(&clog_test_close_pin_waits_state, 1);
6332 : #endif
6333 3587 : while (ccol_pintable_pins(&clog_pintable, idx) > 0) {
6334 10 : usleep(delay_us);
6335 10 : if (delay_us < 1000) delay_us *= 2;
6336 : }
6337 : }
6338 :
6339 : #ifdef RUNNING_UNIT_TESTS
6340 3577 : if (atomic_load(&clog_test_close_finalize_hold)) {
6341 1 : atomic_store(&clog_test_close_finalize_entered_state, true);
6342 22 : for (unsigned int waited = 0; atomic_load(&clog_test_close_finalize_hold) &&
6343 : waited < CLOG_TEST_CLOSE_HOLD_MAX_US;
6344 21 : waited += 1000)
6345 21 : usleep(1000);
6346 : }
6347 : #endif
6348 :
6349 : {
6350 3577 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6351 3577 : uint32_t idx = (uint32_t)(h >> 32);
6352 3577 : clog_slot *slot = (clog_slot *)cvector_at(clog_slot_table.slots, idx);
6353 3577 : logger_free(raw);
6354 3577 : slot->freed = true;
6355 3577 : slot->ptr = NULL;
6356 3577 : slot->generation++;
6357 3577 : if (slot->generation == 0) slot->generation++;
6358 3577 : cvector_push_back(clog_slot_table.free_indices, &idx);
6359 3577 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6360 : }
6361 :
6362 : #ifdef RUNNING_UNIT_TESTS
6363 : {
6364 3577 : unsigned int w = atomic_load(&clog_test_close_release_window_us);
6365 3577 : if (w) {
6366 1 : atomic_store(&clog_test_close_release_window_entered_state, true);
6367 1 : usleep(w);
6368 : }
6369 : }
6370 : #endif
6371 :
6372 3577 : if (atomic_load_explicit(&sh->drain_left, memory_order_acquire)) {
6373 4 : clog_close_left_target(sh);
6374 : } else {
6375 3573 : ccol__mutex_lock(sh->mutex);
6376 3573 : int remaining = --sh->ref_count;
6377 3573 : ccol__mutex_unlock(sh->mutex);
6378 :
6379 3572 : if (remaining == 0) clog_shared_finish_last(sh);
6380 : }
6381 :
6382 3576 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
6383 3577 : clog_slot_table.closes_in_flight--;
6384 3577 : clog_release_slot_table_if_deferred_locked();
6385 3577 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
6386 3576 : }
6387 :
6388 : // Creates a child logger that shares parent_h's output and starts with a copy
6389 : // of its level and fields; the public way to add context per component. A
6390 : // failure is fatal. See clog__derive_checked().
6391 1745 : clog clog_derive(clog parent_h) {
6392 1745 : ccol_retval rv = ccol_success;
6393 1745 : clog h = clog__derive_checked(parent_h, &rv);
6394 1745 : if (rv == ccol_invalid_args)
6395 1 : ccol__fatal_err(
6396 : "clog_derive: clog handle is invalid, stale, or already closed");
6397 1744 : return h;
6398 : }
6399 :
6400 : // Derives a logger from parent_h without a fatal error, for clog_derive() and
6401 : // the HTTP modules, which need to fail cleanly. The parent's pin keeps it and
6402 : // its target alive throughout, so a concurrent close comes before the resolve
6403 : // or waits. Fields are copied under the parent's fields_mutex only, in the
6404 : // order they were set; the reference count is raised under shared->mutex. Gives
6405 : // the handle, or CLOG_NULL with *rv set to ccol_invalid_args (bad, stale or
6406 : // closed parent) or ccol_not_enough_memory.
6407 2149 : clog clog__derive_checked(clog parent_h, ccol_retval *rv) {
6408 2149 : *rv = ccol_invalid_args;
6409 2149 : struct clogger *parent = clog_resolve(parent_h);
6410 2149 : if (!parent) return CLOG_NULL;
6411 2142 : *rv = ccol_not_enough_memory;
6412 :
6413 2142 : struct clogger *child = logger_alloc(parent->shared, parent->min_level);
6414 2142 : if (!child) {
6415 4 : clog_resolve_unpin(parent);
6416 4 : return CLOG_NULL;
6417 : }
6418 :
6419 2138 : ccol__mutex_lock(parent->fields_mutex);
6420 : {
6421 2138 : ccol_chmap_walk walk = {0};
6422 2138 : const void *kv;
6423 2138 : const void *vv;
6424 3401 : while (ccol_chmap_walk_next(parent->fields, &walk, &kv, &vv)) {
6425 1287 : const char *k = (const char *)kv;
6426 1287 : const char *v = (const char *)vv;
6427 1287 : cmap_pair kp = {.ptr = (void *)k, .size = strlen(k) + 1};
6428 1287 : cmap_pair vp = {.ptr = (void *)v, .size = strlen(v) + 1};
6429 1287 : ccol_retval rv = chashmap_insert_elem(child->fields, &kp, &vp);
6430 1287 : if (rv != ccol_success && rv != ccol_key_already_present) {
6431 24 : ccol__mutex_unlock(parent->fields_mutex);
6432 24 : logger_free(child);
6433 24 : clog_resolve_unpin(parent);
6434 24 : return CLOG_NULL;
6435 : }
6436 : }
6437 : }
6438 2114 : ccol__mutex_unlock(parent->fields_mutex);
6439 :
6440 2114 : ccol__mutex_lock(parent->shared->mutex);
6441 2114 : parent->shared->ref_count++;
6442 2114 : ccol__mutex_unlock(parent->shared->mutex);
6443 :
6444 2114 : clog h = clog_handle_acquire(child);
6445 2114 : if (h == CLOG_NULL) {
6446 28 : ccol__mutex_lock(parent->shared->mutex);
6447 28 : parent->shared->ref_count--;
6448 28 : ccol__mutex_unlock(parent->shared->mutex);
6449 28 : logger_free(child);
6450 28 : clog_resolve_unpin(parent);
6451 28 : return CLOG_NULL;
6452 : }
6453 :
6454 2086 : clog_resolve_unpin(parent);
6455 2086 : *rv = ccol_success;
6456 2086 : return h;
6457 : }
6458 :
6459 : // Sets h's minimum level. The level is an atomic of this logger alone, so no
6460 : // lock is needed and siblings aren't affected. Returns ccol_invalid_args for a
6461 : // value outside the enum; a bad handle is fatal.
6462 2509 : ccol_retval clog_set_level(clog h, clog_level level) {
6463 2509 : struct clogger *lg = clog_resolve(h);
6464 2510 : if (!lg)
6465 1 : ccol__fatal_err(
6466 : "clog_set_level: clog handle is invalid, stale, or already closed");
6467 :
6468 2509 : ccol_retval rv = ccol_invalid_args;
6469 2509 : if (clog_level_is_valid(level)) {
6470 2507 : lg->min_level = level;
6471 2507 : rv = ccol_success;
6472 : }
6473 2509 : clog_resolve_unpin(lg);
6474 2509 : return rv;
6475 : }
6476 :
6477 : // Gives h's minimum level, read atomically, so a caller can check what h
6478 : // records. A bad handle is fatal.
6479 2011 : clog_level clog_get_level(clog h) {
6480 2011 : struct clogger *lg = clog_resolve(h);
6481 2011 : if (!lg)
6482 2 : ccol__fatal_err(
6483 : "clog_get_level: clog handle is invalid, stale, or already closed");
6484 :
6485 2009 : clog_level l = lg->min_level;
6486 2009 : clog_resolve_unpin(lg);
6487 2008 : return l;
6488 : }
6489 :
6490 : // Sets the output format of h's target (every logger sharing it). Syslog is
6491 : // refused for a file logger, since it needs a caller's socket. Returns
6492 : // ccol_invalid_args for those cases and leaves the format alone. Takes the
6493 : // target's mutex.
6494 179 : ccol_retval clog_set_format(clog h, clog_format fmt) {
6495 179 : struct clogger *lg = clog_resolve(h);
6496 179 : if (!lg)
6497 1 : ccol__fatal_err(
6498 : "clog_set_format: clog handle is invalid, stale, or already closed");
6499 :
6500 178 : if (!clog_format_is_valid(fmt)) {
6501 2 : clog_resolve_unpin(lg);
6502 2 : return ccol_invalid_args;
6503 : }
6504 176 : ccol_retval rv = ccol_invalid_args;
6505 176 : ccol__mutex_lock(lg->shared->mutex);
6506 176 : if (fmt != CLOG_FMT_SYSLOG || !lg->shared->owns_fd) {
6507 172 : lg->shared->format = fmt;
6508 172 : rv = ccol_success;
6509 : }
6510 176 : ccol__mutex_unlock(lg->shared->mutex);
6511 176 : clog_resolve_unpin(lg);
6512 176 : return rv;
6513 : }
6514 :
6515 : // Gives the output format of h's target, read under its mutex. A bad handle is
6516 : // fatal.
6517 12 : clog_format clog_get_format(clog h) {
6518 12 : struct clogger *lg = clog_resolve(h);
6519 12 : if (!lg)
6520 1 : ccol__fatal_err(
6521 : "clog_get_format: clog handle is invalid, stale, or already closed");
6522 :
6523 11 : ccol__mutex_lock(lg->shared->mutex);
6524 11 : clog_format f = lg->shared->format;
6525 11 : ccol__mutex_unlock(lg->shared->mutex);
6526 11 : clog_resolve_unpin(lg);
6527 11 : return f;
6528 : }
6529 :
6530 : // Sets the syslog facility of h's target, which goes into the PRI of every
6531 : // later syslog record. Returns ccol_invalid_args for a value outside 0 to 11
6532 : // and 16 to 23. Takes the target's mutex.
6533 8 : ccol_retval clog_set_facility(clog h, clog_syslog_facility facility) {
6534 8 : struct clogger *lg = clog_resolve(h);
6535 8 : if (!lg)
6536 1 : ccol__fatal_err(
6537 : "clog_set_facility: clog handle is invalid, stale, or already closed");
6538 :
6539 7 : if (!clog_facility_is_valid(facility)) {
6540 4 : clog_resolve_unpin(lg);
6541 4 : return ccol_invalid_args;
6542 : }
6543 3 : ccol__mutex_lock(lg->shared->mutex);
6544 3 : lg->shared->syslog_facility = facility;
6545 3 : ccol__mutex_unlock(lg->shared->mutex);
6546 3 : clog_resolve_unpin(lg);
6547 3 : return ccol_success;
6548 : }
6549 :
6550 : // Gives the syslog facility of h's target, read under its mutex. A bad handle
6551 : // is fatal.
6552 7 : clog_syslog_facility clog_get_facility(clog h) {
6553 7 : struct clogger *lg = clog_resolve(h);
6554 7 : if (!lg)
6555 1 : ccol__fatal_err(
6556 : "clog_get_facility: clog handle is invalid, stale, or already closed");
6557 :
6558 6 : ccol__mutex_lock(lg->shared->mutex);
6559 6 : clog_syslog_facility f = lg->shared->syslog_facility;
6560 6 : ccol__mutex_unlock(lg->shared->mutex);
6561 6 : clog_resolve_unpin(lg);
6562 6 : return f;
6563 : }
6564 :
6565 : // Sets a field that every later record of h carries. The key must be 1 or more
6566 : // PRINTUSASCII characters and not a reserved key, so it can't break logfmt or
6567 : // an SD-PARAM-NAME. It works under h's fields_mutex, so siblings' writes don't
6568 : // contend. Returns ccol_success (a replaced value too), ccol_invalid_args, or
6569 : // ccol_not_enough_memory with the fields unchanged.
6570 1243 : ccol_retval clog_set_field(clog h, const char *key, const char *value) {
6571 1243 : struct clogger *lg = clog_resolve(h);
6572 1243 : if (!lg)
6573 1 : ccol__fatal_err(
6574 : "clog_set_field: clog handle is invalid, stale, or already closed");
6575 :
6576 1242 : bool args_ok = key && value && *key != '\0' && !is_reserved_field_key(key);
6577 8949 : for (const char *p = key; args_ok && *p; p++) {
6578 7707 : unsigned char c = (unsigned char)*p;
6579 7707 : if (c < 0x21 || c > 0x7e || *p == '=' || *p == '"' || *p == '\\' ||
6580 : *p == ']')
6581 10 : args_ok = false;
6582 : }
6583 1242 : if (!args_ok) {
6584 22 : clog_resolve_unpin(lg);
6585 22 : return ccol_invalid_args;
6586 : }
6587 :
6588 1220 : ccol__mutex_lock(lg->fields_mutex);
6589 :
6590 1220 : cmap_pair kp = {.ptr = (void *)key, .size = strlen(key) + 1};
6591 1220 : cmap_pair vp = {.ptr = (void *)value, .size = strlen(value) + 1};
6592 1220 : ccol_retval rv = chashmap_insert_elem(lg->fields, &kp, &vp);
6593 :
6594 1220 : ccol__mutex_unlock(lg->fields_mutex);
6595 1220 : clog_resolve_unpin(lg);
6596 1220 : return rv == ccol_key_already_present ? ccol_success : rv;
6597 : }
6598 :
6599 : // Removes field key from h, so later records stop carrying it. Works under h's
6600 : // fields_mutex.
6601 506 : void clog_remove_field(clog h, const char *key) {
6602 506 : struct clogger *lg = clog_resolve(h);
6603 506 : if (!lg)
6604 1 : ccol__fatal_err(
6605 : "clog_remove_field: clog handle is invalid, stale, or already closed");
6606 :
6607 505 : if (!key) {
6608 1 : clog_resolve_unpin(lg);
6609 1 : return;
6610 : }
6611 :
6612 504 : ccol__mutex_lock(lg->fields_mutex);
6613 :
6614 504 : cmap_pair kp = {.ptr = (void *)key, .size = strlen(key) + 1};
6615 504 : chashmap_remove_elem(lg->fields, &kp);
6616 :
6617 504 : ccol__mutex_unlock(lg->fields_mutex);
6618 504 : clog_resolve_unpin(lg);
6619 : }
6620 :
6621 : // Removes every field of h, so later records carry none. Works under h's
6622 : // fields_mutex.
6623 4 : void clog_clear_fields(clog h) {
6624 4 : struct clogger *lg = clog_resolve(h);
6625 4 : if (!lg)
6626 1 : ccol__fatal_err(
6627 : "clog_clear_fields: clog handle is invalid, stale, or already closed");
6628 :
6629 3 : ccol__mutex_lock(lg->fields_mutex);
6630 3 : chashmap_reset(lg->fields, 0);
6631 3 : ccol__mutex_unlock(lg->fields_mutex);
6632 3 : clog_resolve_unpin(lg);
6633 3 : }
6634 :
6635 : static bool clog_exit_lock_target(clog_shared *sh,
6636 : const struct timespec *deadline);
6637 : static struct timespec clog_after_drain_deadline(clog_shared *sh);
6638 : static bool clog_fatal_lock_target(clog_shared *sh,
6639 : const struct timespec *deadline);
6640 :
6641 : // Writes a CLOG_FATAL record like clog_write_record() and tells whether every
6642 : // byte went out, so the fatal path can report a loss on stderr. Its writes are
6643 : // already bounded by then.
6644 19 : static __attribute__((noinline, cold)) bool clog_fatal_write_record(
6645 : clog_shared *sh, clog_format fmt, const char *data, size_t len) {
6646 19 : if ((sh->async_partial_record & CLOG_OWED_REPAIR) &&
6647 0 : !clog_owed_gate(sh, fmt, len, CLOG_WRITE_WAIT_FOREVER))
6648 : return false;
6649 19 : size_t written = write_all(sh, data, len, CLOG_WRITE_WAIT_FOREVER);
6650 19 : if (sh->rotation_enabled) sh->bytes_written += (off_t)written;
6651 19 : if (written < len)
6652 5 : clog_note_truncated_record(sh, fmt, data, written, len, errno);
6653 19 : return written == len;
6654 : }
6655 :
6656 : // Builds and writes one record synchronously, under the target's mutex, which
6657 : // it takes itself (the caller must not hold it). It's instantiated twice with
6658 : // fatal as a constant: For ordinary records and for a CLOG_FATAL record, which
6659 : // skips the level filter, takes the mutex within deadline, marks a sink that
6660 : // isn't a regular file as bounded, and returns false when the record didn't go
6661 : // out whole. The ordinary records re-check the level under the lock. The
6662 : // message is formatted on the stack and spills to the heap (ap2 is its copy).
6663 : // It settles a split async record and pays an owed repair first, runs the time
6664 : // rotation check before the write and the size check after, and writes syslog
6665 : // frames after the record. bt_syms is only read; the caller frees it.
6666 : static inline __attribute__((always_inline, format(printf, 9, 0))) bool
6667 15116 : clog_write_sync_body(struct clogger *lg, clog_level level, const char *file,
6668 : int line, const char *func, bool with_backtrace,
6669 : char *const *bt_syms, int bt_depth, const char *fmt,
6670 : va_list ap, va_list ap2, bool fatal,
6671 : const struct timespec *deadline) {
6672 15116 : bool delivered = true;
6673 30231 : const char *proc_val = clog_tident_get()->proc;
6674 :
6675 15115 : if (fatal) {
6676 20 : if (!clog_fatal_lock_target(lg->shared, deadline)) return false;
6677 19 : struct stat st;
6678 19 : if (lg->shared->sink_kind != CLOG_SINK_PLAIN ||
6679 16 : (lg->shared->fd >= 0 && fstat(lg->shared->fd, &st) == 0 &&
6680 16 : !S_ISREG(st.st_mode) && !S_ISBLK(st.st_mode)))
6681 6 : lg->shared->sink_kind |= CLOG_SINK_FATAL_BOUND;
6682 : } else {
6683 : #ifdef RUNNING_UNIT_TESTS
6684 15095 : atomic_fetch_add(&lg->shared->test_sync_lock_waiters, 1);
6685 : #endif
6686 15095 : ccol__mutex_lock(lg->shared->mutex);
6687 : #ifdef RUNNING_UNIT_TESTS
6688 15100 : atomic_fetch_sub(&lg->shared->test_sync_lock_waiters, 1);
6689 : #endif
6690 : }
6691 :
6692 15100 : if (level < lg->min_level && level != CLOG_FATAL) {
6693 1 : ccol__mutex_unlock(lg->shared->mutex);
6694 1 : return true;
6695 : }
6696 :
6697 15118 : if (lg->shared->fd < 0) {
6698 0 : ccol__mutex_unlock(lg->shared->mutex);
6699 0 : return false;
6700 : }
6701 : #ifdef RUNNING_UNIT_TESTS
6702 15118 : if (!fatal) atomic_fetch_add(&lg->shared->test_sync_records_locked, 1);
6703 : #endif
6704 :
6705 15118 : const clog_format log_fmt = lg->shared->format;
6706 :
6707 15118 : char msg_stack[1024];
6708 15118 : char *msg = msg_stack;
6709 15118 : char *msg_heap = NULL;
6710 :
6711 15118 : int mlen = vsnprintf(msg_stack, sizeof(msg_stack), fmt, ap);
6712 :
6713 15118 : if (mlen < 0) {
6714 1 : static const char fmt_err_msg[] = "<log message formatting failed>";
6715 1 : memcpy(msg_stack, fmt_err_msg, sizeof(fmt_err_msg));
6716 15117 : } else if ((size_t)mlen >= sizeof(msg_stack)) {
6717 20 : msg_heap = ccol__mem_alloc(lg->shared->m_procs, (size_t)mlen + 1);
6718 20 : if (msg_heap) {
6719 19 : int mlen2 = vsnprintf(msg_heap, (size_t)mlen + 1, fmt, ap2);
6720 19 : if (mlen2 >= 0) msg = msg_heap;
6721 : }
6722 20 : if (msg == msg_stack) {
6723 1 : static const char trunc_marker[] = "...[truncated]";
6724 1 : size_t mark_len = sizeof(trunc_marker) - 1;
6725 1 : if (mark_len < sizeof(msg_stack) - 1)
6726 1 : memcpy(msg_stack + sizeof(msg_stack) - 1 - mark_len, trunc_marker,
6727 : mark_len);
6728 : }
6729 : }
6730 :
6731 15118 : if (lg->shared->async_partial_record)
6732 20 : clog_flush_and_settle(lg->shared, log_fmt, CLOG_SPLIT_RECORD_DRAIN_WAIT_MS);
6733 :
6734 15118 : clog_time_rotate_if_due(lg->shared);
6735 :
6736 15118 : struct timeval ts;
6737 15118 : gettimeofday(&ts, NULL);
6738 :
6739 15118 : buf_reset(&lg->buf);
6740 15118 : clog_field_source fsrc;
6741 15118 : fsrc.is_live = true;
6742 15118 : fsrc.u.live.fields = lg->fields;
6743 15118 : fsrc.u.live.mutex = &lg->fields_mutex;
6744 15118 : bool built = clog_build_record(&lg->buf, lg->shared, log_fmt, level, &ts,
6745 : proc_val, file, line, func, msg, &fsrc,
6746 : with_backtrace, bt_syms, bt_depth, NULL);
6747 :
6748 15118 : ccol__mem_free(lg->shared->m_procs, msg_heap);
6749 :
6750 15118 : if (lg->shared->fd >= 0) {
6751 15118 : if (built) {
6752 15118 : if (fatal)
6753 19 : delivered = clog_fatal_write_record(lg->shared, log_fmt, lg->buf.data,
6754 : lg->buf.len);
6755 : else
6756 15099 : clog_write_record(lg->shared, log_fmt, lg->buf.data, lg->buf.len);
6757 : } else {
6758 0 : clog_write_unrepresentable_record(lg->shared, log_fmt, level,
6759 : with_backtrace);
6760 : }
6761 : }
6762 :
6763 15116 : if (with_backtrace && lg->shared->fd >= 0 && log_fmt == CLOG_FMT_SYSLOG)
6764 8 : emit_backtrace_syslog_lines(&lg->buf, lg->shared, level, &ts, bt_syms,
6765 : bt_depth);
6766 :
6767 15116 : clog_size_rotate_if_due(lg->shared);
6768 :
6769 19 : ccol__mutex_unlock(lg->shared->mutex);
6770 15097 : return delivered;
6771 : }
6772 :
6773 : // Writes one ordinary record synchronously through clog_write_sync_body(): The
6774 : // path of every non-async target, and the fallback of clog_write_async() when
6775 : // the envelope can't be allocated.
6776 15096 : static void __attribute__((format(printf, 9, 0))) clog_write_sync(
6777 : struct clogger *lg, clog_level level, const char *file, int line,
6778 : const char *func, bool with_backtrace, char *const *bt_syms, int bt_depth,
6779 : const char *fmt, va_list ap) {
6780 15096 : va_list ap2;
6781 15096 : va_copy(ap2, ap);
6782 15096 : (void)clog_write_sync_body(lg, level, file, line, func, with_backtrace,
6783 : bt_syms, bt_depth, fmt, ap, ap2, false, NULL);
6784 15098 : va_end(ap2);
6785 15098 : }
6786 :
6787 : static void clog_flush_pinned(struct clogger *lg);
6788 :
6789 : // The static, empty envelope of a wake, so waking the writer allocates nothing
6790 : // on a bounded queue.
6791 : static clog_async_msg clog_wake_envelope = {.kind = CLOG_ASYNC_MSG_WAKE};
6792 :
6793 : // Wakes sh's writer thread after a thread that wrote a record itself left work
6794 : // for it (kept batch bytes, an owed repair), since an idle writer waits without
6795 : // a limit. A refused send needs nothing more: A full queue wakes the writer
6796 : // anyway, sends off belong to a drain that settles the target, and an unbounded
6797 : // queue out of memory leaves the work to the next record, flush, close or exit
6798 : // drain.
6799 19 : static __attribute__((cold)) void clog_wake_writer(clog_shared *sh) {
6800 19 : cmessage m = {.data = &clog_wake_envelope,
6801 : .size = sizeof(clog_wake_envelope)};
6802 19 : if (sh->is_bounded_queue)
6803 5 : (void)ccircq_try_send(sh->q.circq, &m);
6804 : else
6805 14 : (void)cdynmq_send(sh->q.dynmq, &m);
6806 19 : }
6807 :
6808 : // Formats one record into a job and queues it for the writer thread, the path
6809 : // of every async target. Fields and identity are captured now. Without an
6810 : // envelope the call goes to clog_write_sync(). When the send fails (no memory,
6811 : // or sends turned off by a drain), the record is written directly from the job
6812 : // under the mutex, after clog_flush_pinned() so it can't land ahead of records
6813 : // already queued; it joins the batch behind kept records when it can, and runs
6814 : // the rotation checks and the settle like any direct write. Only on the exit
6815 : // paths is a record dropped: When a drain left the target, or when the mutex
6816 : // doesn't come before the drain's deadline (an unbounded wait would keep the
6817 : // handle pinned and hang a later close).
6818 26403 : static void __attribute__((format(printf, 9, 0))) clog_write_async(
6819 : struct clogger *lg, clog_level level, const char *file, int line,
6820 : const char *func, bool with_backtrace, char **bt_syms, int bt_depth,
6821 : const char *fmt, va_list ap) {
6822 52762 : clog_async_msg *envelope =
6823 26403 : ccol__mem_calloc(lg->shared->m_procs, 1, sizeof(*envelope));
6824 26359 : if (!envelope) {
6825 3 : if (atomic_load_explicit(&lg->shared->drain_left, memory_order_acquire)) {
6826 0 : if (bt_syms) free(bt_syms);
6827 20 : return;
6828 : }
6829 3 : clog_flush_pinned(lg);
6830 3 : clog_write_sync(lg, level, file, line, func, with_backtrace, bt_syms,
6831 : bt_depth, fmt, ap);
6832 3 : if (bt_syms) free(bt_syms);
6833 3 : clog_wake_writer(lg->shared);
6834 3 : return;
6835 : }
6836 26356 : envelope->kind = CLOG_ASYNC_MSG_JOB;
6837 26356 : clog_async_job *job = &envelope->u.job;
6838 :
6839 26356 : job->bt_syms = bt_syms;
6840 26356 : job->bt_depth = bt_depth;
6841 26356 : job->level = level;
6842 26356 : job->file = file;
6843 26356 : job->line = line;
6844 26356 : job->func = func;
6845 26356 : job->with_backtrace = with_backtrace;
6846 26356 : gettimeofday(&job->ts, NULL);
6847 26402 : _Static_assert(sizeof(job->proc_val) == CLOG_PROC_VAL_LEN,
6848 : "a job holds the whole cached identity string");
6849 52804 : memcpy(job->proc_val, clog_tident_get()->proc, CLOG_PROC_VAL_LEN);
6850 :
6851 26402 : job->msg_heap = NULL;
6852 26402 : va_list ap2;
6853 26402 : va_copy(ap2, ap);
6854 26402 : int mlen = vsnprintf(job->msg_inline, sizeof(job->msg_inline), fmt, ap);
6855 26402 : if (mlen < 0) {
6856 1 : static const char fmt_err_msg[] = "<log message formatting failed>";
6857 1 : memcpy(job->msg_inline, fmt_err_msg, sizeof(fmt_err_msg));
6858 26401 : } else if ((size_t)mlen >= sizeof(job->msg_inline)) {
6859 475 : job->msg_heap = ccol__mem_alloc(lg->shared->m_procs, (size_t)mlen + 1);
6860 475 : if (job->msg_heap) {
6861 474 : int mlen2 = vsnprintf(job->msg_heap, (size_t)mlen + 1, fmt, ap2);
6862 474 : if (mlen2 < 0) {
6863 0 : ccol__mem_free(lg->shared->m_procs, job->msg_heap);
6864 0 : job->msg_heap = NULL;
6865 : }
6866 : }
6867 475 : if (!job->msg_heap) {
6868 1 : static const char trunc_marker[] = "...[truncated]";
6869 1 : size_t mark_len = sizeof(trunc_marker) - 1;
6870 1 : if (mark_len < sizeof(job->msg_inline) - 1)
6871 1 : memcpy(job->msg_inline + sizeof(job->msg_inline) - 1 - mark_len,
6872 : trunc_marker, mark_len);
6873 : }
6874 : }
6875 26402 : va_end(ap2);
6876 26402 : job->msg = job->msg_heap ? job->msg_heap : job->msg_inline;
6877 :
6878 26402 : snapshot_fields(lg, &job->fields, &job->field_count, &job->field_pool,
6879 : &job->fields_snapshot_failed);
6880 :
6881 26404 : cmessage m = {.data = envelope, .size = sizeof(*envelope)};
6882 52819 : ccol_retval rv = lg->shared->is_bounded_queue
6883 9794 : ? ccircq_send(lg->shared->q.circq, &m)
6884 26404 : : cdynmq_send(lg->shared->q.dynmq, &m);
6885 26415 : if (rv != ccol_success &&
6886 33 : atomic_load_explicit(&lg->shared->drain_left, memory_order_acquire)) {
6887 8 : clog_async_job_release(lg->shared, envelope);
6888 8 : return;
6889 : }
6890 25 : if (rv != ccol_success) {
6891 25 : clog_flush_pinned(lg);
6892 :
6893 24 : if (rv == ccol_not_permitted) {
6894 18 : struct timespec dl = clog_after_drain_deadline(lg->shared);
6895 19 : if (!clog_exit_lock_target(lg->shared, &dl)) {
6896 8 : clog_async_job_release(lg->shared, envelope);
6897 8 : return;
6898 : }
6899 : } else {
6900 6 : ccol__mutex_lock(lg->shared->mutex);
6901 : }
6902 17 : if (lg->shared->fd >= 0) {
6903 17 : clog_format fmt2 = lg->shared->format;
6904 17 : clog_field_source fsrc;
6905 17 : fsrc.is_live = false;
6906 17 : fsrc.u.snap.views = job->fields;
6907 17 : fsrc.u.snap.count = job->field_count;
6908 17 : fsrc.u.snap.pool = job->field_pool.buf;
6909 17 : fsrc.u.snap.failed = job->fields_snapshot_failed;
6910 :
6911 17 : clog_shared *wsh = lg->shared;
6912 17 : if (wsh->async_buf.len > 0)
6913 2 : clog_flush_and_settle(wsh, fmt2, CLOG_SPLIT_RECORD_DRAIN_WAIT_MS);
6914 17 : if (wsh->async_buf.len > 0 && fmt2 != CLOG_FMT_SYSLOG &&
6915 1 : !wsh->sink_per_record) {
6916 1 : size_t record_start = wsh->async_buf.len;
6917 1 : bool used_fallback = false;
6918 1 : if (clog_build_record(&wsh->async_buf, wsh, fmt2, job->level, &job->ts,
6919 : job->proc_val, job->file, job->line, job->func,
6920 1 : job->msg, &fsrc, job->with_backtrace,
6921 1 : job->bt_syms, job->bt_depth, &used_fallback) &&
6922 1 : !used_fallback) {
6923 1 : ccol__mutex_unlock(wsh->mutex);
6924 1 : clog_async_job_release(wsh, envelope);
6925 1 : return;
6926 : }
6927 0 : wsh->async_buf.len = record_start;
6928 : }
6929 :
6930 16 : clog_time_rotate_if_due(lg->shared);
6931 :
6932 16 : buf_reset(&lg->buf);
6933 32 : bool built = clog_build_record(
6934 : &lg->buf, lg->shared, fmt2, job->level, &job->ts, job->proc_val,
6935 16 : job->file, job->line, job->func, job->msg, &fsrc, job->with_backtrace,
6936 16 : job->bt_syms, job->bt_depth, NULL);
6937 16 : if (built) {
6938 16 : clog_write_record(lg->shared, fmt2, lg->buf.data, lg->buf.len);
6939 : } else {
6940 0 : clog_write_unrepresentable_record(lg->shared, fmt2, job->level,
6941 0 : job->with_backtrace);
6942 : }
6943 16 : if (job->with_backtrace && fmt2 == CLOG_FMT_SYSLOG)
6944 0 : emit_backtrace_syslog_lines(&lg->buf, lg->shared, job->level, &job->ts,
6945 0 : job->bt_syms, job->bt_depth);
6946 :
6947 16 : clog_size_rotate_if_due(lg->shared);
6948 : }
6949 16 : ccol__mutex_unlock(lg->shared->mutex);
6950 :
6951 16 : clog_async_job_release(lg->shared, envelope);
6952 16 : clog_wake_writer(lg->shared);
6953 : }
6954 : }
6955 :
6956 : #ifdef RUNNING_UNIT_TESTS
6957 :
6958 : // Force the mutex or condition variable initialization of the next
6959 : // clog_flush_pinned() to fail, which glibc gives no way to provoke. Each
6960 : // disarms itself.
6961 : static _Atomic bool clog_test_force_flush_mutex_init_failure_state = false;
6962 : static _Atomic bool clog_test_force_flush_condvar_init_failure_state = false;
6963 :
6964 : // Take one forced init failure of the flush request's mutex or condition
6965 : // variable, for clog_flush_pinned() in a test build; true when one was armed.
6966 262 : static bool clog_test_consume_forced_flush_mutex_init_failure(void) {
6967 262 : return atomic_exchange(&clog_test_force_flush_mutex_init_failure_state,
6968 : false);
6969 : }
6970 261 : static bool clog_test_consume_forced_flush_condvar_init_failure(void) {
6971 261 : return atomic_exchange(&clog_test_force_flush_condvar_init_failure_state,
6972 : false);
6973 : }
6974 :
6975 : // Arm or disarm the forced failure of the next flush request's mutex or
6976 : // condition variable init, so a test can check that the flush returns at once.
6977 1 : void clog__test_force_flush_mutex_init_failure(bool force) {
6978 1 : atomic_store(&clog_test_force_flush_mutex_init_failure_state, force);
6979 1 : }
6980 1 : void clog__test_force_flush_condvar_init_failure(bool force) {
6981 1 : atomic_store(&clog_test_force_flush_condvar_init_failure_state, force);
6982 1 : }
6983 : #else
6984 :
6985 : // Stubs of a non-test build, so clog_flush_pinned() needs no #ifdef: No init
6986 : // failure is forced.
6987 : static inline bool clog_test_consume_forced_flush_mutex_init_failure(void) {
6988 : return false;
6989 : }
6990 : static inline bool clog_test_consume_forced_flush_condvar_init_failure(void) {
6991 : return false;
6992 : }
6993 : #endif
6994 :
6995 : static void clog_flush_after_drain(clog_shared *sh);
6996 :
6997 : // Flushes lg's async target: Queues a flush request and waits until the writer
6998 : // thread has written everything queued before it. It's the body of
6999 : // clog_flush(), and clog_write_async() and the fatal path call it with a handle
7000 : // they already pinned (the pin is held through the wait, so a close waits for
7001 : // it). The request's mutex and condition variable live on this stack and are
7002 : // checked, since waiting on a broken one is undefined; a failed init or send
7003 : // returns at once. When a drain turned sends off, it waits, bounded, through
7004 : // the owner send for what the queue already holds. A target a drain left is
7005 : // skipped.
7006 263 : static void clog_flush_pinned(struct clogger *lg) {
7007 263 : if (atomic_load_explicit(&lg->shared->drain_left, memory_order_acquire))
7008 3 : return;
7009 262 : clog_async_ctrl ctrl;
7010 523 : if (clog_test_consume_forced_flush_mutex_init_failure() ||
7011 261 : ccol__mutex_init(ctrl.mutex) != 0)
7012 1 : return;
7013 521 : if (clog_test_consume_forced_flush_condvar_init_failure() ||
7014 260 : ccol__cond_var_init(ctrl.cv) != 0) {
7015 1 : ccol__mutex_destroy(ctrl.mutex);
7016 1 : return;
7017 : }
7018 260 : ctrl.done = false;
7019 :
7020 260 : clog_async_msg envelope;
7021 260 : envelope.kind = CLOG_ASYNC_MSG_FLUSH;
7022 260 : envelope.u.ctrl = &ctrl;
7023 260 : cmessage m = {.data = &envelope, .size = sizeof(envelope)};
7024 520 : ccol_retval rv = lg->shared->is_bounded_queue
7025 11 : ? ccircq_send(lg->shared->q.circq, &m)
7026 260 : : cdynmq_send(lg->shared->q.dynmq, &m);
7027 :
7028 260 : if (rv == ccol_success) {
7029 240 : ccol__mutex_lock(ctrl.mutex);
7030 480 : while (!ctrl.done) ccol__cond_var_wait(ctrl.cv, ctrl.mutex);
7031 240 : ccol__mutex_unlock(ctrl.mutex);
7032 : }
7033 260 : ccol__mutex_destroy(ctrl.mutex);
7034 260 : ccol__cond_var_destroy(ctrl.cv);
7035 259 : if (rv == ccol_not_permitted) clog_flush_after_drain(lg->shared);
7036 : }
7037 :
7038 : // Flushes h's async target and returns once every record queued before the call
7039 : // is written, so a caller can make sure its records reached the output. Does
7040 : // nothing for a synchronous logger.
7041 237 : void clog_flush(clog h) {
7042 237 : struct clogger *lg = clog_resolve(h);
7043 237 : if (!lg)
7044 1 : ccol__fatal_err(
7045 : "clog_flush: clog handle is invalid, stale, or already closed");
7046 236 : if (lg->shared->async_enabled) clog_flush_pinned(lg);
7047 236 : clog_resolve_unpin(lg);
7048 236 : }
7049 :
7050 : // Makes the last delivery attempt for an async target's batch on the fatal and
7051 : // exit paths: One bounded flush, a settle of a split record, and a marker for
7052 : // whatever is still undelivered. timeout_ms bounds each write so an output that
7053 : // takes nothing can't hold the process. Needs sh->mutex.
7054 28 : static void clog_settle_batch_locked(clog_shared *sh, int timeout_ms) {
7055 28 : if (sh->async_buf.len > 0) {
7056 7 : writer_flush_buffer(sh, timeout_ms);
7057 7 : clog_settle_after_flush(sh, sh->format, timeout_ms);
7058 7 : clog_drop_undelivered(sh, "the process stopped", timeout_ms);
7059 : }
7060 28 : }
7061 :
7062 : static void clog_exit_drain(void);
7063 :
7064 : // True once the exit drain is registered with atexit().
7065 : static bool clog_exit_drain_registered;
7066 :
7067 : // Ends a CLOG_FATAL call after its record and unpin: Calls exit(), whose exit
7068 : // drain flushes every other async logger and finishes compressions within its
7069 : // budget. Runs the drain directly only when its registration failed.
7070 20 : static __attribute__((noinline, noreturn)) void clog_fatal_exit(void) {
7071 20 : if (!clog_exit_drain_registered) clog_exit_drain();
7072 20 : exit(EXIT_FAILURE);
7073 : }
7074 :
7075 : // Exit drain: At exit() or a return from main() a still open async logger would
7076 : // lose its queue and batch and cut a compression off, so a handler registered
7077 : // at load drains every async target (queue, batch, a marker for what can't go
7078 : // out) and then the compressions. One budget bounds every wait and lock, so a
7079 : // stuck writer or a held lock delays exit by at most CLOG_EXIT_DRAIN_BUDGET_MS.
7080 : // A target that can't be locked in time, or whose own thread called exit(), is
7081 : // skipped. An abandoned compression gets CLOG_EXIT_ABANDON_GRACE_MS more to
7082 : // stop and remove its output.
7083 : #define CLOG_EXIT_DRAIN_BUDGET_MS 5000U
7084 : #define CLOG_EXIT_ABANDON_GRACE_MS 1000U
7085 :
7086 : #ifdef RUNNING_UNIT_TESTS
7087 :
7088 : // Budget a test sets for the exit drain; 0 keeps the default.
7089 : static _Atomic unsigned int clog_test_exit_drain_budget_ms = 0;
7090 :
7091 : // Sets the exit drain budget, so a test of a stuck target runs fast; 0 restores
7092 : // CLOG_EXIT_DRAIN_BUDGET_MS.
7093 27 : void clog__test_set_exit_drain_budget_ms(unsigned int budget_ms) {
7094 27 : atomic_store(&clog_test_exit_drain_budget_ms, budget_ms);
7095 27 : }
7096 :
7097 : // Gives the exit drain budget in milliseconds; a test build can shorten it so a
7098 : // stuck-target test doesn't wait 5 s.
7099 58 : static unsigned int clog_exit_drain_budget_ms(void) {
7100 58 : unsigned int b = atomic_load(&clog_test_exit_drain_budget_ms);
7101 38 : return b ? b : CLOG_EXIT_DRAIN_BUDGET_MS;
7102 : }
7103 :
7104 : // Locks the mutex of h's target and never unlocks it, so a test can make a
7105 : // stuck target.
7106 1 : void clog__test_lock_target_forever(clog h) {
7107 1 : struct clogger *lg = clog_resolve(h);
7108 1 : if (!lg) return;
7109 1 : clog_shared *sh = lg->shared;
7110 1 : clog_resolve_unpin(lg);
7111 1 : ccol__mutex_lock(sh->mutex);
7112 : }
7113 :
7114 : // Takes the handle table's write lock and never releases it, so a test can
7115 : // check that the exit drain gives up on it.
7116 1 : void clog__test_lock_table_forever(void) {
7117 1 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
7118 1 : ccol__rw_lock_wrlock(clog_slot_table.rwlock);
7119 1 : }
7120 :
7121 : // While set, the drain's send to a bounded queue doesn't wait, as when the
7122 : // budget is spent.
7123 : static _Atomic bool clog_test_exit_drain_send_no_wait = false;
7124 :
7125 : // Makes the exit drain's send to a bounded queue not wait while on is true, so
7126 : // a test can reach the full-queue path at once.
7127 1 : void clog__test_force_exit_drain_send_without_wait(bool on) {
7128 1 : atomic_store(&clog_test_exit_drain_send_no_wait, on);
7129 1 : }
7130 :
7131 : // The targets a drain left because their writer didn't answer, so a test can
7132 : // ask about one; a fixed table is enough.
7133 : #define CLOG_TEST_LEFT_TARGETS_LIMIT 16
7134 : static clog_shared *clog_test_left_targets[CLOG_TEST_LEFT_TARGETS_LIMIT];
7135 : static _Atomic size_t clog_test_left_targets_count = 0;
7136 :
7137 : // Records that a drain left sh, so clog__test_exit_drain_left_target() can
7138 : // report it.
7139 10 : static void clog_test_note_left_target(clog_shared *sh) {
7140 10 : size_t i = atomic_fetch_add(&clog_test_left_targets_count, 1);
7141 10 : if (i < CLOG_TEST_LEFT_TARGETS_LIMIT) clog_test_left_targets[i] = sh;
7142 : }
7143 :
7144 : // Tells whether a drain gave up on h's target, so a test can check that a stuck
7145 : // target is left.
7146 1 : bool clog__test_exit_drain_left_target(clog h) {
7147 1 : struct clogger *lg = clog_resolve(h);
7148 1 : if (!lg) return false;
7149 1 : clog_shared *sh = lg->shared;
7150 1 : clog_resolve_unpin(lg);
7151 1 : size_t n = atomic_load(&clog_test_left_targets_count);
7152 1 : if (n > CLOG_TEST_LEFT_TARGETS_LIMIT) n = CLOG_TEST_LEFT_TARGETS_LIMIT;
7153 1 : for (size_t i = 0; i < n; i++)
7154 1 : if (clog_test_left_targets[i] == sh) return true;
7155 : return false;
7156 : }
7157 : #else
7158 :
7159 : // Gives the exit drain budget in milliseconds, CLOG_EXIT_DRAIN_BUDGET_MS.
7160 : static inline unsigned int clog_exit_drain_budget_ms(void) {
7161 : return CLOG_EXIT_DRAIN_BUDGET_MS;
7162 : }
7163 : #endif
7164 :
7165 : // Gives the time ms milliseconds after base, for building the drain and fatal
7166 : // deadlines.
7167 121 : static struct timespec clog_ts_after_ms(const struct timespec *base,
7168 : unsigned int ms) {
7169 121 : struct timespec t = *base;
7170 121 : t.tv_sec += (time_t)(ms / 1000U);
7171 121 : t.tv_nsec += (long)(ms % 1000U) * 1000000L;
7172 4 : if (t.tv_nsec >= 1000000000L) {
7173 2 : t.tv_sec++;
7174 2 : t.tv_nsec -= 1000000000L;
7175 : }
7176 121 : return t;
7177 : }
7178 :
7179 : // Gives the time from now until the monotonic deadline, clamped at zero, for a
7180 : // timed condition wait of a drain.
7181 154 : static struct timespec clog_ts_until(const struct timespec *deadline) {
7182 154 : struct timespec now, r = {0, 0};
7183 154 : clock_gettime(CLOCK_MONOTONIC, &now);
7184 154 : if (now.tv_sec > deadline->tv_sec ||
7185 27 : (now.tv_sec == deadline->tv_sec && now.tv_nsec >= deadline->tv_nsec))
7186 4 : return r;
7187 150 : r.tv_sec = deadline->tv_sec - now.tv_sec;
7188 150 : r.tv_nsec = deadline->tv_nsec - now.tv_nsec;
7189 150 : if (r.tv_nsec < 0) {
7190 127 : r.tv_sec--;
7191 127 : r.tv_nsec += 1000000000L;
7192 : }
7193 150 : return r;
7194 : }
7195 :
7196 : // Gives the microseconds until the monotonic deadline, rounded up, or 0 once it
7197 : // passed; the timeout of a drain's queue send or receive.
7198 21 : static uint64_t clog_us_until(const struct timespec *deadline) {
7199 21 : struct timespec left = clog_ts_until(deadline);
7200 21 : return (uint64_t)left.tv_sec * UINT64_C(1000000) +
7201 21 : ((uint64_t)left.tv_nsec + 999u) / 1000u;
7202 : }
7203 :
7204 : // Converts a monotonic deadline to the CLOCK_REALTIME time that POSIX timed
7205 : // locks expect. The drain calls it right before each lock, so the time left
7206 : // stays right.
7207 133 : static struct timespec clog_realtime_at(const struct timespec *deadline) {
7208 133 : struct timespec left = clog_ts_until(deadline);
7209 133 : struct timespec at;
7210 133 : clock_gettime(CLOCK_REALTIME, &at);
7211 133 : at.tv_sec += left.tv_sec;
7212 133 : at.tv_nsec += left.tv_nsec;
7213 133 : if (at.tv_nsec >= 1000000000L) {
7214 108 : at.tv_sec++;
7215 108 : at.tv_nsec -= 1000000000L;
7216 : }
7217 133 : return at;
7218 : }
7219 :
7220 : // Locks sh->mutex within the deadline, so a drain, and the paths that run after
7221 : // one, never wait for ever on a stuck target. A free lock is taken even after
7222 : // the deadline. Returns whether it locked.
7223 75 : static bool clog_exit_lock_target(clog_shared *sh,
7224 : const struct timespec *deadline) {
7225 51 : struct timespec at = clog_realtime_at(deadline);
7226 75 : return ccol__mutex_timedlock(sh->mutex, at) == 0;
7227 : }
7228 :
7229 : // How long a CLOG_FATAL call keeps waiting for its target's mutex past the
7230 : // deadline. The writer steps aside while the call waits, so a holder making
7231 : // progress hands the mutex over well within this time.
7232 : #define CLOG_FATAL_LOCK_GRACE_MS 100U
7233 :
7234 : // Takes sh->mutex for a CLOG_FATAL record within the deadline, or at least
7235 : // CLOG_FATAL_LOCK_GRACE_MS from now. A drain can use up the whole budget, and a
7236 : // single try at the deadline would lose the record to a busy writer thread.
7237 : // Returns whether it locked.
7238 20 : static bool clog_fatal_lock_target(clog_shared *sh,
7239 : const struct timespec *deadline) {
7240 20 : struct timespec now;
7241 20 : clock_gettime(CLOCK_MONOTONIC, &now);
7242 20 : struct timespec grace = clog_ts_after_ms(&now, CLOG_FATAL_LOCK_GRACE_MS);
7243 40 : const struct timespec *until =
7244 2 : (deadline->tv_sec > grace.tv_sec ||
7245 2 : (deadline->tv_sec == grace.tv_sec && deadline->tv_nsec > grace.tv_nsec))
7246 : ? deadline
7247 20 : : &grace;
7248 20 : atomic_fetch_add(&sh->fatal_waiters, 1u);
7249 20 : bool locked = clog_exit_lock_target(sh, until);
7250 20 : atomic_fetch_sub(&sh->fatal_waiters, 1u);
7251 20 : return locked;
7252 : }
7253 :
7254 : // The exit drain's flush request, on the heap because a request the budget
7255 : // gives up on stays in the queue and the writer answers it later.
7256 : typedef struct {
7257 : clog_async_ctrl ctrl;
7258 : clog_async_msg envelope;
7259 : } clog_exit_flush;
7260 :
7261 : // Outcome of clog_owner_flush(): Answered, sent but not answered, not sent
7262 : // (queue full or refused), or no memory for the request.
7263 : typedef enum {
7264 : CLOG_OWNER_FLUSH_DONE,
7265 : CLOG_OWNER_FLUSH_PENDING,
7266 : CLOG_OWNER_FLUSH_NOT_SENT,
7267 : CLOG_OWNER_FLUSH_NO_MEMORY
7268 : } clog_owner_flush_result;
7269 :
7270 : // Puts a flush request behind everything in sh's queue through the owner send
7271 : // (which works with sends off) and waits until the deadline for the writer to
7272 : // answer; used by the drains. The request comes from the target's allocator and
7273 : // is left to the writer thread if it answers late. Returns the outcome.
7274 59 : static clog_owner_flush_result clog_owner_flush(
7275 : clog_shared *sh, const struct timespec *deadline) {
7276 59 : clog_exit_flush *req = ccol__mem_alloc(sh->m_procs, sizeof(*req));
7277 59 : if (!req) return CLOG_OWNER_FLUSH_NO_MEMORY;
7278 59 : ccol__cond_var_attr ca;
7279 59 : bool ready = false;
7280 59 : if (ccol__mutex_init(req->ctrl.mutex) == 0) {
7281 59 : if (ccol__cond_var_attr_init(ca) == 0) {
7282 118 : ready = ccol__cond_var_attr_setclock(ca, CLOCK_MONOTONIC) == 0 &&
7283 59 : ccol__cond_var_init_ca(req->ctrl.cv, ca) == 0;
7284 59 : ccol__cond_var_attr_destroy(ca);
7285 : }
7286 59 : if (!ready) ccol__mutex_destroy(req->ctrl.mutex);
7287 : }
7288 0 : if (!ready) {
7289 0 : ccol__mem_free(sh->m_procs, req);
7290 0 : return CLOG_OWNER_FLUSH_NO_MEMORY;
7291 : }
7292 59 : req->ctrl.done = false;
7293 59 : req->envelope.kind = CLOG_ASYNC_MSG_FLUSH;
7294 59 : req->envelope.u.ctrl = &req->ctrl;
7295 59 : cmessage m = {.data = &req->envelope, .size = sizeof(req->envelope)};
7296 59 : ccol_retval rv;
7297 59 : if (sh->is_bounded_queue) {
7298 21 : uint64_t left_us = clog_us_until(deadline);
7299 : #ifdef RUNNING_UNIT_TESTS
7300 21 : if (atomic_load(&clog_test_exit_drain_send_no_wait)) left_us = 0;
7301 : #endif
7302 21 : rv = ccircq_owner_send(sh->q.circq, &m, left_us);
7303 : } else {
7304 38 : rv = cdynmq_owner_send(sh->q.dynmq, &m);
7305 : }
7306 59 : bool done = false;
7307 59 : if (rv == ccol_success) {
7308 58 : ccol__mutex_lock(req->ctrl.mutex);
7309 116 : while (!req->ctrl.done &&
7310 58 : ccol__cond_var_timedwait(req->ctrl.cv, req->ctrl.mutex, *deadline) ==
7311 : 0) {
7312 97 : }
7313 58 : done = req->ctrl.done;
7314 58 : ccol__mutex_unlock(req->ctrl.mutex);
7315 57 : if (!done) return CLOG_OWNER_FLUSH_PENDING;
7316 : }
7317 40 : ccol__mutex_destroy(req->ctrl.mutex);
7318 40 : ccol__cond_var_destroy(req->ctrl.cv);
7319 40 : ccol__mem_free(sh->m_procs, req);
7320 40 : return done ? CLOG_OWNER_FLUSH_DONE : CLOG_OWNER_FLUSH_NOT_SENT;
7321 : }
7322 :
7323 : // Drains async target sh within the deadline, for the exit drain and the fatal
7324 : // path: It turns sends off first, then puts the flush request in through the
7325 : // owner send, so every accepted record is ahead of it and later records take
7326 : // the synchronous fallback. Then it settles the batch and pays an owed repair
7327 : // under the mutex. When the writer doesn't answer, the queue stays full or the
7328 : // mutex doesn't come, it sets drain_left (an unbounded queue gets its sends
7329 : // back, a bounded one stays closed) and returns false. The caller keeps sh
7330 : // alive (table lock or a pin).
7331 40 : static bool clog_exit_drain_async(clog_shared *sh,
7332 : const struct timespec *deadline) {
7333 40 : atomic_store_explicit(
7334 : &sh->drain_deadline_ns,
7335 : (uint64_t)deadline->tv_sec * 1000000000ull + (uint64_t)deadline->tv_nsec,
7336 : memory_order_relaxed);
7337 40 : if (sh->is_bounded_queue)
7338 12 : (void)ccircq_disable_sending(sh->q.circq);
7339 : else
7340 28 : (void)cdynmq_disable_sending(sh->q.dynmq);
7341 40 : clog_owner_flush_result r = clog_owner_flush(sh, deadline);
7342 40 : if (r == CLOG_OWNER_FLUSH_NO_MEMORY) return true;
7343 68 : if (r != CLOG_OWNER_FLUSH_DONE || !clog_exit_lock_target(sh, deadline)) {
7344 12 : atomic_store_explicit(&sh->drain_left, true, memory_order_release);
7345 12 : if (!sh->is_bounded_queue) (void)cdynmq_enable_sending(sh->q.dynmq);
7346 12 : return false;
7347 : }
7348 28 : int left = clog_ms_until(deadline);
7349 28 : int wait_ms = left < CLOG_SPLIT_RECORD_DRAIN_WAIT_MS
7350 : ? left
7351 : : CLOG_SPLIT_RECORD_DRAIN_WAIT_MS;
7352 28 : clog_settle_batch_locked(sh, wait_ms);
7353 28 : if (sh->async_partial_record & CLOG_OWED_REPAIR)
7354 5 : (void)clog_pay_owed(sh, sh->format, wait_ms);
7355 28 : ccol__mutex_unlock(sh->mutex);
7356 28 : return true;
7357 : }
7358 :
7359 : // Gives the deadline of a thread whose send a drain refused: The drain's own
7360 : // deadline, and at least CLOG_SPLIT_RECORD_DRAIN_WAIT_MS from now, so a record
7361 : // logged after a drain (from a destructor) still gets written.
7362 38 : static struct timespec clog_after_drain_deadline(clog_shared *sh) {
7363 38 : uint64_t ns =
7364 38 : atomic_load_explicit(&sh->drain_deadline_ns, memory_order_relaxed);
7365 38 : struct timespec deadline = {(time_t)(ns / 1000000000ull),
7366 38 : (long)(ns % 1000000000ull)};
7367 38 : struct timespec now;
7368 38 : clock_gettime(CLOCK_MONOTONIC, &now);
7369 38 : struct timespec floor_at =
7370 38 : clog_ts_after_ms(&now, CLOG_SPLIT_RECORD_DRAIN_WAIT_MS);
7371 38 : if (floor_at.tv_sec > deadline.tv_sec ||
7372 8 : (floor_at.tv_sec == deadline.tv_sec &&
7373 : floor_at.tv_nsec > deadline.tv_nsec))
7374 38 : deadline = floor_at;
7375 38 : return deadline;
7376 : }
7377 :
7378 : // Waits, bounded by clog_after_drain_deadline(), for the records sh's queue
7379 : // accepted before a drain turned sends off, so a direct write after a refused
7380 : // send doesn't land ahead of them.
7381 19 : static void clog_flush_after_drain(clog_shared *sh) {
7382 19 : struct timespec deadline = clog_after_drain_deadline(sh);
7383 19 : (void)clog_owner_flush(sh, &deadline);
7384 19 : }
7385 :
7386 : // Waits within the deadline for sh's compressor to finish every queued and
7387 : // running job; at the deadline it drops the queued jobs and aborts the running
7388 : // one. A mutex held past the deadline leaves them all to the thread. Needs the
7389 : // table's write lock.
7390 4 : static void clog_exit_drain_compressions(clog_shared *sh,
7391 : const struct timespec *deadline) {
7392 8 : if (!clog_exit_lock_target(sh, deadline)) return;
7393 3 : if (sh->compressor_live) {
7394 7 : while ((sh->compress_head || sh->compress_running) &&
7395 3 : ccol__cond_var_timedwait(sh->compress_cv, sh->mutex, *deadline) ==
7396 : 0) {
7397 5 : }
7398 3 : if (sh->compress_head || sh->compress_running) {
7399 : clog_compress_job *j = sh->compress_head;
7400 1 : while (j) {
7401 0 : clog_compress_job *next = j->next;
7402 0 : ccol__mem_free(sh->m_procs, j);
7403 : j = next;
7404 : }
7405 1 : sh->compress_head = NULL;
7406 1 : sh->compress_tail = NULL;
7407 1 : atomic_store(&sh->compress_abort, true);
7408 1 : struct timespec grace =
7409 1 : clog_ts_after_ms(deadline, CLOG_EXIT_ABANDON_GRACE_MS);
7410 2 : while (sh->compress_running &&
7411 1 : ccol__cond_var_timedwait(sh->compress_cv, sh->mutex, grace) == 0) {
7412 2 : }
7413 : }
7414 : }
7415 3 : ccol__mutex_unlock(sh->mutex);
7416 : }
7417 :
7418 : // The exit handler: Drains every async target and then its compressions within
7419 : // one budget (the fatal deadline after a CLOG_FATAL call), and pays owed
7420 : // repairs with a try-lock only. It walks live_shareds under the table's write
7421 : // lock (taken for writing because a fork child re-initialized it), and skips
7422 : // the target whose own thread called exit() or a drain already left. Sends stay
7423 : // off afterwards, so later records are written synchronously. Does nothing
7424 : // unless a writer or compressor thread started or a debt was left.
7425 98 : static void clog_exit_drain(void) {
7426 98 : if (!atomic_load_explicit(&clog_exit_drain_armed, memory_order_relaxed))
7427 41 : return;
7428 58 : ccol__call_once(clog_slot_table.once, clog_slot_table_init_globals);
7429 58 : struct timespec start;
7430 58 : clock_gettime(CLOCK_MONOTONIC, &start);
7431 20 : struct timespec deadline =
7432 58 : atomic_load_explicit(&clog_fatal_bound_armed, memory_order_acquire)
7433 : ? clog_fatal_deadline
7434 98 : : clog_ts_after_ms(&start, clog_exit_drain_budget_ms());
7435 58 : struct timespec table_at = clog_realtime_at(&deadline);
7436 58 : if (ccol__rw_lock_timedwrlock(clog_slot_table.rwlock, table_at) != 0) return;
7437 57 : if (clog_slot_table.live_shareds) {
7438 57 : size_t n = cvector_size(clog_slot_table.live_shareds);
7439 192 : for (size_t i = 0; i < n; i++) {
7440 270 : clog_shared *sh =
7441 135 : *(clog_shared **)cvector_at(clog_slot_table.live_shareds, i);
7442 135 : if (sh == clog_thread_serves) continue;
7443 133 : if (sh->async_enabled) {
7444 34 : if (!clog_exit_drain_async(sh, &deadline)) {
7445 : #ifdef RUNNING_UNIT_TESTS
7446 10 : clog_test_note_left_target(sh);
7447 : #endif
7448 10 : continue;
7449 : }
7450 : }
7451 123 : if (sh->rotation_enabled && sh->rotation.compress_rotated)
7452 4 : clog_exit_drain_compressions(sh, &deadline);
7453 134 : if (atomic_load_explicit(&sh->owes_repair, memory_order_relaxed) &&
7454 11 : ccol__mutex_trylock(sh->mutex) == 0) {
7455 10 : int left = clog_ms_until(&deadline);
7456 10 : (void)clog_pay_owed(sh, sh->format,
7457 : left < CLOG_SPLIT_RECORD_DRAIN_WAIT_MS
7458 : ? left
7459 : : CLOG_SPLIT_RECORD_DRAIN_WAIT_MS);
7460 10 : ccol__mutex_unlock(sh->mutex);
7461 : }
7462 : }
7463 : }
7464 57 : ccol__rw_lock_unlock(clog_slot_table.rwlock);
7465 : }
7466 :
7467 : #ifdef RUNNING_UNIT_TESTS
7468 :
7469 : // Runs the exit drain now, so a test can check it without ending the process.
7470 5 : void clog__test_run_exit_drain(void) { clog_exit_drain(); }
7471 : #endif
7472 :
7473 : // Registers the exit drain with atexit() at load, so it runs after every exit
7474 : // handler the application registers later and drains what those log.
7475 14 : __attribute__((constructor)) static void clog_register_exit_drain(void) {
7476 14 : clog_exit_drain_registered = atexit(clog_exit_drain) == 0;
7477 14 : }
7478 :
7479 : // Arms the deadline of the stop once, at the first CLOG_FATAL call.
7480 : static ccol__once_flag clog_fatal_once = CCOL__ONCE_INIT;
7481 :
7482 : // Fixes the deadline of the whole stop (now plus the drain budget) and arms the
7483 : // bounded writes, once, when the first CLOG_FATAL call starts.
7484 20 : static void clog_fatal_arm(void) {
7485 20 : struct timespec now;
7486 20 : clock_gettime(CLOCK_MONOTONIC, &now);
7487 34 : clog_fatal_deadline = clog_ts_after_ms(&now, clog_exit_drain_budget_ms());
7488 20 : atomic_store_explicit(&clog_fatal_bound_armed, true, memory_order_release);
7489 20 : }
7490 :
7491 : // Says on stderr, with a bounded write, that a CLOG_FATAL record couldn't be
7492 : // written, unless stderr is the same output. It reads fd without the lock,
7493 : // since a stuck thread may hold it.
7494 6 : static void clog_fatal_report_loss(clog_shared *sh) {
7495 6 : static const char msg[] =
7496 : "clogger: a CLOG_FATAL record could not be written to its log output "
7497 : "in time; the process stops without it\n";
7498 6 : int fd = __atomic_load_n(&sh->fd, __ATOMIC_RELAXED);
7499 6 : struct stat out, err;
7500 6 : if (fstat(STDERR_FILENO, &err) != 0) return;
7501 6 : if (fd >= 0 && fstat(fd, &out) == 0 && out.st_dev == err.st_dev &&
7502 1 : out.st_ino == err.st_ino)
7503 : return;
7504 6 : struct pollfd pfd = {.fd = STDERR_FILENO,
7505 : .events = clog_pollout_events(STDERR_FILENO),
7506 : .revents = 0};
7507 6 : if (poll(&pfd, 1, CLOG_SPLIT_RECORD_DRAIN_WAIT_MS) > 0 &&
7508 6 : (pfd.revents & POLLOUT)) {
7509 6 : ssize_t w = write(STDERR_FILENO, msg, sizeof(msg) - 1);
7510 6 : (void)w;
7511 : }
7512 : }
7513 :
7514 : // Writes a CLOG_FATAL record and stops the process; it never returns. One
7515 : // deadline, the drain budget from the first fatal call, bounds the whole stop:
7516 : // writes to sinks that aren't regular files, every wait, and the mutex wait
7517 : // (plus its grace). An async target is drained first so earlier records reach
7518 : // the log. A record that can't go out is reported on stderr and the process
7519 : // stops anyway. lg is pinned; it's unpinned before exit.
7520 : static __attribute__((noinline, cold, noreturn, format(printf, 8, 0))) void
7521 20 : clog_write_fatal(struct clogger *lg, const char *file, int line,
7522 : const char *func, bool with_backtrace, char **bt_syms,
7523 : int bt_depth, const char *fmt, va_list ap) {
7524 20 : ccol__call_once(clog_fatal_once, clog_fatal_arm);
7525 20 : clog_shared *sh = lg->shared;
7526 20 : if (sh->async_enabled) (void)clog_exit_drain_async(sh, &clog_fatal_deadline);
7527 20 : va_list ap2;
7528 20 : va_copy(ap2, ap);
7529 20 : bool delivered = clog_write_sync_body(lg, CLOG_FATAL, file, line, func,
7530 : with_backtrace, bt_syms, bt_depth, fmt,
7531 : ap, ap2, true, &clog_fatal_deadline);
7532 20 : va_end(ap2);
7533 20 : if (!delivered) clog_fatal_report_loss(sh);
7534 20 : if (bt_syms) free(bt_syms);
7535 20 : clog_resolve_unpin(lg);
7536 20 : clog_fatal_exit();
7537 : }
7538 :
7539 : // The function behind every clog_<level>() macro: Checks the level with a
7540 : // relaxed load and returns at once for a dropped record, captures the backtrace
7541 : // in this frame when asked, and sends the record down the fatal, async or
7542 : // synchronous path. async_enabled is read without a lock, since it's written
7543 : // once before any reader exists. A message queued just before a concurrent
7544 : // level change is still delivered, as clog_set_level(3) says.
7545 44633 : void clog__write(clog h, clog_level level, const char *file, int line,
7546 : const char *func, bool with_backtrace, const char *fmt, ...) {
7547 44633 : struct clogger *lg = clog_resolve(h);
7548 44621 : if (!lg)
7549 1 : ccol__fatal_err(
7550 : "clog__write: clog handle is invalid, stale, or already closed");
7551 :
7552 44620 : if (level < atomic_load_explicit(&lg->min_level, memory_order_relaxed) &&
7553 : level != CLOG_FATAL) {
7554 2977 : clog_resolve_unpin(lg);
7555 32440 : return;
7556 : }
7557 :
7558 41643 : char **bt_syms = NULL;
7559 41643 : int bt_depth = 0;
7560 41643 : if (with_backtrace) capture_backtrace(&bt_syms, &bt_depth);
7561 :
7562 41643 : va_list ap;
7563 41643 : va_start(ap, fmt);
7564 :
7565 41643 : if (__builtin_expect(level == CLOG_FATAL, 0))
7566 20 : clog_write_fatal(lg, file, line, func, with_backtrace, bt_syms, bt_depth,
7567 : fmt, ap);
7568 :
7569 41623 : if (lg->shared->async_enabled) {
7570 26468 : clog_write_async(lg, level, file, line, func, with_backtrace, bt_syms,
7571 : bt_depth, fmt, ap);
7572 26483 : va_end(ap);
7573 26483 : clog_resolve_unpin(lg);
7574 26483 : return;
7575 : }
7576 :
7577 15155 : clog_write_sync(lg, level, file, line, func, with_backtrace, bt_syms,
7578 : bt_depth, fmt, ap);
7579 15157 : va_end(ap);
7580 15157 : if (bt_syms) free(bt_syms);
7581 15157 : clog_resolve_unpin(lg);
7582 : }
|