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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
/*-
* syslog-rs - a syslog client translated from libc to rust
* Copyright (C) 2021  Aleksandr Morozov
* 
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
* 
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

use std::{
    mem::MaybeUninit, 
};
use std::sync::atomic::{AtomicBool, Ordering};
use std::cell::RefCell;

use crossbeam::utils::{Backoff, CachePadded};

use chrono::{offset::Local, SecondsFormat};

//use crate::{map_error, throw_error};

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




/// A common instance which describes the syslog state
pub struct Syslog
{   
    /// A multithreading sync lock. A giant lock which used for access
    /// to both - stream and [SyslogOption]
    lock: AtomicBool,

    /// A [CachePadded] [SyslogOption] instance which is mostly read only.
    option: CachePadded<SyslogOption>,

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

unsafe impl Send for Syslog {}
unsafe impl Sync for Syslog {}

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

/// Private realization. It is assumed that functions which are called,
/// are called after 'lock' is locked.
impl Syslog
{
    /// Disconnects the unix stream from syslog.
    /// Should be called only when lock is acuired
    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
    fn connectlog(&self) -> SyRes<()>
    {
        // try priv socket
        let stream = SyslogSocket::connect()?;

        let mut len: MaybeUninit<libc::socklen_t> = std::mem::MaybeUninit::uninit();
        // set the sndbuf len
        let res = unsafe
            {
                libc::getsockopt(
                    stream.get_raw_fd(), 
                    libc::SOL_SOCKET, 
                    libc::SO_SNDBUF, 
                    len.as_mut_ptr() as *mut libc::c_void, 
                    &mut {std::mem::size_of::<libc::socklen_t>() as libc::socklen_t} 
                )
            };

        if res == 0
        {
            let mut len = unsafe { len.assume_init() };

            if len < MAXLINE
            {
                len = MAXLINE;

                unsafe {
                    libc::setsockopt(
                        stream.get_raw_fd(), 
                        libc::SOL_SOCKET, 
                        libc::SO_SNDBUF, 
                        &len as *const _ as *const libc::c_void, 
                        std::mem::size_of::<libc::socklen_t>() as libc::socklen_t
                    )
                };
            }
        }

        *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")]
    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.option.is_logmasked(pri) == true
        {
            return;
        }

        // set default facility if not specified in pri
        if (pri & LOG_FACMASK) == 0
        {
            pri |= self.option.get_logfacility().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().format("%h %e %T").to_string();

        // get appname
        if self.option.exists_logtag() == true
        {
            match portable::p_getprogname()
            {
                Some(r) => self.option.set_logtag(r),
                None => self.option.set_logtag("unknown")
            }
        }

        let b_progname = self.option.get_logtag();
        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 = 
            [
                "<".as_bytes(), pri.to_string().as_bytes(), ">".as_bytes()
            ].concat();

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

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

        // output to stderr if required
        self.option.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.option.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;
                        }

                        std::thread::sleep(std::time::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.option.is_logstat_flag(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"
    ))]
    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.option.is_logmasked(pri) == true
        {
            return;
        }

        // set default facility if not specified in pri
        if (pri & LOG_FACMASK) == 0
        {
            pri |= self.option.get_logfacility().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.option.exists_logtag() == true
        {
            match portable::p_getprogname()
            {
                Some(r) => self.option.set_logtag(r),
                None => self.option.set_logtag(NILVALUE)
            }
        }

        let b_progname = self.option.get_logtag();
        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 = 
            [
                "<".as_bytes(), pri.to_string().as_bytes(), ">1".as_bytes()
            ].concat();

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

        // output to stderr if required
        self.option.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.option.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;
                        }

                        std::thread::sleep(std::time::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.option.is_logstat_flag(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)};
            }
        }

    }
}

/// A public implementations
impl Syslog
{
    /// As in a libc, this function initializes the syslog instance. The 
    /// main difference with realization in C is it returns the instance
    /// to program used this crate. This structure implements the [Send] 
    /// and [Sync] so it does not require any additional synchonization.
    ///
    /// # Arguments
    /// 
    /// * `ident` - a identification of the sender. If not set, the crate
    ///             will determine automatically!
    /// * `logstat` - sets up the syslog behaviour. Use [LogStat] 
    /// 
    /// * `facility` - a syslog facility. Use [LogFacility]
    /// 
    /// # Returns
    ///
    /// * A [SyRes] with instance or Err()
    ///
    /// # Example
    /// 
    /// ```
    ///  Syslog::openlog(
    ///        Some("test1"), 
    ///         LogStat::LOG_NDELAY | LogStat::LOG_PID, 
    ///         LogFacility::LOG_DAEMON);
    /// ```
    pub fn openlog(
        ident: Option<&str>, 
        logstat: LogStat, 
        facility: LogFacility) -> SyRes<Self>
    {
        let ret = Self
            {
                lock: AtomicBool::new(false),
                option: CachePadded::new(SyslogOption::new(ident, logstat, facility)),
                stream: RefCell::new(SyslogSocket::none()),
            };

        if logstat.contains(LogStat::LOG_NDELAY) == true
        {
            ret.connectlog()?;
        }

        return Ok(ret);
    }

    /// Sets the logmask to filter out the syslog calls.
    /// 
    /// See macroses [common::LOG_MASK] and [common::LOG_UPTO] to generate mask
    ///
    /// # Example
    ///
    /// LOG_MASK!(Priority::LOG_EMERG) | LOG_MASK!(Priority::LOG_ERROR)
    ///
    /// or
    ///
    /// ~(LOG_MASK!(Priority::LOG_INFO))
    /// LOG_UPTO!(Priority::LOG_ERROR)
    pub fn setlogmask(&self, logmask: i32) -> i32
    {
        let backoff = Backoff::new();

        // try lock
        while self.lock.swap(true, Ordering::Acquire) == true
        {
            backoff.snooze();
        }

        // locked

        let pri = self.option.set_logmask(logmask);

        // unlock 
        self.lock.store(false, Ordering::Release);

        return pri;
    }

    /// Similar to libc, closelog() will close the log
    pub fn closelog(&self)
    {
        let backoff = Backoff::new();

        // try lock
        while self.lock.swap(true, Ordering::Acquire) == true
        {
            backoff.snooze();
        }
        
        self.disconnectlog();

        // unlock
        self.lock.store(false, Ordering::Release);
    }

    /// Similar to libc, syslog() sends data to syslog server.
    /// 
    /// # Arguments
    ///
    /// * `pri` - a priority [Priority]
    ///
    /// * `fmt` - a string message. In C exists a functions with
    ///     variable argumets amount. In Rust you should create your
    ///     own macros like format!() or use format!()
    pub fn syslog(&self, pri: Priority, fmt: String)
    {
        self.vsyslog(pri, fmt);
    }

    /// Similar to syslog() and created for the compatability.
    pub fn vsyslog<S: AsRef<str>>(&self, pri: Priority, fmt: S)
    {
        let backoff = Backoff::new();

        // try lock
        while self.lock.swap(true, Ordering::Acquire) == true
        {
            backoff.snooze();
        }

        self.vsyslog1(pri.bits(), fmt);

        // unlock
        self.lock.store(false, Ordering::Release);
    }
}

#[test]
fn test_single_message()
{
    /*use std::sync::Arc;
    use std::thread;
    use std::time::Duration;
    use super::{LOG_MASK};*/

    let log = 
            Syslog::openlog(
                Some("test1"), 
                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
                LogFacility::LOG_DAEMON);

    assert_eq!(log.is_ok(), true, "{}", log.err().unwrap());

    let log = log.unwrap();

    log.syslog(Priority::LOG_DEBUG, format!("test_set_logmask() проверка BOM"));

    log.closelog();

    return;
}

#[test]
fn test_multithreading()
{
    use std::sync::Arc;
    use std::thread;
    use std::time::{Instant, Duration};

    let log = 
            Syslog::openlog(
                Some("test1"), 
                LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID, 
                LogFacility::LOG_DAEMON);

    assert_eq!(log.is_ok(), true, "{}", log.err().unwrap());

    let log = Arc::new(log.unwrap());
    let c1_log = log.clone();
    let c2_log = log.clone();

    thread::spawn(move|| {
        for i in 0..5
        {
            thread::sleep(Duration::from_nanos(200));
            let now = Instant::now();
            c1_log.syslog(Priority::LOG_DEBUG, format!("a message from thread 1 #{}[]", i));
            let elapsed = now.elapsed();
            println!("t1: {:?}", elapsed);
        }
    });

    thread::spawn(move|| {
        for i in 0..5
        {
            thread::sleep(Duration::from_nanos(201));
            let now = Instant::now();
            c2_log.syslog(Priority::LOG_DEBUG, format!("сообщение от треда 2 №{}ХЪ", i));
            let elapsed = now.elapsed();
            println!("t2: {:?}", elapsed);
        }
    });

    let now = Instant::now();
    log.syslog(Priority::LOG_DEBUG, format!("A message from main, сообщение от главнюка"));
    let elapsed = now.elapsed();
    println!("main: {:?}", elapsed);

    thread::sleep(Duration::from_secs(2));

    log.closelog();

    return;
}