1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
use crate::errors::{Context, SdError};
use nix::fcntl::*;
use nix::sys::memfd::memfd_create;
use nix::sys::memfd::MemFdCreateFlag;
use nix::sys::socket::{sendmsg, ControlMessage, MsgFlags, UnixAddr};
use once_cell::sync::OnceCell;
use std::collections::HashMap;
use std::ffi::{CString, OsStr};
use std::fs::{File, Metadata};
use std::io::{self, Write};
use std::os::linux::fs::MetadataExt;
use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd};
use std::os::unix::net::UnixDatagram;
use std::str::FromStr;

/// Default path of the systemd-journald `AF_UNIX` datagram socket.
pub static SD_JOURNAL_SOCK_PATH: &str = "/run/systemd/journal/socket";

/// The shared socket to journald.
static SD_SOCK: OnceCell<UnixDatagram> = OnceCell::new();

/// Trait for checking the type of a file descriptor.

/// Log priority values.
///
/// See `man 3 syslog`.
#[derive(Clone, Copy, Debug)]
#[repr(u8)]
pub enum Priority {
    /// System is unusable.
    Emergency = 0,
    /// Action must be taken immediately.
    Alert,
    /// Critical condition,
    Critical,
    /// Error condition.
    Error,
    /// Warning condition.
    Warning,
    /// Normal, but significant, condition.
    Notice,
    /// Informational message.
    Info,
    /// Debug message.
    Debug,
}

impl std::convert::From<Priority> for u8 {
    fn from(p: Priority) -> Self {
        match p {
            Priority::Emergency => 0,
            Priority::Alert => 1,
            Priority::Critical => 2,
            Priority::Error => 3,
            Priority::Warning => 4,
            Priority::Notice => 5,
            Priority::Info => 6,
            Priority::Debug => 7,
        }
    }
}

impl Priority {
    fn numeric_level(&self) -> &str {
        match self {
            Priority::Emergency => "0",
            Priority::Alert => "1",
            Priority::Critical => "2",
            Priority::Error => "3",
            Priority::Warning => "4",
            Priority::Notice => "5",
            Priority::Info => "6",
            Priority::Debug => "7",
        }
    }
}

#[inline(always)]
fn is_valid_char(c: char) -> bool {
    c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_'
}

/// The variable name must be in uppercase and consist only of characters,
/// numbers and underscores, and may not begin with an underscore.
///
/// See <https://github.com/systemd/systemd/blob/ed056c560b47f84a0aa0289151f4ec91f786d24a/src/libsystemd/sd-journal/journal-file.c#L1557>
/// for the reference implementation of journal_field_valid.
fn is_valid_field(input: &str) -> bool {
    // journald doesn't allow empty fields or fields with more than 64 bytes
    if input.is_empty() || 64 < input.len() {
        return false;
    }

    // Fields starting with underscores are protected by journald
    if input.starts_with('_') {
        return false;
    }

    // Journald doesn't allow fields to start with digits
    if input.starts_with(|c: char| c.is_ascii_digit()) {
        return false;
    }

    input.chars().all(is_valid_char)
}

/// Add `field` and `payload` to journal fields `data` with explicit length encoding.
///
/// Write
///
/// 1. the field name,
/// 2. an ASCII newline,
/// 3. the payload size as LE encoded 64 bit integer,
/// 4. the payload, and
/// 5. a final ASCII newline
///
/// to `data`.
///
/// See <https://systemd.io/JOURNAL_NATIVE_PROTOCOL/> for details.
fn add_field_and_payload_explicit_length(data: &mut Vec<u8>, field: &str, payload: &str) {
    let encoded_len = (payload.len() as u64).to_le_bytes();

    // Bump the capacity to avoid multiple allocations during the extend/push calls.  The 2 is for
    // the newline characters.
    data.reserve(field.len() + encoded_len.len() + payload.len() + 2);

    data.extend(field.as_bytes());
    data.push(b'\n');
    data.extend(encoded_len);
    data.extend(payload.as_bytes());
    data.push(b'\n');
}

/// Add  a journal `field` and its `payload` to journal fields `data` with appropriate encoding.
///
/// If `payload` does not contain a newline character use the simple journal field encoding, and
/// write the field name and the payload separated by `=` and suffixed by a final new line.
///
/// Otherwise encode the payload length explicitly with [[`add_field_and_payload_explicit_length`]].
///
/// See <https://systemd.io/JOURNAL_NATIVE_PROTOCOL/> for details.
fn add_field_and_payload(data: &mut Vec<u8>, field: &str, payload: &str) {
    if is_valid_field(field) {
        if payload.contains('\n') {
            add_field_and_payload_explicit_length(data, field, payload);
        } else {
            // If payload doesn't contain an newline directly write the field name and the payload.
            // Bump the capacity to avoid multiple allocations during extend/push calls.  The 2 is
            // for the two pushed bytes.
            data.reserve(field.len() + payload.len() + 2);

            data.extend(field.as_bytes());
            data.push(b'=');
            data.extend(payload.as_bytes());
            data.push(b'\n');
        }
    }
}

/// Send a message with structured properties to the journal.
///
/// The PRIORITY or MESSAGE fields from the vars iterator are always ignored in favour of the priority and message arguments.
pub fn journal_send<K, V>(
    priority: Priority,
    msg: &str,
    vars: impl Iterator<Item = (K, V)>,
) -> Result<(), SdError>
where
    K: AsRef<str>,
    V: AsRef<str>,
{
    let sock = SD_SOCK
        .get_or_try_init(UnixDatagram::unbound)
        .context("failed to open datagram socket")?;

    let mut data = Vec::new();
    add_field_and_payload(&mut data, "PRIORITY", priority.numeric_level());
    add_field_and_payload(&mut data, "MESSAGE", msg);
    for (ref k, ref v) in vars {
        if k.as_ref() != "PRIORITY" && k.as_ref() != "MESSAGE" {
            add_field_and_payload(&mut data, k.as_ref(), v.as_ref())
        }
    }

    // Message sending logic:
    //  * fast path: data within datagram body.
    //  * slow path: data in a sealed memfd, which is sent as an FD in ancillary data.
    //
    // Maximum data size is system dependent, thus this always tries the fast path and
    // falls back to the slow path if the former fails with `EMSGSIZE`.
    match sock.send_to(&data, SD_JOURNAL_SOCK_PATH) {
        Ok(x) => Ok(x),
        // `EMSGSIZE` (errno code 90) means the message was too long for a UNIX socket,
        Err(ref err) if err.raw_os_error() == Some(90) => {
            send_memfd_payload(sock, &data).context("sending with memfd failed")
        }
        Err(e) => Err(e).context("send_to failed"),
    }
    .map(|_| ())
    .with_context(|| format!("failed to print to journal at '{}'", SD_JOURNAL_SOCK_PATH))
}

/// Print a message to the journal with the given priority.
pub fn journal_print(priority: Priority, msg: &str) -> Result<(), SdError> {
    let map: HashMap<&str, &str> = HashMap::new();
    journal_send(priority, msg, map.iter())
}

/// Send an overlarge payload to systemd-journald socket.
///
/// This is a slow-path for sending a large payload that could not otherwise fit
/// in a UNIX datagram. Payload is thus written to a memfd, which is sent as ancillary
/// data.
fn send_memfd_payload(sock: &UnixDatagram, data: &[u8]) -> Result<usize, SdError> {
    let memfd = {
        let fdname = &CString::new("libsystemd-rs-logging").context("unable to create cstring")?;
        let tmpfd = memfd_create(fdname, MemFdCreateFlag::MFD_ALLOW_SEALING)
            .context("unable to create memfd")?;

        // SAFETY: `memfd_create` just returned this FD.
        let mut file = unsafe { File::from_raw_fd(tmpfd) };
        file.write_all(data).context("failed to write to memfd")?;
        file
    };

    // Seal the memfd, so that journald knows it can safely mmap/read it.
    fcntl(memfd.as_raw_fd(), FcntlArg::F_ADD_SEALS(SealFlag::all()))
        .context("unable to seal memfd")?;

    let fds = &[memfd.as_raw_fd()];
    let ancillary = [ControlMessage::ScmRights(fds)];
    let path = UnixAddr::new(SD_JOURNAL_SOCK_PATH).context("unable to create new unix address")?;
    sendmsg(
        sock.as_raw_fd(),
        &[],
        &ancillary,
        MsgFlags::empty(),
        Some(&path),
    )
    .context("sendmsg failed")?;

    // Close our side of the memfd after we send it to systemd.
    drop(memfd);

    Ok(data.len())
}

/// A systemd journal stream.
#[derive(Debug, PartialEq)]
pub struct JournalStream {
    /// The device number of the journal stream.
    device: u64,
    /// The inode number of the journal stream.
    inode: u64,
}

impl JournalStream {
    /// Parse the device and inode number from a systemd journal stream specification.
    ///
    /// See also [`JournalStream::from_env()`].
    pub(crate) fn parse<S: AsRef<OsStr>>(value: S) -> Result<Self, SdError> {
        let s = value.as_ref().to_str().with_context(|| {
            format!(
                "Failed to parse journal stream: Value {:?} not UTF-8 encoded",
                value.as_ref()
            )
        })?;
        let (device_s, inode_s) =
            s.find(':')
                .map(|i| (&s[..i], &s[i + 1..]))
                .with_context(|| {
                    format!(
                        "Failed to parse journal stream: Missing separator ':' in value '{}'",
                        s
                    )
                })?;
        let device = u64::from_str(device_s).with_context(|| {
            format!(
                "Failed to parse journal stream: Device part is not a number '{}'",
                device_s
            )
        })?;
        let inode = u64::from_str(inode_s).with_context(|| {
            format!(
                "Failed to parse journal stream: Inode part is not a number '{}'",
                inode_s
            )
        })?;
        Ok(JournalStream { device, inode })
    }

    /// Parse the device and inode number of the systemd journal stream denoted by the given environment variable.
    pub(crate) fn from_env_impl<S: AsRef<OsStr>>(key: S) -> Result<Self, SdError> {
        Self::parse(std::env::var_os(&key).with_context(|| {
            format!(
                "Failed to parse journal stream: Environment variable {:?} unset",
                key.as_ref()
            )
        })?)
    }

    /// Parse the device and inode number of the systemd journal stream denoted by the default `$JOURNAL_STREAM` variable.
    ///
    /// These values are extracted from `$JOURNAL_STREAM`, and consists of the device and inode
    /// numbers of the systemd journal stream, separated by `:`.
    pub fn from_env() -> Result<Self, SdError> {
        Self::from_env_impl("JOURNAL_STREAM")
    }

    /// Get the journal stream that would correspond to the given file metadata.
    ///
    /// Return a journal stream struct containing the device and inode number of the given file metadata.
    pub fn from_metadata(metadata: &Metadata) -> Self {
        Self {
            device: metadata.st_dev(),
            inode: metadata.st_ino(),
        }
    }

    /// Get the journal stream that would correspond to the given file descriptor.
    ///
    /// Return a journal stream struct containing the device and inode number of the given file descriptor.
    pub fn from_fd<F: AsRawFd>(fd: F) -> std::io::Result<Self> {
        // SAFETY: We do claim ownership of the file descriptor here, but we move it back out down below.
        let file = unsafe { std::fs::File::from_raw_fd(fd.as_raw_fd()) };
        let stream = file.metadata().map(|m| Self::from_metadata(&m));
        // Move the file descriptor back out of `file` to make sure the caller of this function retains ownership.
        let _ = file.into_raw_fd();
        stream
    }
}

/// Whether this process can be automatically upgraded to native journal logging.
///
/// Inspects the `$JOURNAL_STREAM` environment variable and compares the device and inode
/// numbers in this variable against the stderr file descriptor.
///
/// Return `true` if they match, and `false` otherwise (or in case of any IO error).
///
/// For services normally logging to stderr but also supporting systemd-style structured
/// logging, it is recommended to perform this check and thenupgrade to the native systemd
/// journal protocol if possible.
///
/// See section “Automatic Protocol Upgrading” in [systemd documentation][1] for more information.
///
/// [1]: https://systemd.io/JOURNAL_NATIVE_PROTOCOL/#automatic-protocol-upgrading
pub fn connected_to_journal() -> bool {
    JournalStream::from_env().map_or(false, |env_stream| {
        JournalStream::from_fd(io::stderr()).map_or(false, |o| o == env_stream)
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    fn ensure_journald_socket() -> bool {
        match std::fs::metadata(SD_JOURNAL_SOCK_PATH) {
            Ok(_) => true,
            Err(_) => {
                eprintln!(
                    "skipped, journald socket not found at '{}'",
                    SD_JOURNAL_SOCK_PATH
                );
                false
            }
        }
    }

    #[test]
    fn test_priority_numeric_level_matches_to_string() {
        let priorities = [
            Priority::Emergency,
            Priority::Alert,
            Priority::Critical,
            Priority::Error,
            Priority::Warning,
            Priority::Notice,
            Priority::Info,
            Priority::Debug,
        ];

        for priority in priorities.into_iter() {
            assert_eq!(&(u8::from(priority)).to_string(), priority.numeric_level());
        }
    }

    #[test]
    fn test_journal_print_simple() {
        if !ensure_journald_socket() {
            return;
        }

        journal_print(Priority::Info, "TEST LOG!").unwrap();
    }

    #[test]
    fn test_journal_print_large_buffer() {
        if !ensure_journald_socket() {
            return;
        }

        let data = "A".repeat(212995);
        journal_print(Priority::Debug, &data).unwrap();
    }

    #[test]
    fn test_journal_send_simple() {
        if !ensure_journald_socket() {
            return;
        }

        let mut map: HashMap<&str, &str> = HashMap::new();
        map.insert("TEST_JOURNALD_LOG1", "foo");
        map.insert("TEST_JOURNALD_LOG2", "bar");
        journal_send(Priority::Info, "Test Journald Log", map.iter()).unwrap()
    }
    #[test]
    fn test_journal_skip_fields() {
        if !ensure_journald_socket() {
            return;
        }

        let mut map: HashMap<&str, &str> = HashMap::new();
        let priority = format!("{}", u8::from(Priority::Warning));
        map.insert("TEST_JOURNALD_LOG3", "result");
        map.insert("PRIORITY", &priority);
        map.insert("MESSAGE", "Duplicate value");
        journal_send(Priority::Info, "Test Skip Fields", map.iter()).unwrap()
    }

    #[test]
    fn test_is_valid_field_lowercase_invalid() {
        let field = "test";
        assert_eq!(is_valid_field(&field), false);
    }

    #[test]
    fn test_is_valid_field_uppercase_non_ascii_invalid() {
        let field = "TRÖT";
        assert_eq!(is_valid_field(&field), false);
    }

    #[test]
    fn test_is_valid_field_uppercase_valid() {
        let field = "TEST";
        assert_eq!(is_valid_field(&field), true);
    }

    #[test]
    fn test_is_valid_field_uppercase_non_alpha_invalid() {
        let field = "TE!ST";
        assert_eq!(is_valid_field(&field), false);
    }

    #[test]
    fn test_is_valid_field_uppercase_leading_underscore_invalid() {
        let field = "_TEST";
        assert_eq!(is_valid_field(&field), false);
    }

    #[test]
    fn test_is_valid_field_uppercase_leading_digit_invalid() {
        assert_eq!(is_valid_field("1TEST"), false);
    }

    #[test]
    fn add_field_and_payload_explicit_length_simple() {
        let mut data = Vec::new();
        add_field_and_payload_explicit_length(&mut data, "FOO", "BAR");
        assert_eq!(
            data,
            vec![b'F', b'O', b'O', b'\n', 3, 0, 0, 0, 0, 0, 0, 0, b'B', b'A', b'R', b'\n']
        );
    }

    #[test]
    fn add_field_and_payload_explicit_length_internal_newline() {
        let mut data = Vec::new();
        add_field_and_payload_explicit_length(&mut data, "FOO", "B\nAR");
        assert_eq!(
            data,
            vec![b'F', b'O', b'O', b'\n', 4, 0, 0, 0, 0, 0, 0, 0, b'B', b'\n', b'A', b'R', b'\n']
        );
    }

    #[test]
    fn add_field_and_payload_explicit_length_trailing_newline() {
        let mut data = Vec::new();
        add_field_and_payload_explicit_length(&mut data, "FOO", "BAR\n");
        assert_eq!(
            data,
            vec![b'F', b'O', b'O', b'\n', 4, 0, 0, 0, 0, 0, 0, 0, b'B', b'A', b'R', b'\n', b'\n']
        );
    }

    #[test]
    fn add_field_and_payload_simple() {
        let mut data = Vec::new();
        add_field_and_payload(&mut data, "FOO", "BAR");
        assert_eq!(data, "FOO=BAR\n".as_bytes());
    }

    #[test]
    fn add_field_and_payload_internal_newline() {
        let mut data = Vec::new();
        add_field_and_payload(&mut data, "FOO", "B\nAR");
        assert_eq!(
            data,
            vec![b'F', b'O', b'O', b'\n', 4, 0, 0, 0, 0, 0, 0, 0, b'B', b'\n', b'A', b'R', b'\n']
        );
    }

    #[test]
    fn add_field_and_payload_trailing_newline() {
        let mut data = Vec::new();
        add_field_and_payload(&mut data, "FOO", "BAR\n");
        assert_eq!(
            data,
            vec![b'F', b'O', b'O', b'\n', 4, 0, 0, 0, 0, 0, 0, 0, b'B', b'A', b'R', b'\n', b'\n']
        );
    }

    #[test]
    fn journal_stream_from_fd_does_not_claim_ownership_of_fd() {
        // Just get hold of some open file which we know exists and can be read by the current user.
        let file = File::open(file!()).unwrap();
        let journal_stream = JournalStream::from_fd(file.as_raw_fd()).unwrap();
        assert_ne!(journal_stream.device, 0);
        assert_ne!(journal_stream.inode, 0);
        // Easy way to check if a file descriptor is still open, see https://stackoverflow.com/a/12340730/355252
        let result = fcntl(file.as_raw_fd(), FcntlArg::F_GETFD);
        assert!(
            result.is_ok(),
            "File descriptor not valid anymore after JournalStream::from_fd: {:?}",
            result,
        );
    }
}