Skip to main content

tuwunel_core/log/
journald.rs

1//! Native systemd journal submission and field recording.
2//!
3//! The module routes formatted messages to the journal socket and records
4//! structured tracing fields for journal queries.
5
6#[cfg(unix)]
7use std::os::unix::net::UnixDatagram;
8use std::{
9	cell::RefCell,
10	env::args_os,
11	ffi::OsStr,
12	fmt::Debug,
13	io::{self, Write, stderr},
14	path::Path,
15};
16
17use tracing::{
18	Event, Level, Metadata, Subscriber,
19	field::{Field, Visit},
20	level_filters::LevelFilter,
21	span::{Attributes, Id, Record},
22	subscriber::Interest,
23};
24use tracing_subscriber::{
25	layer::{Context, Layer},
26	registry::LookupSpan,
27};
28
29#[cfg(not(unix))]
30use self::unsupported::UnixDatagram;
31use super::is_systemd_mode;
32use crate::{
33	Config, Result,
34	arrayvec::ArrayString,
35	err, format_small_string, implement,
36	smallstr::SmallString,
37	smallvec::SmallVec,
38	utils::{
39		math::{ExpectInto, Expected},
40		string::{Unquote, to_array_string},
41	},
42};
43
44#[cfg(test)]
45mod tests;
46
47/// Stand-in for the journald socket on targets outside the unix family.
48///
49/// Nothing constructs it, since `enabled()` is always false without systemd.
50#[cfg(not(unix))]
51mod unsupported {
52	use std::io;
53
54	use super::implement;
55
56	pub(super) struct UnixDatagram;
57
58	#[implement(UnixDatagram)]
59	pub(super) fn unbound() -> io::Result<Self> { Err(unavailable()) }
60
61	#[implement(UnixDatagram)]
62	#[expect(clippy::unused_self)]
63	pub(super) fn send_to(&self, _payload: &[u8], _path: &str) -> io::Result<usize> {
64		Err(unavailable())
65	}
66
67	fn unavailable() -> io::Error {
68		io::Error::new(io::ErrorKind::Unsupported, "journald requires unix datagram sockets")
69	}
70}
71
72/// Encoded journal fields; a longer run spills to the heap.
73type Buffer = SmallVec<[u8; 128]>;
74
75/// Syslog identifier tagging every entry.
76type Identifier = SmallString<[u8; 16]>;
77
78/// Formatted source line number.
79type CodeLine = ArrayString<10>;
80
81/// Journal name of a user field, including the prefix.
82type FieldName = SmallString<[u8; 32]>;
83
84/// Value of a user field recorded through its `Debug` implementation.
85type FieldValue = SmallString<[u8; 64]>;
86
87const SOCKET: &str = "/run/systemd/journal/socket";
88
89const IDENTIFIER: &str = "tuwunel";
90
91/// Keeps a user field from colliding with one of the journal's own.
92const PREFIX: &str = "F_";
93
94/// Journald rejects a longer field name.
95const NAME_MAX: usize = 64;
96
97/// Bounds the datagram well under the default socket send buffer.
98const PAYLOAD_MAX: usize = 128 * 1024;
99
100const LEN_PREFIX: usize = size_of::<u64>();
101
102/// Datagram connection to the journald submission socket.
103pub struct Journal {
104	socket: UnixDatagram,
105	identifier: Identifier,
106}
107
108/// One entry, submitted when the writer is dropped. Its payload accumulates
109/// in the thread's buffer, which the fields layer opened for this event.
110pub struct Entry<'a> {
111	journal: &'a Journal,
112	message: usize,
113}
114
115/// Records the fields of each event and span for the entry the wrapped
116/// console layer is about to write, leaving them queryable with
117/// `journalctl F_NAME=value`.
118pub struct Fields<L> {
119	inner: L,
120	submit: bool,
121}
122
123/// Encoded fields of one span, held in its registry extensions.
124struct SpanFields(Buffer);
125
126struct Visitor<'a> {
127	fields: &'a mut Buffer,
128}
129
130thread_local! {
131	/// Entry under construction on this thread, reused across events.
132	static PAYLOAD: RefCell<Buffer> = const { RefCell::new(Buffer::new_const()) };
133}
134
135impl Journal {
136	/// Opens the socket when journald is configured, keeping the console when
137	/// nothing is listening on it.
138	#[must_use]
139	pub fn open(config: &Config) -> Option<Self> {
140		enabled(config)
141			.then(Self::new)?
142			.inspect_err(|e| {
143				writeln!(stderr(), "{e}").ok();
144			})
145			.ok()
146	}
147
148	fn new() -> Result<Self> {
149		let journal = Self {
150			socket: UnixDatagram::unbound()?,
151			identifier: identifier(),
152		};
153
154		journal
155			.send(&[])
156			.map_err(|e| err!(Config("logging.journald", "{SOCKET}: {e}.")))?;
157
158		Ok(journal)
159	}
160}
161
162/// Tags entries with the running executable's name.
163fn identifier() -> Identifier {
164	args_os()
165		.next()
166		.as_deref()
167		.map(Path::new)
168		.and_then(Path::file_name)
169		.and_then(OsStr::to_str)
170		.map_or_else(|| IDENTIFIER.into(), Into::into)
171}
172
173/// Opens an entry at the event's severity, carrying its source metadata after
174/// the fields recorded for it, and leaves the message field open.
175#[implement(Journal)]
176#[must_use]
177pub fn entry(&self, meta: &Metadata<'_>) -> Entry<'_> {
178	let message = PAYLOAD.with_borrow_mut(|payload| {
179		put(payload, "PRIORITY", &[priority(*meta.level())]);
180		put(payload, "SYSLOG_IDENTIFIER", self.identifier.as_bytes());
181		put(payload, "TARGET", meta.target().as_bytes());
182
183		if let Some(file) = meta.file() {
184			put(payload, "CODE_FILE", file.as_bytes());
185		}
186
187		if let Some(line) = meta.line() {
188			let line: CodeLine = to_array_string(line);
189
190			put(payload, "CODE_LINE", line.as_bytes());
191		}
192
193		payload.extend_from_slice(b"MESSAGE\n");
194		payload.extend_from_slice(&[0; LEN_PREFIX]);
195
196		payload.len()
197	});
198
199	Entry { journal: self, message }
200}
201
202#[implement(Journal)]
203fn send(&self, payload: &[u8]) -> io::Result<usize> { self.socket.send_to(payload, SOCKET) }
204
205impl Write for Entry<'_> {
206	fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
207		PAYLOAD.with_borrow_mut(|payload| payload.extend_from_slice(buf));
208
209		Ok(buf.len())
210	}
211
212	fn flush(&mut self) -> io::Result<()> { Ok(()) }
213}
214
215impl Drop for Entry<'_> {
216	fn drop(&mut self) {
217		PAYLOAD.with_borrow_mut(|payload| {
218			close(payload, self.message);
219
220			if self.journal.send(payload).is_err() {
221				fallback(&payload[self.message..]);
222			}
223
224			// A span event reaches the writer without passing the fields layer,
225			// so the buffer is released here rather than after recording.
226			payload.clear();
227		});
228	}
229}
230
231/// Writes a message the socket would not take to the console, which journald
232/// captures in turn under systemd.
233fn fallback(message: &[u8]) { stderr().write_all(message).ok(); }
234
235/// Seals the message field, trimming the formatter's trailing whitespace and
236/// truncating on a character boundary what the datagram cannot carry.
237#[expect(
238	clippy::little_endian_bytes,
239	reason = "the journal protocol specifies little-endian field lengths"
240)]
241fn close(payload: &mut Buffer, message: usize) {
242	let budget = PAYLOAD_MAX.saturating_sub(message);
243	let len = payload[message..].trim_ascii_end().len();
244	let len = (len > budget)
245		.then(|| boundary(&payload[message..], budget))
246		.unwrap_or(len);
247
248	let size: u64 = len.expect_into();
249
250	payload.truncate(message.expected_add(len));
251	payload[message.expected_sub(LEN_PREFIX)..message].copy_from_slice(&size.to_le_bytes());
252	payload.push(b'\n');
253}
254
255/// Steps back to the nearest character boundary at or below `len`; a
256/// continuation byte never begins a character.
257fn boundary(message: &[u8], len: usize) -> usize {
258	(0..=len)
259		.rev()
260		.find(|&i| {
261			message
262				.get(i)
263				.is_none_or(|byte| byte & 0b1100_0000 != 0b1000_0000)
264		})
265		.unwrap_or_default()
266}
267
268impl<L> Fields<L> {
269	/// Wraps a subscriber layer with optional native journal field recording.
270	///
271	/// Events always continue through the inner layer. Structured field
272	/// submission is enabled only when the supplied configuration selects the
273	/// journal.
274	pub fn new(inner: L, config: &Config) -> Self { Self { inner, submit: enabled(config) } }
275}
276
277/// Reports whether events are submitted directly to journald.
278///
279/// Requires `logging.journald` and systemd mode. Console output is otherwise
280/// captured by journald at a single fixed priority.
281pub(super) fn enabled(config: &Config) -> bool { config.logging.journald && is_systemd_mode() }
282
283impl<S, L> Layer<S> for Fields<L>
284where
285	S: Subscriber + for<'a> LookupSpan<'a>,
286	L: Layer<S>,
287{
288	#[inline]
289	fn on_layer(&mut self, subscriber: &mut S) { self.inner.on_layer(subscriber); }
290
291	#[inline]
292	fn register_callsite(&self, meta: &'static Metadata<'static>) -> Interest {
293		self.inner.register_callsite(meta)
294	}
295
296	#[inline]
297	fn enabled(&self, meta: &Metadata<'_>, ctx: Context<'_, S>) -> bool {
298		self.inner.enabled(meta, ctx)
299	}
300
301	#[inline]
302	fn max_level_hint(&self) -> Option<LevelFilter> { self.inner.max_level_hint() }
303
304	fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
305		if self.submit {
306			record_span(attrs, id, &ctx);
307		}
308
309		self.inner.on_new_span(attrs, id, ctx);
310	}
311
312	fn on_record(&self, id: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
313		if self.submit {
314			record_values(id, values, &ctx);
315		}
316
317		self.inner.on_record(id, values, ctx);
318	}
319
320	#[inline]
321	fn on_follows_from(&self, id: &Id, follows: &Id, ctx: Context<'_, S>) {
322		self.inner.on_follows_from(id, follows, ctx);
323	}
324
325	#[inline]
326	fn event_enabled(&self, event: &Event<'_>, ctx: Context<'_, S>) -> bool {
327		self.inner.event_enabled(event, ctx)
328	}
329
330	fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
331		if self.submit {
332			record_event(event, &ctx);
333		}
334
335		self.inner.on_event(event, ctx);
336	}
337
338	#[inline]
339	fn on_enter(&self, id: &Id, ctx: Context<'_, S>) { self.inner.on_enter(id, ctx); }
340
341	#[inline]
342	fn on_exit(&self, id: &Id, ctx: Context<'_, S>) { self.inner.on_exit(id, ctx); }
343
344	#[inline]
345	fn on_close(&self, id: Id, ctx: Context<'_, S>) { self.inner.on_close(id, ctx); }
346
347	#[inline]
348	fn on_id_change(&self, old: &Id, new: &Id, ctx: Context<'_, S>) {
349		self.inner.on_id_change(old, new, ctx);
350	}
351}
352
353/// Encodes a span's fields once, for every event it later encloses.
354fn record_span<S>(attrs: &Attributes<'_>, id: &Id, ctx: &Context<'_, S>)
355where
356	S: Subscriber + for<'a> LookupSpan<'a>,
357{
358	let Some(span) = ctx.span(id) else {
359		return;
360	};
361
362	let mut fields = Buffer::new();
363
364	put(&mut fields, "SPAN_NAME", span.name().as_bytes());
365	attrs.record(&mut Visitor { fields: &mut fields });
366
367	span.extensions_mut().insert(SpanFields(fields));
368}
369
370/// Appends the fields of a span recorded after its creation.
371fn record_values<S>(id: &Id, values: &Record<'_>, ctx: &Context<'_, S>)
372where
373	S: Subscriber + for<'a> LookupSpan<'a>,
374{
375	let Some(span) = ctx.span(id) else {
376		return;
377	};
378
379	let mut extensions = span.extensions_mut();
380	let Some(SpanFields(fields)) = extensions.get_mut::<SpanFields>() else {
381		return;
382	};
383
384	values.record(&mut Visitor { fields });
385}
386
387/// Opens this thread's buffer with the event's fields and those of the spans
388/// enclosing it, for the entry the console writer appends to next.
389fn record_event<S>(event: &Event<'_>, ctx: &Context<'_, S>)
390where
391	S: Subscriber + for<'a> LookupSpan<'a>,
392{
393	PAYLOAD.with_borrow_mut(|payload| {
394		payload.clear();
395
396		extend_scope(payload, event, ctx);
397		event.record(&mut Visitor { fields: payload });
398	});
399}
400
401/// Appends the fields of every span enclosing the event, innermost first.
402fn extend_scope<S>(payload: &mut Buffer, event: &Event<'_>, ctx: &Context<'_, S>)
403where
404	S: Subscriber + for<'a> LookupSpan<'a>,
405{
406	ctx.event_scope(event)
407		.into_iter()
408		.flatten()
409		.for_each(|span| {
410			let extensions = span.extensions();
411
412			if let Some(SpanFields(fields)) = extensions.get::<SpanFields>() {
413				payload.extend_from_slice(fields);
414			}
415		});
416}
417
418impl Visit for Visitor<'_> {
419	fn record_str(&mut self, field: &Field, value: &str) { self.record(field, value.as_bytes()); }
420
421	fn record_debug(&mut self, field: &Field, value: &dyn Debug) {
422		let value: FieldValue = format_small_string!("{value:?}");
423
424		self.record(field, value.as_str().unquote_infallible().as_bytes());
425	}
426}
427
428/// The message is the entry's own `MESSAGE`, and an underscored name marks a
429/// field the console formatter also hides.
430#[implement(Visitor, params = "<'_>")]
431fn record(&mut self, field: &Field, value: &[u8]) {
432	let name = field.name();
433	let skip = name == "message" || name.starts_with('_') || self.fields.len() >= PAYLOAD_MAX;
434
435	if skip {
436		return;
437	}
438
439	put(self.fields, &sanitize(name), value);
440}
441
442/// Journald accepts only uppercase alphanumerics and underscores in a field
443/// name, and drops a field whose name it rejects.
444fn sanitize(name: &str) -> FieldName {
445	PREFIX
446		.chars()
447		.chain(
448			name.chars()
449				.map(|c| if matches!(c, '.' | '-') { '_' } else { c })
450				.filter(|c| *c == '_' || c.is_ascii_alphanumeric())
451				.map(|c| c.to_ascii_uppercase()),
452		)
453		.take(NAME_MAX)
454		.collect()
455}
456
457/// Appends a length-encoded field, which may carry any byte sequence.
458#[expect(
459	clippy::little_endian_bytes,
460	reason = "the journal protocol specifies little-endian field lengths"
461)]
462fn put(payload: &mut Buffer, name: &str, value: &[u8]) {
463	let len: u64 = value.len().expect_into();
464
465	payload.extend_from_slice(name.as_bytes());
466	payload.push(b'\n');
467	payload.extend_from_slice(&len.to_le_bytes());
468	payload.extend_from_slice(value);
469	payload.push(b'\n');
470}
471
472/// Maps a level onto the syslog severity code journald expects.
473const fn priority(level: Level) -> u8 {
474	match level {
475		| Level::ERROR => b'3',
476		| Level::WARN => b'4',
477		| Level::INFO => b'5',
478		| Level::DEBUG => b'6',
479		| Level::TRACE => b'7',
480	}
481}