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 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
/*-
* syslog-rs - a syslog client translated from libc to rust
* Copyright (C) 2020 Aleksandr Morozov, RELKOM s.r.o
* Copyright (C) 2021-2022 Aleksandr Morozov
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
use std::path::Path;
use tokio::net::UnixDatagram;
use tokio::time::{sleep, Duration};
use tokio::sync::Mutex;
use async_recursion::async_recursion;
use async_trait::async_trait;
use chrono::offset::Local;
use nix::libc;
#[cfg(any(
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd",
target_os = "netbsd",
target_os = "macos"
))]
use chrono::SecondsFormat;
use crate::portable;
use crate::common::*;
use crate::error::{SyRes};
use super::async_socket::*;
pub use super::syslog_trait::{SyslogStd, SyslogExt};
/// Internal structure with syslog setup
struct SyslogInternal
{
/// A identification i.e program name, thread name
logtag: Option<String>,
/// Defines how syslog operates
logstat: LogStat,
/// Holds the facility
facility: LogFacility,
/// A logmask
logmask: i32,
/// A stream
stream: Box<dyn AsyncSyslogTap + Send>,
}
//unsafe impl Sync for SyslogInternal{}
//unsafe impl Send for SyslogInternal{}
// Drop is called when no more references are left.
impl Drop for SyslogInternal
{
fn drop(&mut self)
{
self.disconnectlog();
}
}
impl SyslogInternal
{
fn new(
logtag: Option<&str>,
logstat: LogStat,
facility: LogFacility,
opt_path: Option<&Path>
) -> 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 logtag
{
Some(r) => Some(truncate_n(r, RFC_MAX_APP_NAME)),
None => None,
};
return
Self
{
logtag: ident,
logstat: logstat,
facility: log_facility,
logmask: 0xff,
stream: AsyncTap::<UnixDatagram>::new(opt_path),
};
}
pub(crate)
fn set_logmask(&mut self, logmask: i32) -> i32
{
let oldmask = self.logmask;
if logmask != 0
{
self.logmask = logmask;
}
return oldmask;
}
pub(crate)
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);
}
}
pub(crate)
fn is_logmasked(&self, pri: i32) -> bool
{
if ((1 << (pri & LogMask::LOG_PRIMASK)) & self.logmask) == 0
{
return true;
}
return false;
}
pub(crate)
fn set_logtag<L: AsRef<str>>(&mut self, logtag: L)
{
self.logtag =
Some(truncate_n(logtag.as_ref(), RFC_MAX_APP_NAME));
}
/// Disconnects the unix stream from syslog.
/// Should be called only when lock is acuired
fn disconnectlog(&mut self)
{
let _ = self.stream.disconnectlog();
}
/// 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(&mut self) -> SyRes<()>
{
return self.stream.connectlog();
}
/// An internal function which is called by the syslog or vsyslog.
/// A glibc implementation RFC3164
#[cfg(target_os = "linux")]
#[async_recursion]
async
fn vsyslog1(&mut self, mut pri: i32, fmt: &str)
{
// check for invalid bits
match check_invalid_bits(&mut pri)
{
Ok(_) => {},
Err(_e) => self.vsyslog1(get_internal_log(), fmt).await
}
// 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().format("%h %e %T").to_string();
// get appname
if self.logtag.is_none() == true
{
match portable::p_getprogname()
{
Some(r) => self.set_logtag(r),
None => self.set_logtag("")
}
}
let progname = self.logtag.as_ref().unwrap();
let msg_final =
if fmt.ends_with("\n") == true
{
truncate(fmt)
}
else
{
fmt
};
// 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(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.is_connected() == false
{
// open connection
match self.connectlog()
{
Ok(_) => {},
Err(e) =>
{
self.send_to_stderr(unsafe { e.into_inner().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
{
match self.stream.send(&fullmsg).await
{
Ok(_) => return,
Err(err) =>
{
if let Some(libc::ENOBUFS) = err.raw_os_error()
{
// scenario 2
if self.stream.is_priv() == true
{
break;
}
sleep(Duration::from_micros(1)).await;
}
else
{
// scenario 1
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"
))]
#[async_recursion]
async
fn vsyslog1(&mut self, mut pri: i32, fmt: &str)
{
// check for invalid bits
match check_invalid_bits(&mut pri)
{
Ok(_) => {},
Err(_e) => self.vsyslog1(get_internal_log(), fmt.as_ref()).await
}
// 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.is_none() == true
{
match portable::p_getprogname()
{
Some(r) => self.set_logtag(r),
None => self.set_logtag("")
}
}
let progname = self.logtag.as_ref().unwrap();
let msg_final =
if fmt.ends_with("\n") == true
{
truncate(fmt)
}
else
{
fmt
};
// 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();
// 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.is_connected() == true
{
// open connection
match self.connectlog()
{
Ok(_) => {},
Err(e) =>
{
self.send_to_stderr(unsafe { e.into_inner().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
{
match self.stream.send(&fullmsg).await
{
Ok(_) => return,
Err(err) =>
{
if let Some(libc::ENOBUFS) = err.raw_os_error()
{
// scenario 2
if self.stream.is_priv() == true
{
break;
}
sleep(Duration::from_micros(1)).await;
}
else
{
// scenario 1
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)};
}
}
}
}
/// A common instance which describes the syslog state
pub struct Syslog
{
/// A giant lock to synchronize the access to assets of the [SyslogInternal]
lock: Mutex<SyslogInternal>,
}
unsafe impl Send for Syslog {}
unsafe impl Sync for Syslog {}
#[async_trait]
impl SyslogStd for 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);
/// ```
async
fn openlog(
ident: Option<&str>,
logstat: LogStat,
facility: LogFacility
) -> SyRes<Self>
{
let mut inner =
SyslogInternal::new(
ident,
logstat,
facility,
None
);
if logstat.contains(LogStat::LOG_NDELAY) == true
{
inner.connectlog()?;
}
let ret =
Self
{
lock: Mutex::new(inner),
};
return Ok(ret);
}
/// Sets the logmask to filter out the syslog calls.
///
/// See macroses [LOG_MASK] and [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)
async
fn setlogmask(&self, logmask: i32) -> i32
{
return
self.lock
.lock()
.await
.set_logmask(logmask);
}
/// Similar to libc, closelog() will close the log
async
fn closelog(&self)
{
self.lock.lock().await.disconnectlog();
}
/// 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!()]
async
fn syslog(&self, pri: Priority, fmt: String)
{
self.lock
.lock()
.await
.vsyslog1(pri.bits(), fmt.as_str())
.await;
}
/// Similar to syslog() and created for the compatability.
async
fn vsyslog<S: AsRef<str> + Send>(&self, pri: Priority, fmt: S)
{
let f = fmt.as_ref();
self.lock
.lock()
.await
.vsyslog1(pri.bits(), f)
.await;
}
}
// --- NON STANDART API
#[async_trait]
impl SyslogExt for Syslog
{
/// NON STANDARD FUNCTION
///
/// This function acting like `openlog()` but allows to open connection to
/// the arbitrary object.
///
/// # Arguments
///
/// * @see `openlog()`
///
/// * `sock_path` - [AsRef] [Path] a path to the unix datagram socket
async
fn openlog_custom<P>(ident: Option<&str>, logstat: LogStat, facility: LogFacility, sock_path: P) -> SyRes<Self>
where P: AsRef<Path> + Send
{
let mut syslog =
SyslogInternal::new(ident, logstat, facility, Some(sock_path.as_ref()));
if logstat.contains(LogStat::LOG_NDELAY) == true
{
syslog.connectlog()?;
}
return Ok(
Self
{
lock: Mutex::new(syslog),
}
);
}
/// This function can be used to update the facility name, for example
/// after fork().
///
/// # Arguments
///
/// * `ident` - a new identity (up to 48 UTF8 chars)
async
fn change_identity<I: AsRef<str> + Send>(&self, ident: I)
{
self.lock.lock().await.set_logtag(ident);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_multithreading()
{
use std::sync::Arc;
use tokio::time::{sleep, Duration};
use std::time::{Instant};
let log =
Syslog::openlog(
Some("test1"),
LogStat::LOG_CONS | LogStat::LOG_NDELAY | LogStat::LOG_PID,
LogFacility::LOG_DAEMON).await;
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();
tokio::spawn( async move
{
for i in 0..5
{
let cc_c1_log = c1_log.clone();
sleep(Duration::from_nanos(200)).await;
tokio::spawn( async move
{
let m = format!("a message from thread 1 #{}[]", i);
let now = Instant::now();
cc_c1_log.syslog(Priority::LOG_DEBUG, m).await;
let elapsed = now.elapsed();
println!("t1: {:?}", elapsed);
});
}
}
);
tokio::spawn(async move
{
for i in 0..5
{
let cc_c2_log = c2_log.clone();
sleep(Duration::from_nanos(201)).await;
tokio::spawn( async move
{
let m = format!("сообщение от треда 2 №{}ХЪ", i);
let now = Instant::now();
cc_c2_log.vsyslog(Priority::LOG_DEBUG, m).await;
let elapsed = now.elapsed();
println!("t2: {:?}", elapsed);
});
}
});
let m = format!("A message from main, сообщение от главнюка");
let now = Instant::now();
log.syslog(Priority::LOG_DEBUG, m).await;
let elapsed = now.elapsed();
println!("main: {:?}", elapsed);
sleep(Duration::from_secs(2)).await;
log.closelog().await;
sleep(Duration::from_nanos(201)).await;
return;
}