syslog-rs 2.0.1

A native Rust implementation of the glibc/libc syslog.
Documentation
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
/*-
 * syslog-rs - a syslog client translated from libc to rust
 * 
 * Copyright 2025 Aleksandr Morozov
 * 
 * The syslog-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *                     
 *   2. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */


use std::fmt;
use std::ops::{BitAnd, Shl};
use std::path::Path;
use std::sync::LazyLock;

use nix::libc;


use crate::portable;

use super::error::SyRes;
use super::throw_error;

bitflags! {
    /// Flags  which  control  the  operation  of openlog() and 
    /// subsequent calls to syslog.
    pub struct LogStat: libc::c_int 
    {
        /// Log the process ID with each message. (!todo)
        const LOG_PID = libc::LOG_PID;
        
        /// Write directly to the system console if there is an error 
        /// while sending to the system logger.
        const LOG_CONS = libc::LOG_CONS;

        /// The converse of LOG_NDELAY; opening of the connection is delayed 
        /// until syslog() is called. (This is the default behaviour,and need 
        /// not be specified.)
        const LOG_ODELAY = libc::LOG_ODELAY;

        /// Open the connection immediately
        const LOG_NDELAY = libc::LOG_NDELAY;

        /// Don't wait for child processes that may have been created 
        /// while logging the message
        const LOG_NOWAIT = libc::LOG_NOWAIT;
        
        /// Also log the message to stderr
        const LOG_PERROR = 0x20;
    }
}

bitflags! {
    pub(crate) struct LogMask: libc::c_int 
    {
        const LOG_FACMASK = libc::LOG_FACMASK;
        const LOG_PRIMASK = libc::LOG_PRIMASK;
    }
}

bitflags! {
    /// This determines the importance of the message
    pub struct Priority: libc::c_int 
    {
        /// system is unusable
        const LOG_EMERG = libc::LOG_EMERG;

        /// action must be taken immediately
        const LOG_ALERT = libc::LOG_ALERT;

        /// critical conditions
        const LOG_CRIT = libc::LOG_CRIT;

        /// error conditions
        const LOG_ERR = libc::LOG_ERR;

        /// warning conditions
        const LOG_WARNING = libc::LOG_WARNING;

        /// normal, but significant, condition
        const LOG_NOTICE = libc::LOG_NOTICE;
        
        /// informational message
        const LOG_INFO = libc::LOG_INFO;

        /// debug-level message
        const LOG_DEBUG = libc::LOG_DEBUG;
    }
}

impl fmt::Display for Priority
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        //let pri = self.bits & LogMask::LOG_PRIMASK;

        if self.contains(Self::LOG_DEBUG) == true
        {
            write!(f, "[DEBUG]")
        }
        else if self.contains(Self::LOG_INFO) == true
        {
            write!(f, "[INFO]")
        }
        else if self.contains(Self::LOG_NOTICE) == true
        {
            write!(f, "[NOTICE]")
        }
        else if self.contains(Self::LOG_WARNING) == true
        {
            write!(f, "[WARNING]")
        }
        else if self.contains(Self::LOG_ERR) == true
        {
            write!(f, "[ERR]")
        }
        else if self.contains(Self::LOG_CRIT) == true
        {
            write!(f, "[CRIT]")
        }
        else if self.contains(Self::LOG_ALERT) == true
        {
            write!(f, "[ALERT]")
        }
        else if self.contains(Self::LOG_EMERG) == true
        {
            write!(f, "[EMERG]")
        }
        else
        {
            write!(f, "[UNKNOWN]")
        }
    }
}

impl Priority
{
    /// This function validates the `pri` for the incorrects bits set.
    /// If bits are set incorrectly, resets the invalid bits with:
    /// *pri & (LogMask::LOG_PRIMASK | LogMask::LOG_FACMASK).
    ///
    /// # Arguments
    ///
    /// * `pri` - a priority bits
    ///
    /// # Returns
    /// 
    /// * A [SyRes]. Ok() when valid or Err with error message
    pub(crate) 
    fn check_invalid_bits(&mut self) -> SyRes<()>
    {
    
        if (self.bits() & !(LogMask::LOG_PRIMASK | LogMask::LOG_FACMASK )) != 0
        {
            let pri_old = self.clone();
            
            *self = unsafe { Self::from_bits_unchecked( self.bits() & (LogMask::LOG_PRIMASK | LogMask::LOG_FACMASK).bits() ) };

            throw_error!("unknwon facility/priority: {:x}", pri_old);
        }

        return Ok(());
    }

    pub(crate) 
    fn set_facility(&mut self, f: LogFacility)
    {
        *self = unsafe { Self::from_bits_unchecked(self.bits | f.bits() )};
    }
}

bitflags! {
    /// The facility argument is used to specify what type of program 
    /// is logging the message.
    pub struct LogFacility: libc::c_int 
    {
        /// kernel messages (these can't be generated from user processes)
        const LOG_KERN = libc::LOG_KERN;

        /// (default) generic user-level messages
        const LOG_USER = libc::LOG_USER;

        /// mail subsystem
        const LOG_MAIL = libc::LOG_MAIL;

        /// system daemons without separate facility value
        const LOG_DAEMON = libc::LOG_DAEMON;
        
        /// security/authorization messages
        const LOG_AUTH = libc::LOG_AUTH;

        /// messages generated internally by syslogd(8)
        const LOG_SYSLOG = libc::LOG_SYSLOG;

        /// line printer subsystem
        const LOG_LPR = libc::LOG_LPR;

        /// USENET news subsystem
        const LOG_NEWS = libc::LOG_NEWS;

        /// UUCP subsystem
        const LOG_UUCP = libc::LOG_UUCP;

        /// reserved for local use
        const LOG_LOCAL0 = libc::LOG_LOCAL0;

        /// reserved for local use
        const LOG_LOCAL1 = libc::LOG_LOCAL1;

        /// reserved for local use
        const LOG_LOCAL2 = libc::LOG_LOCAL2;
        
        /// reserved for local use
        const LOG_LOCAL3 = libc::LOG_LOCAL3;

        /// reserved for local use
        const LOG_LOCAL4 = libc::LOG_LOCAL4;

        /// reserved for local use
        const LOG_LOCAL5 = libc::LOG_LOCAL5;

        /// reserved for local use
        const LOG_LOCAL6 = libc::LOG_LOCAL6;
        
        /// reserved for local use
        const LOG_LOCAL7 = libc::LOG_LOCAL7;
    }
}

/// max hostname size
pub const MAXHOSTNAMELEN: usize = 256;

/// mask to extract facility part
pub const LOG_FACMASK: i32 = 0x03f8;

/// Maximum number of characters of syslog message.
/// According to RFC5424. However syslog-protocol also may state that 
/// the max message will be defined by the transport layer.
pub const MAXLINE: usize = 8192;

/// RFC3164 limit
pub const RFC3164_MAX_PAYLOAD_LEN: usize = 1024;

#[cfg(all(feature = "udp_truncate_1024_bytes", feature = "udp_truncate_1440_bytes"))]
compile_error!("either 'udp_truncate_1024_bytes' or 'udp_truncate_1440_bytes' should be enabled");

// RFC5424 480 octets or limited by the (transport) MAX_DGRAM_LEN or other.
#[cfg(feature = "udp_truncate_1024_bytes")]
pub const RFC5424_UDP_MAX_PKT_LEN: usize  = 1024;

#[cfg(any(feature = "udp_truncate_1440_bytes", all(not(feature = "udp_truncate_1440_bytes"), not(feature = "udp_truncate_1024_bytes"))))]
pub const RFC5424_UDP_MAX_PKT_LEN: usize  = 2048;

#[cfg(feature = "tcp_truncate_1024_bytes")]
pub const RFC5424_TCP_MAX_PKT_LEN: usize  = 1024;

#[cfg(feature = "tcp_truncate_2048_bytes")]
pub const RFC5424_TCP_MAX_PKT_LEN: usize  = 2048;

#[cfg(feature = "tcp_truncate_4096_bytes")]
pub const RFC5424_TCP_MAX_PKT_LEN: usize  = 4096;

#[cfg(feature = "tcp_truncate_max_bytes")]
pub const RFC5424_TCP_MAX_PKT_LEN: usize  = MAXLINE;

/// A max byte lenth of APPNAME (NILVALUE / 1*48PRINTUSASCII)
pub const RFC_MAX_APP_NAME: usize = 48;

/// RFC5424 defined value.
pub const NILVALUE: &'static str = "-";

/// RFC5424 defined value (bytes).
pub const NILVALUE_B: &'static [u8] = b"-";

pub const WSPACE: &'static str = " ";

pub const NEXTLINE: &'static str = "\n";

/// Unpriv socket
pub const PATH_LOG: &'static str = "/var/run/log";

/// Priviledged socket
pub const PATH_LOG_PRIV: &'static str = "/var/run/logpriv";

/// backward compatibility
pub const PATH_OLDLOG: &'static str = "/dev/log";

/// OSX compat
pub const PATH_OSX: &'static str = "/var/run/syslog";

/*
pub static PATH_CONSOLE: LazyLock<CString> = LazyLock::new(|| 
    {
        CString::new("/dev/console").unwrap()
    }
);
*/
pub static PATH_CONSOLE: LazyLock<&Path> = LazyLock::new(|| 
    {
        Path::new("/dev/console")
    }
);

pub static RFC5424_MAX_DGRAM: LazyLock<usize> = LazyLock::new(|| 
    {
        portable::get_local_dgram_maxdgram() as usize
    }
);



/// LOG_MASK is used to create the priority mask in setlogmask. 
/// For a single Priority mask
/// used with [Priority]
/// can be used with | & ! bit operations LOG_MASK()
///
/// # Examples
/// 
/// ```
///     LOG_MASK!(Priority::LOG_ALERT) | LOG_MASK!(Priority::LOG_INFO)
/// ```
#[macro_export]
macro_rules! LOG_MASK 
{
    ($($arg:tt)*) => (
        (1 << $($arg)*)
    )
}

/// LOG_MASK is used to create the priority mask in setlogmask
/// For a mask UPTO specified
/// used with [Priority]
///
/// # Examples
/// 
/// ```
///     LOG_UPTO!(Priority::LOG_ALERT)
/// ```
#[macro_export]
macro_rules! LOG_UPTO 
{
    ($($arg:tt)*) => (
        ((1 << (($($arg)*) + 1)) - 1)
    )
}

/// Returns the static configuration for internal log
pub 
fn get_internal_log() -> libc::c_int
{
    return 
        Priority::LOG_ERR.bits() | 
        (LogStat::LOG_CONS| LogStat::LOG_PERROR| LogStat::LOG_PID).bits();
}

impl Shl<Priority> for i32
{
    type Output = i32;

    fn shl(self, rhs: Priority) -> i32 
    {
        let lhs = self;
        return lhs << rhs.bits();
    }
}

impl BitAnd<Priority> for i32
{
    type Output = i32;

    #[inline]
    fn bitand(self, rhs: Priority) -> i32
    {
        return self & rhs.bits();
    }
}

impl BitAnd<LogMask> for Priority 
{
    type Output = Priority;

    #[inline]
    fn bitand(self, rhs: LogMask) -> Self::Output
    {
        return Self {bits: self.bits() & rhs.bits()};
    }
}

impl BitAnd<LogMask> for LogFacility 
{
    type Output = LogFacility;

    #[inline]
    fn bitand(self, rhs: LogMask) -> Self::Output
    {
        return Self {bits: self.bits() & rhs.bits()};
    }
}

impl BitAnd<LogMask> for i32 
{
    type Output = i32;

    #[inline]
    fn bitand(self, rhs: LogMask) -> i32
    {
        return self & rhs.bits();
    }
}

#[cfg(feature = "build_sync")]
pub(crate) mod sync_portion
{
    use std::borrow::Cow;
    use std::io::Write;
    use std::io::IoSlice;
    use crate::error::SyRes;
    use crate::map_error_os;

    /// Sends to the FD i.e file of stderr, stdout or any which 
    /// implements [Write] `write_vectored`.
    ///
    /// # Arguments
    /// 
    /// * `file_fd` - mutable consume of the container FD.
    ///
    /// * `msg` - a reference on array of data
    ///
    /// * `newline` - a new line string ref i.e "\n" or "\r\n"
    pub(crate) 
    fn send_to_fd<W>(mut file_fd: W, msg: &[Cow<'_, str>], newline: &str) -> SyRes<usize>
    where W: Write
    {
        let mut iov_list: Vec<IoSlice<'_>> = Vec::with_capacity(msg.len() + 1);

        msg.iter().for_each(|v| iov_list.push(IoSlice::new(v.as_bytes())));
        iov_list.push(IoSlice::new(newline.as_bytes()));

        return 
            file_fd
                .write_vectored(&iov_list)
                .map_err(|e|
                    map_error_os!(e, "send_to_fd() writev() failed")
                );
    }
}

#[cfg(feature = "build_sync")]
pub(crate) use self::sync_portion::*;

/// This function trancated 1 last UTF8 character from the string.
///
/// # Arguments
///
/// * `lt` - a string which is trucated
/// 
/// # Returns
/// 
/// * A reference to the ctruncated string
pub 
fn truncate(lt: &str) -> &str
{
    let ltt =
        match lt.char_indices().nth(lt.len()-1) 
        {
            None => lt,
            Some((idx, _)) => &lt[..idx],
        };
    return ltt;
}

/// Trancates the string up to closest to N byte equiv UTF8
///  if string exceeds size
/// 
/// For example:  
/// ボルテ 'e3 83 9c e3 83 ab e3 83 86' with N=3  
/// will give 'ボ'  
/// 
/// ボルテ 'e3 83 9c e3 83 ab e3 83 86' with N=4  
/// will give 'ボ' 
/// 
/// ボルテ 'e3 83 9c e3 83 ab e3 83 86' with N=1  
/// will give ''
/// 
/// # Arguments
///
/// * `lt` - a string to truncate
///
/// * `n` - a size (in bytes, not in chars)
/// 
/// # Returns 
///
/// * The new instance of String even if no action was required
pub 
fn truncate_n<'t>(lt: &'t str, n: usize) -> &'t str
{
    if lt.as_bytes().len() <= n
    {
        return lt;
    }

    let mut nn: usize = 0;
    let mut cc = lt.chars();
    let mut ln: usize;

    loop 
    {
        match cc.next()
        {
            Some(r) =>
            {
                ln = r.len_utf8();
                nn += ln;

                if nn == n
                {
                    return &lt[..nn];
                }
                else if nn > n
                {
                    return &lt[..nn-ln];
                }
            },
            None => 
                return lt,
        }
    }
}


#[cfg(test)]
mod tests
{
    use std::borrow::Cow;

    use super::*;

    #[cfg(feature = "build_sync")]
    #[test]
    fn test_error_message()
    {
        /*use std::sync::Arc;
        use std::thread;
        use std::time::Duration;
        use super::{LOG_MASK};*/

        let testmsg = Cow::Borrowed("this is test message!");
        let testmsg2 = Cow::Borrowed(" this is test message 2!");
        let newline = "\n";
        let stderr_lock = std::io::stderr().lock();
        let res = send_to_fd(stderr_lock, &[testmsg, testmsg2], &newline);

        println!("res: {:?}", res);

        assert_eq!(res.is_ok(), true, "err: {}", res.err().unwrap());
    
        return;
    }

    #[test]
    fn test_truncate()
    {
        let test = "cat\n";

        let trunc = truncate(test);

        assert_eq!("cat", trunc);
    }

    #[test]
    fn test_priority_shl()
    {
        assert_eq!((1 << 5), (1 << Priority::LOG_NOTICE));
    }

    #[test]
    fn test_truncate_n()
    {
        assert_eq!(truncate_n("abcde", 3), "abc");
        assert_eq!(truncate_n("ボルテ", 4), "");
        assert_eq!(truncate_n("ボルテ", 5), "");
        assert_eq!(truncate_n("ボルテ", 6), "ボル");
        assert_eq!(truncate_n("abcde", 0), "");
        assert_eq!(truncate_n("abcde", 5), "abcde");
        assert_eq!(truncate_n("abcde", 6), "abcde");
        assert_eq!(truncate_n("ДАТА", 3), "Д");
        assert_eq!(truncate_n("ДАТА", 4), "ДА");
        assert_eq!(truncate_n("ДАТА", 1), "");
    }

}