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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
use std::thread::sleep;
use std::time::Duration;
use std::cell::{Cell, RefCell};

use chrono::offset::Local;

#[cfg(any(
    target_os = "freebsd",
    target_os = "dragonfly",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "macos"
))]
use chrono::SecondsFormat;

use super::portable;
use super::socket::*;
use super::common::*;
use super::error::{SyRes/* , SyslogError*/};

/// A common instance which describes the syslog state
pub struct SyncSyslogInternal
{   
    /// A identification i.e program name, thread name
    logtag: RefCell<Option<String>>, 

    /// Defines how syslog operates
    logstat: LogStat,

    /// Holds the facility 
    facility: LogFacility,

    /// A logmask
    logmask: Cell<i32>,

    /// A stream
    stream: RefCell<SyslogSocket>,
}

impl Drop for SyncSyslogInternal 
{
    fn drop(&mut self) 
    {
        self.disconnectlog();
    }
}

/// Private realization. It is assumed that functions which are called,
/// are called after 'lock' is locked.
impl SyncSyslogInternal
{
    /// Creates new instance of [SyslogOption].
    ///
    /// # Arguments
    ///
    /// * `ident` - An optional argument which takes ref to str. If none, the
    ///     ident will be set later. Yje ident will be trucated to 48 UTF8
    ///     chars.
    /// 
    /// * `logstat` - A [LogStat] flags separated by '|'
    /// 
    /// * `facility` - A [LogFacility] flag
    ///
    /// # Returns
    ///
    /// * The instance of the [SyslogOption]. Never fails.
    pub(crate) fn new(
        ident: Option<&str>, 
        logstat: LogStat, 
        facility: LogFacility) -> Self
    {
        // check if log_facility is invalid
        let log_facility =
            if facility.is_empty() == false && 
                (facility & !LogMask::LOG_FACMASK).is_empty() == true
            {
                facility
            }
            else
            {
                // default facility code
                LogFacility::LOG_USER
            };

        let ident = match ident
            {
                Some(r) => Some(truncate_n(r, 48)),
                None => None,
            };
        
        return 
            Self
            {
                logtag: RefCell::new(ident),
                logstat: logstat, 
                facility: log_facility,
                logmask: Cell::new(0xff),
                stream: RefCell::new(SyslogSocket::none()),
            };
    }

    fn send_to_stderr(&self, msg: &mut [u8])
    {
        if self.logstat.intersects(LogStat::LOG_PERROR) == true
        {
            let mut newline = String::from("\n");
            send_to_stderr(libc::STDERR_FILENO, msg, &mut newline);
        }
    }

    fn is_logmasked(&self, pri: i32) -> bool
    {
        if ((1 << (pri & LogMask::LOG_PRIMASK)) & self.logmask.get()) == 0
        {
            return true;
        }

        return false;
    }

    pub(crate) fn set_logmask(&self, logmask: i32) -> i32
    {
        let oldmask = self.logmask.get();

        if logmask != 0
        {
            self.logmask.set(logmask);
        }

        return oldmask;
    }

    pub(crate) fn set_logtag<L: AsRef<str>>(&self, logtag: L)
    {
        *self.logtag.borrow_mut() = 
            Some(truncate_n(logtag.as_ref(), 48));
    }

    /// Disconnects the unix stream from syslog.
    /// Should be called only when lock is acuired
    pub(crate) fn disconnectlog(&self)
    {
        if self.stream.borrow().is_none() == false
        {
            self.stream.borrow_mut().shutdown();

            *self.stream.borrow_mut() = SyslogSocket::none();
        }
    }

    /// Connects unix stream to the syslog and sets up the properties of
    /// the unix stream.
    /// Should be called only when lock is acuired
    pub(crate) fn connectlog(&self) -> SyRes<()>
    {
        let stream = SyslogSocket::connect()?;

        *self.stream.borrow_mut() = stream;

        return Ok(());
    }

    /// An internal function which is called by the syslog or vsyslog.
    /// A glibc implementation RFC3164
    #[cfg(target_os = "linux")]
    pub(crate) fn vsyslog1<S: AsRef<str>>(&self, mut pri: i32, fmt: S)
    {
        // check for invalid bits
        match check_invalid_bits(&mut pri)
        {
            Ok(_) => {},
            Err(_e) => self.vsyslog1(get_internal_log(), fmt.as_ref())
        }

        // check priority against setlogmask
        if self.is_logmasked(pri) == true
        {
            return;
        }

        // set default facility if not specified in pri
        if (pri & LOG_FACMASK) == 0
        {
            pri |= self.facility.bits();
        }

        // get timedate
        let timedate = Local::now().format("%h %e %T").to_string();

        // get appname
        if self.logtag.borrow().is_none() == true
        {
            match portable::p_getprogname()
            {
                Some(r) => 
                {
                    *self.logtag.borrow_mut() = 
                        Some(truncate_n(r.as_str(), 48));
                },
                None => 
                {
                    *self.logtag.borrow_mut() = 
                        Some(truncate_n("unknown", 48));
                }
            }
        }

        let b_progname = self.logtag.borrow();
        let progname = b_progname.as_ref().unwrap();
        

        let msg = fmt.as_ref();
        let msg_final = 
            if msg.ends_with("\n") == true
            {
                truncate(msg)
            }
            else
            {
                msg
            };

        // message based on RFC 3164
        let msg_pri = 
            [
                b"<", pri.to_string().as_bytes(), b">"
            ].concat();

        let msg_header = 
            [ 
                // timedate
                timedate.as_bytes(), 
                // hostname
               // " ".as_bytes(), hostname.as_bytes(), 
            ].concat();

        let mut msg = 
            [
                // appname
                b" ", progname.as_bytes(), 
                // PID
                b"[", portable::get_pid().to_string().as_str().as_bytes(), b"]:",
                // msg
                b" ", /*b"\xEF\xBB\xBF",*/ msg_final.as_bytes()
            ].concat();
        
        drop(b_progname);

        // output to stderr if required
        self.send_to_stderr(&mut msg);
        
        
        let fullmsg = [msg_pri.as_slice(), msg_header.as_slice(), msg.as_slice()].concat();

        if self.stream.borrow().is_none() == true
        {
            // open connection
            match self.connectlog()
            {
                Ok(_) => {},
                Err(e) =>
                {
                    self.send_to_stderr(unsafe { e.eject_string().as_bytes_mut() } );
                    return;
                }
            }
        }

        // There are two possible scenarios when send may fail:
        // 1. syslog temporary unavailable
        // 2. syslog out of buffer space
        // If we are connected to priv socket then in case of 1 we reopen connection
        //      and retry once.
        // If we are connected to unpriv then in case of 2 repeatedly retrying to send
        //      until syslog socket buffer space will be cleared

        loop
        {
            let mut stream = self.stream.borrow_mut();

            match stream.send(&fullmsg)
            {
                Ok(_) => return,
                Err(err) =>
                {   
                    if let Some(libc::ENOBUFS) = err.raw_os_error()
                    {
                        // scenario 2
                        if stream.is_priv() == true
                        {
                            break;
                        }

                        sleep(Duration::from_micros(1));
                        drop(stream);
                    }
                    else
                    {
                        // scenario 1
                        drop(stream);

                        self.disconnectlog();
                        match self.connectlog()
                        {
                            Ok(_) => {},
                            Err(_e) => break,
                        }

                        // if resend will fail then probably the scn 2 will take place
                    }   
                }
            }
        } // loop


        // If program reached this point then transmission over socket failed.
        // Try to output message to console

        if self.logstat.intersects(LogStat::LOG_CONS)
        {
            let fd = unsafe {
                libc::open(
                    PATH_CONSOLE.as_ptr(), 
                    libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC, 
                    0
                )
            };

            if fd >= 0
            {
                let mut without_pri = [msg_header.as_slice(), msg.as_slice()].concat();
                let mut newline = String::from("\r\n");
                send_to_stderr(fd, without_pri.as_mut_slice(),&mut newline);

                unsafe {libc::close(fd)};
            }
        }
    }

    /// An internal function which is called by the syslog or vsyslog.
    /// A glibc implementation RFC5424
    #[cfg(any(
        target_os = "freebsd",
        target_os = "dragonfly",
        target_os = "openbsd",
        target_os = "netbsd",
        target_os = "macos"
    ))]
    pub(crate) fn vsyslog1<S: AsRef<str>>(&self, mut pri: i32, fmt: S)
    {
        // check for invalid bits
        match check_invalid_bits(&mut pri)
        {
            Ok(_) => {},
            Err(_e) => self.vsyslog1(get_internal_log(), fmt.as_ref())
        }

        // check priority against setlogmask
        if self.is_logmasked(pri) == true
        {
            return;
        }

        // set default facility if not specified in pri
        if (pri & LOG_FACMASK) == 0
        {
            pri |= self.facility.bits();
        }

        let mut hostname_buf = [0u8; MAXHOSTNAMELEN];
        let hostname = 
            match nix::unistd::gethostname(&mut hostname_buf)
            {
                Ok(r) =>
                {
                    match r.to_str()
                    {
                        Ok(r) => r,
                        Err(_e) => NILVALUE
                    }
                },
                Err(_e) => NILVALUE,
            };

        // get timedate
        let timedate = 
            Local::now().to_rfc3339_opts(SecondsFormat::Secs, false);

        // get appname
        if self.logtag.borrow().is_none() == true
        {
            match portable::p_getprogname()
            {
                Some(r) => 
                {
                    *self.logtag.borrow_mut() = 
                        Some(truncate_n(r.as_str(), 48));
                },
                None => 
                {
                    *self.logtag.borrow_mut() = Some(NILVALUE.to_string());
                }
            }
        }

        let b_progname = self.logtag.borrow();
        let progname = b_progname.as_ref().unwrap();
        

        let msg = fmt.as_ref();
        let msg_final = 
            if msg.ends_with("\n") == true
            {
                truncate(msg)
            }
            else
            {
                msg
            };

        // message based on RFC 5424
        let msg_pri = 
            [
                b"<", pri.to_string().as_bytes(), b">1"
            ].concat();

        let msg_header = 
            [ 
                // timedate
                b" ", timedate.as_bytes(), 
                // hostname
                b" ", hostname.as_bytes(), 
            ].concat();
        
        let mut msg = 
            [
                // appname
                b" ", progname.as_bytes(), 
                // PID
                b" ", portable::get_pid().to_string().as_str().as_bytes(),
                // message ID
                b" ", NILVALUE.as_bytes(), 
                // structured data
                b" ", NILVALUE.as_bytes(), 
                // msg
                b" ", /*b"\xEF\xBB\xBF",*/ msg_final.as_bytes()
            ].concat();
        
        drop(progname);

        // output to stderr if required
        self.send_to_stderr(&mut msg);
        
        
        let fullmsg = [msg_pri.as_slice(), msg_header.as_slice(), msg.as_slice()].concat();

        if self.stream.borrow().is_none() == true
        {
            // open connection
            match self.connectlog()
            {
                Ok(_) => {},
                Err(e) =>
                {
                    self.send_to_stderr(unsafe { e.eject_string().as_bytes_mut() } );
                    return;
                }
            }
        }

        // There are two possible scenarios when send may fail:
        // 1. syslog temporary unavailable
        // 2. syslog out of buffer space
        // If we are connected to priv socket then in case of 1 we reopen connection
        //      and retry once.
        // If we are connected to unpriv then in case of 2 repeatedly retrying to send
        //      until syslog socket buffer space will be cleared

        loop
        {
            let mut stream = self.stream.borrow_mut();

            match stream.send(&fullmsg)
            {
                Ok(_) => return,
                Err(err) =>
                {   
                    if let Some(libc::ENOBUFS) = err.raw_os_error()
                    {
                        // scenario 2
                        if stream.is_priv() == true
                        {
                            break;
                        }

                        sleep(Duration::from_micros(1));
                        drop(stream);
                    }
                    else
                    {
                        // scenario 1
                        drop(stream);

                        self.disconnectlog();
                        match self.connectlog()
                        {
                            Ok(_) => {},
                            Err(_e) => break,
                        }

                        // if resend will fail then probably the scn 2 will take place
                    }   
                }
            }
        } // loop


        // If program reached this point then transmission over socket failed.
        // Try to output message to console

        if self.logstat.intersects(LogStat::LOG_CONS)
        {
            let fd = unsafe {
                libc::open(
                    PATH_CONSOLE.as_ptr(), 
                    libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC, 
                    0
                )
            };

            if fd >= 0
            {
                let mut without_pri = [msg_header.as_slice(), msg.as_slice()].concat();
                let mut newline = String::from("\r\n");
                send_to_stderr(fd, without_pri.as_mut_slice(),&mut newline);

                unsafe {libc::close(fd)};
            }
        }

    }
}

#[test]
fn test_bit_operations()
{
    let correct = 
        SyncSyslogInternal::new(Some("test1"), LogStat::LOG_PID, LogFacility::LOG_DAEMON);

    assert_eq!(correct.facility, LogFacility::LOG_DAEMON);
    assert_eq!((correct.facility & !LogFacility::LOG_DAEMON), LogFacility::empty());
}

#[test]
fn test_bit_operations2()
{
    let _correct = 
        SyncSyslogInternal::new(Some("test2"), LogStat::LOG_PID, LogFacility::LOG_DAEMON);

    let mut pri = Priority::LOG_ALERT.bits();

    let res = check_invalid_bits(&mut pri);

    assert_eq!(res.is_ok(), true);
    assert_eq!(pri, Priority::LOG_ALERT.bits());
}

#[test]
fn test_set_priority()
{
    use super::LOG_MASK;

    let correct = 
        SyncSyslogInternal::new(Some("test1"), LogStat::LOG_PID, LogFacility::LOG_DAEMON);

    let ret = correct.set_logmask(LOG_MASK!(Priority::LOG_ERR));

    assert_eq!(ret, 0xff);

    let ret = correct.set_logmask(LOG_MASK!(Priority::LOG_ERR));

    assert_eq!(ret, LOG_MASK!(Priority::LOG_ERR));

    let ret = correct.is_logmasked(Priority::LOG_WARNING.bits());
    assert_eq!(ret, true);

    let ret = correct.is_logmasked(Priority::LOG_ERR.bits());
    assert_eq!(ret, false);

    let ret = correct.is_logmasked(Priority::LOG_CRIT.bits());
    assert_eq!(ret, true);
}

#[test]
fn test_set_priority2()
{
    use super::LOG_MASK;
    
    let correct = 
        SyncSyslogInternal::new(Some("test1"), LogStat::LOG_PID, LogFacility::LOG_DAEMON);

    let ret = correct.set_logmask(!LOG_MASK!(Priority::LOG_ERR));

    assert_eq!(ret, 0xff);

    let ret = correct.is_logmasked(Priority::LOG_WARNING.bits());
    assert_eq!(ret, false);

    let ret = correct.is_logmasked(Priority::LOG_ERR.bits());
    assert_eq!(ret, true);

    let ret = correct.is_logmasked(Priority::LOG_CRIT.bits());
    assert_eq!(ret, false);
}