syslog_rs/formatters/
syslog_3146.rs

1/*-
2 * syslog-rs - a syslog client translated from libc to rust
3 * 
4 * Copyright 2025 Aleksandr Morozov
5 * 
6 * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by
7 * the European Commission - subsequent versions of the EUPL (the "Licence").
8 * 
9 * You may not use this work except in compliance with the Licence.
10 * 
11 * You may obtain a copy of the Licence at:
12 * 
13 *    https://joinup.ec.europa.eu/software/page/eupl
14 * 
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the Licence is distributed on an "AS IS" basis, WITHOUT
17 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
18 * Licence for the specific language governing permissions and limitations
19 * under the Licence.
20 */
21
22use std::borrow::Cow;
23
24use chrono::Local;
25
26use crate::{socket::TapType, truncate, truncate_n, Priority, RFC3164_MAX_PAYLOAD_LEN};
27
28use super::{SyslogFormatted, SyslogFormatter};
29
30
31
32#[derive(Debug, Clone)]
33pub struct FormatRfc3146;
34
35unsafe impl Send for FormatRfc3146 {}
36
37impl SyslogFormatter for FormatRfc3146
38{
39    fn vsyslog1_format<'f>(_tap_type: TapType, pri: Priority, progname: &'f str, pid: &'f str, fmt: &'f str) -> SyslogFormatted<'f>
40    {
41        // get timedate
42        let timedate = Local::now().format("%h %e %T").to_string();
43
44        let msg_payload = truncate_n(fmt.as_ref(), RFC3164_MAX_PAYLOAD_LEN);
45
46        let msg_payload_final = 
47            if msg_payload.ends_with("\n") == true
48            {
49                truncate(&msg_payload)
50            }
51            else
52            {
53                &msg_payload
54            };
55            
56        // message based on RFC 3164
57        let msg_pri = 
58            [
59                "<", pri.bits().to_string().as_str(), ">"
60            ]
61            .concat();
62
63        let msg_pkt = 
64            [
65                //pri <>
66                Cow::Owned(msg_pri), 
67                // timedate
68                Cow::Owned(timedate.clone()),
69                // hostname
70                // " ".as_bytes(), hostname.as_bytes(), 
71                // appname
72                Cow::Borrowed(" "), Cow::Borrowed(progname),
73                // PID
74                Cow::Borrowed("["), Cow::Borrowed(pid), Cow::Borrowed("]:"),
75                // msg
76                Cow::Borrowed(" "), /*b"\xEF\xBB\xBF",*/ Cow::Borrowed(msg_payload_final)
77            ]
78            .to_vec();
79            
80        let msg_rng = msg_pkt.len();
81
82
83        return SyslogFormatted{ msg: msg_pkt, stderr_range: 1..msg_rng };
84    }
85}
86