diff --git a/Cargo.toml b/Cargo.toml index 86a49d4df2d43d6c84277c0f8260eab2d5184db3..a3a55acf43642daa1dfedf816cb3454ff4c3e31e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,7 +36,6 @@ linux = [ "xargs", "attr", "free", - "usleep", "which", "usleep", "column", @@ -56,7 +55,8 @@ linux = [ "mount", "umount", "arp", - "less" + "less", + "logger", ] ## # * bypass/override ~ translate 'test' feature name to avoid dependency collision with rust core 'test' crate (o/w surfaces as compiler errors during testing) @@ -77,7 +77,6 @@ members = [ "src/oe/xargs", "src/oe/attr", "src/oe/which", - "src/oe/usleep", "src/oe/free", "src/oe/usleep", "src/oe/column", @@ -97,7 +96,8 @@ members = [ "src/oe/mount", "src/oe/umount", "src/oe/arp", - "src/oe/less" + "src/oe/less", + "src/oe/logger", ] [dependencies] @@ -112,7 +112,7 @@ textwrap = { version="=0.16.1", features=["terminal_size"] } unicode-width = "=0.1.13" os_display = "=0.1.3" uucore = { version=">=0.0.16", package="uucore", path="src/uucore" } -zip = { version = "0.6.0", optional=true, default_features=false, features=["deflate"] } +zip = { version = "0.6.0", optional=true, default-features=false, features=["deflate"] } # * uutils base32 = { optional=true, version="0.0.16", package="oe_base32", path="src/oe/base32" } chage = { optional=true, version="0.0.1", package = "oe_chage", path = "src/oe/chage" } @@ -146,6 +146,8 @@ mount = { optional=true, version="0.0.1", package="oe_mount", path="src/oe/mount umount = { optional=true, version="0.0.1", package="oe_umount", path="src/oe/umount" } arp = { optional=true, version="0.0.1", package="oe_arp", path="src/oe/arp" } less = { optional=true, version="0.0.1", package="oe_less", path="src/oe/less" } +logger = { optional=true, version="0.0.1", package="oe_logger", path="src/oe/logger" } +hostname = "0.3.1" # this breaks clippy linting with: "tests/by-util/test_factor_benches.rs: No such file or directory (os error 2)" # factor_benches = { optional = true, version = "0.0.0", package = "uu_factor_benches", path = "tests/benches/factor" } @@ -177,6 +179,7 @@ nix = { version="0.27.1", features=["user"]} serial_test = "1.0.0" serde_json = "1.0" + [target.'cfg(any(target_os = "linux", target_os = "android"))'.dev-dependencies] procfs = { version = "0.14.0", default-features = false } rlimit = "0.8.3" diff --git a/ci/01-pre-commit.sh b/ci/01-pre-commit.sh index 78ac717286eaa7ea52ad17ffacb74d18abb456bd..058e51872d2cc996428ea0c42e79e11a963bea18 100755 --- a/ci/01-pre-commit.sh +++ b/ci/01-pre-commit.sh @@ -1,4 +1,4 @@ -#!/usr/bin/env -e bash +#!/usr/bin/env bash SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" source $SCRIPT_DIR/common_function diff --git a/ci/02-musl-build.sh b/ci/02-musl-build.sh index c675f7bd69ae4e8d946d4dfbf1e3ac1a178ddbb2..0bf8b96849c7b5751c6af5b0b004adc23d5eef51 100755 --- a/ci/02-musl-build.sh +++ b/ci/02-musl-build.sh @@ -16,4 +16,4 @@ rustup target add $arch-unknown-linux-musl export RUSTFLAGS="-C link-arg=-lm" cargo build --all --no-default-features --features "default" --target=$arch-unknown-linux-musl -#RUST_BACKTRACE=full RUSTFLAGS="-L /usr/$arch-linux-musl/lib64/libm.a" cargo test --all --all-targets --all-features --target=$arch-unknown-linux-musl -- --nocapture --test-threads=1 +# RUST_BACKTRACE=full RUSTFLAGS="-L /usr/$arch-linux-musl/lib64/libm.a" cargo test --all --all-targets --all-features --target=$arch-unknown-linux-musl -- --nocapture --test-threads=1 diff --git a/ci/codespell_ignore_words b/ci/codespell_ignore_words index f85b17a733f340588b40086a9a9bd517db439ebe..020ee47f2c8b8aec083fac1ceea990419cdd7202 100755 --- a/ci/codespell_ignore_words +++ b/ci/codespell_ignore_words @@ -8,4 +8,5 @@ ether chage cant unsupport +nd coreutil diff --git a/src/oe/logger/Cargo.toml b/src/oe/logger/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..2dca99300326f1c0135d72064be0df7dc73c4912 --- /dev/null +++ b/src/oe/logger/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "oe_logger" +version = "0.0.1" +authors = ["openeuler developers"] +license = "MulanPSL-2.0" +edition = "2021" + +[lib] +path = "src/logger.rs" + +[dependencies] +clap = { version = "3.2.0", features = ["wrap_help", "cargo"] } +time = { version = "0.3.44", features = ["macros", "formatting", "local-offset"] } +uucore = { version=">=0.0.16", package="uucore", path="../../uucore", features = ["encoding", "process", "entries"] } + +[[bin]] +name = "logger" +path = "src/main.rs" diff --git a/src/oe/logger/LICENSE b/src/oe/logger/LICENSE new file mode 100755 index 0000000000000000000000000000000000000000..ce048652004313b1fc67927f1037ac4896ad0f9a --- /dev/null +++ b/src/oe/logger/LICENSE @@ -0,0 +1,127 @@ + 木兰宽松许可证, 第2版 + + 木兰宽松许可证, 第2版 + 2020年1月 http://license.coscl.org.cn/MulanPSL2 + + + 您对“软件”的复制、使用、修改及分发受木兰宽松许可证,第2版(“本许可证”)的如下条款的约束: + + 0. 定义 + + “软件”是指由“贡献”构成的许可在“本许可证”下的程序和相关文档的集合。 + + “贡献”是指由任一“贡献者”许可在“本许可证”下的受版权法保护的作品。 + + “贡献者”是指将受版权法保护的作品许可在“本许可证”下的自然人或“法人实体”。 + + “法人实体”是指提交贡献的机构及其“关联实体”。 + + “关联实体”是指,对“本许可证”下的行为方而言,控制、受控制或与其共同受控制的机构,此处的控制是指有受控方或共同受控方至少50%直接或间接的投票权、资金或其他有价证券。 + + 1. 授予版权许可 + + 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的版权许可,您可以复制、使用、修改、分发其“贡献”,不论修改与否。 + + 2. 授予专利许可 + + 每个“贡献者”根据“本许可证”授予您永久性的、全球性的、免费的、非独占的、不可撤销的(根据本条规定撤销除外)专利许可,供您制造、委托制造、使用、许诺销售、销售、进口其“贡献”或以其他方式转移其“贡献”。前述专利许可仅限于“贡献者”现在或将来拥有或控制的其“贡献”本身或其“贡献”与许可“贡献”时的“软件”结合而将必然会侵犯的专利权利要求,不包括对“贡献”的修改或包含“贡献”的其他结合。如果您或您的“关联实体”直接或间接地,就“软件”或其中的“贡献”对任何人发起专利侵权诉讼(包括反诉或交叉诉讼)或其他专利维权行动,指控其侵犯专利权,则“本许可证”授予您对“软件”的专利许可自您提起诉讼或发起维权行动之日终止。 + + 3. 无商标许可 + + “本许可证”不提供对“贡献者”的商品名称、商标、服务标志或产品名称的商标许可,但您为满足第4条规定的声明义务而必须使用除外。 + + 4. 分发限制 + + 您可以在任何媒介中将“软件”以源程序形式或可执行形式重新分发,不论修改与否,但您必须向接收者提供“本许可证”的副本,并保留“软件”中的版权、商标、专利及免责声明。 + + 5. 免责声明与责任限制 + + “软件”及其中的“贡献”在提供时不带任何明示或默示的担保。在任何情况下,“贡献者”或版权所有者不对任何人因使用“软件”或其中的“贡献”而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。 + + 6. 语言 + “本许可证”以中英文双语表述,中英文版本具有同等法律效力。如果中英文版本存在任何冲突不一致,以中文版为准。 + + 条款结束 + + 如何将木兰宽松许可证,第2版,应用到您的软件 + + 如果您希望将木兰宽松许可证,第2版,应用到您的新软件,为了方便接收者查阅,建议您完成如下三步: + + 1, 请您补充如下声明中的空白,包括软件名、软件的首次发表年份以及您作为版权人的名字; + + 2, 请您在软件包的一级目录下创建以“LICENSE”为名的文件,将整个许可证文本放入该文件中; + + 3, 请将如下声明文本放入每个源文件的头部注释中。 + + Copyright (c) 2025 Sun Yuhang + [logger] is licensed under Mulan PSL v2. + You can use this software according to the terms and conditions of the Mulan PSL v2. + You may obtain a copy of Mulan PSL v2 at: + http://license.coscl.org.cn/MulanPSL2 + THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + See the Mulan PSL v2 for more details. + + + Mulan Permissive Software License,Version 2 + + Mulan Permissive Software License,Version 2 (Mulan PSL v2) + January 2020 http://license.coscl.org.cn/MulanPSL2 + + Your reproduction, use, modification and distribution of the Software shall be subject to Mulan PSL v2 (this License) with the following terms and conditions: + + 0. Definition + + Software means the program and related documents which are licensed under this License and comprise all Contribution(s). + + Contribution means the copyrightable work licensed by a particular Contributor under this License. + + Contributor means the Individual or Legal Entity who licenses its copyrightable work under this License. + + Legal Entity means the entity making a Contribution and all its Affiliates. + + Affiliates means entities that control, are controlled by, or are under common control with the acting entity under this License, ‘control’ means direct or indirect ownership of at least fifty percent (50%) of the voting power, capital or other securities of controlled or commonly controlled entity. + + 1. Grant of Copyright License + + Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable copyright license to reproduce, use, modify, or distribute its Contribution, with modification or not. + + 2. Grant of Patent License + + Subject to the terms and conditions of this License, each Contributor hereby grants to you a perpetual, worldwide, royalty-free, non-exclusive, irrevocable (except for revocation under this Section) patent license to make, have made, use, offer for sale, sell, import or otherwise transfer its Contribution, where such patent license is only limited to the patent claims owned or controlled by such Contributor now or in future which will be necessarily infringed by its Contribution alone, or by combination of the Contribution with the Software to which the Contribution was contributed. The patent license shall not apply to any modification of the Contribution, and any other combination which includes the Contribution. If you or your Affiliates directly or indirectly institute patent litigation (including a cross claim or counterclaim in a litigation) or other patent enforcement activities against any individual or entity by alleging that the Software or any Contribution in it infringes patents, then any patent license granted to you under this License for the Software shall terminate as of the date such litigation or activity is filed or taken. + + 3. No Trademark License + + No trademark license is granted to use the trade names, trademarks, service marks, or product names of Contributor, except as required to fulfill notice requirements in Section 4. + + 4. Distribution Restriction + + You may distribute the Software in any medium with or without modification, whether in source or executable forms, provided that you provide recipients with a copy of this License and retain copyright, patent, trademark and disclaimer statements in the Software. + + 5. Disclaimer of Warranty and Limitation of Liability + + THE SOFTWARE AND CONTRIBUTION IN IT ARE PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED. IN NO EVENT SHALL ANY CONTRIBUTOR OR COPYRIGHT HOLDER BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE SOFTWARE OR THE CONTRIBUTION IN IT, NO MATTER HOW IT’S CAUSED OR BASED ON WHICH LEGAL THEORY, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + 6. Language + + THIS LICENSE IS WRITTEN IN BOTH CHINESE AND ENGLISH, AND THE CHINESE VERSION AND ENGLISH VERSION SHALL HAVE THE SAME LEGAL EFFECT. IN THE CASE OF DIVERGENCE BETWEEN THE CHINESE AND ENGLISH VERSIONS, THE CHINESE VERSION SHALL PREVAIL. + + END OF THE TERMS AND CONDITIONS + + How to Apply the Mulan Permissive Software License,Version 2 (Mulan PSL v2) to Your Software + + To apply the Mulan PSL v2 to your work, for easy identification by recipients, you are suggested to complete following three steps: + + i Fill in the blanks in following statement, including insert your software name, the year of the first publication of your software, and your name identified as the copyright owner; + + ii Create a file named “LICENSE” which contains the whole context of this License in the first directory of your software package; + + iii Attach the statement to the appropriate annotated syntax at the beginning of each source file. + + + Copyright (c) 2025 Sun Yuhang + [logger] is licensed under Mulan PSL v2. + You can use this software according to the terms and conditions of the Mulan PSL v2. + You may obtain a copy of Mulan PSL v2 at: + http://license.coscl.org.cn/MulanPSL2 + THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. + See the Mulan PSL v2 for more details. diff --git a/src/oe/logger/logger.md b/src/oe/logger/logger.md new file mode 100644 index 0000000000000000000000000000000000000000..dc6ff2b9cbc2a76e2aad66cdf45f83b938a65570 --- /dev/null +++ b/src/oe/logger/logger.md @@ -0,0 +1,40 @@ +# logger + +## Usage +``` +logger [options] [] +``` + +## About + +Enter messages into the system log. + +## Options + -i log the logger command's PID + --id[=] log the given , or otherwise the PID + -f, --file log the contents of this file + -e, --skip-empty do not log empty lines when processing files + --no-act do everything except the write the log + -p, --priority mark given message with this priority + --octet-count use rfc6587 octet counting + --prio-prefix look for a prefix on every line read from stdin + -s, --stderr output message to standard error as well + -S, --size maximum size for a single message + -t, --tag mark every line with this tag + -n, --server write to this remote syslog server + -P, --port use this port for UDP or TCP connection + -T, --tcp use TCP only + -d, --udp use UDP only + --rfc3164 use the obsolete BSD syslog protocol + --rfc5424[=] use the syslog protocol (the default for remote); + can be notime, or notq, and/or nohost + --sd-id rfc5424 structured data ID + --sd-param rfc5424 structured data name=value + --msgid set rfc5424 message id field + -u, --socket write to this Unix socket + --socket-errors[=] + print connection errors when using Unix sockets + --journald[=] write journald entry + + -h, --help display this help + -V, --version display version diff --git a/src/oe/logger/src/logger.rs b/src/oe/logger/src/logger.rs new file mode 100644 index 0000000000000000000000000000000000000000..c7407049170ee680f3c590b5e592a21a927d0ba9 --- /dev/null +++ b/src/oe/logger/src/logger.rs @@ -0,0 +1,63 @@ +// Copyright (c) 2025 Sun Yuhang +// [logger] is licensed under Mulan PSL v2. +// You can use this software according to the terms and conditions of the Mulan PSL v2. +// You may obtain a copy of Mulan PSL v2 at: +// http://license.coscl.org.cn/MulanPSL2 +// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. +// See the Mulan PSL v2 for more details. + +//! # oe_logger +use clap::Command; +use std::io; +use uucore::{error::UResult, help_section, help_usage}; + +/// Command-line parsing and I/O helpers used by the `logger` utility. +pub mod logger_common; + +/// Syslog header generators (local/RFC3164/RFC5424). +pub mod syslog_header; + +const ABOUT: &str = help_section!("about", "logger.md"); +const USAGE: &str = help_usage!("logger.md"); + +#[uucore::main] +pub fn oemain(args: impl uucore::Args) -> UResult<()> { + let mut cfg: logger_common::Config = logger_common::parse_logger_cmd_args(args, ABOUT, USAGE)?; + + if cfg.journald_path.is_some() { + match logger_common::journald_entry(&cfg) { + Ok(()) => return Ok(()), + Err(_e) => { + eprintln!( + "{}: {}", + logger_common::progname(), + "journald entry could not be written" + ); + eprintln!("hello"); + std::process::exit(1); + } + } + } + + logger_common::logger_open(&mut cfg); + + let res: io::Result<()> = if cfg.inline_msg.is_some() { + syslog_header::generate_syslog_header(&mut cfg); + // println!("before hdr:{:?}", cfg.hdr); + logger_common::logger_command_line(&mut cfg) + } else { + logger_common::logger_stdin(&mut cfg) + }; + + match res { + Ok(()) => Ok(()), + Err(_e) => { + std::process::exit(1); + } + } +} + +/// Build the clap `Command` for this app (used by tests and integration code). +pub fn oe_app<'a>() -> Command<'a> { + logger_common::logger_app(ABOUT, USAGE) +} diff --git a/src/oe/logger/src/logger_common.rs b/src/oe/logger/src/logger_common.rs new file mode 100644 index 0000000000000000000000000000000000000000..a1274a1736767812239f7bf9d925a2801d43579d --- /dev/null +++ b/src/oe/logger/src/logger_common.rs @@ -0,0 +1,1709 @@ +// Copyright (c) 2025 Sun Yuhang +// [logger] is licensed under Mulan PSL v2. +// You can use this software according to the terms and conditions of the Mulan PSL v2. +// You may obtain a copy of Mulan PSL v2 at: +// http://license.coscl.org.cn/MulanPSL2 +// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. +// See the Mulan PSL v2 for more details. + +//! Core command-line parsing, config model, and I/O for the logger. + +use crate::syslog_header::{syslog_local_header, syslog_rfc3164_header, syslog_rfc5424_header}; +use clap::{crate_version, Arg, ArgMatches, Command}; +use std::collections::HashSet; +use std::fs::File; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::net::{TcpStream, ToSocketAddrs, UdpSocket}; +use std::os::unix::net::{UnixDatagram, UnixStream}; +use std::path::{Path, PathBuf}; +use std::time::Duration; +use uucore::display::Quotable; +use uucore::error::{UResult, USimpleError, UUsageError}; +use uucore::format_usage; +use uucore::entries::uid2usr; +use uucore::process::geteuid; +const LOG_FACMASK: u16 = 0x03f8; + +/// Function pointer type for syslog header generators. +/// +/// The function mutates `Config.hdr` with the formatted header. +pub type SyslogHeaderFn = fn(&mut Config); +// pub type SyslogHeaderFn = for<'r> fn(&'r mut Config); +/// Selected process identifier that will appear in the tag. +#[derive(Debug, Clone)] +pub enum LogId { + /// Use the process ID of the running logger. + Pid, + /// Use the explicit numeric id provided by the user. + Explicit(String), +} + +/// How to report socket connection errors when using Unix sockets. +#[derive(Debug, Clone, Copy)] +pub enum SocketErrorsMode { + /// Always print the error and return an error. + On, + /// Do not print the error; succeed silently. + Off, + /// Print the error but do not fail the command. + Auto, +} + +/// RFC5424 header trimming options (applied when `--rfc5424[=]` is used). +#[derive(Debug, Clone)] +pub struct Rfc5424Snip { + /// If true, omit the timestamp field, and do not inject `timeQuality`. + pub notime: bool, + /// If true, do not auto-inject `timeQuality` structured data. + pub notq: bool, + /// If true, omit the hostname field. + pub nohost: bool, +} + +/// Which syslog header type to generate. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SyslogHeaderKind { + /// Local format: RFC3164 style without hostname. + Local, + /// RFC3164 format. + Rfc3164, + /// RFC5424 format. + Rfc5424, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum LocalSockMode { + Auto, + DatagramOnly, + StreamOnly, +} + +#[derive(Debug, Clone, Copy)] +enum NetProto { + Udp, + Tcp, +} + +#[derive(Debug, Clone)] +enum SdTok { + /// A structured data element ID (e.g. `meta` or `example@32473`). + Id(String), + /// A `name="value"` parameter belonging to the last seen ID. + Param(String, String), +} + +#[derive(Debug, Clone, Default)] +struct SdElem { + id: String, + params: Vec<(String, String)>, +} + +fn net_effective_proto(cfg: &Config) -> NetProto { + if cfg.use_tcp { + NetProto::Tcp + } else { + NetProto::Udp + } +} + +fn net_default_port(p: NetProto) -> u16 { + match p { + NetProto::Udp => 514, + NetProto::Tcp => 601, + } +} + +fn net_effective_port(cfg: &Config, p: NetProto) -> u16 { + cfg.port.unwrap_or_else(|| net_default_port(p)) +} + +fn choose_local_mode(cfg: &Config) -> LocalSockMode { + if cfg.use_tcp { + LocalSockMode::StreamOnly + } else if cfg.use_udp { + LocalSockMode::DatagramOnly + } else { + LocalSockMode::Auto + } +} + +pub fn username() -> io::Result { + uid2usr(geteuid()).map(Into::into) +} + +/// Long option and flag names used by the clap `Command`. +pub mod options { + /// `-i`: log the logger command's PID. + pub static PID_FLAG: &str = "i"; + /// `--id[=]`: log an explicit id or fallback to PID when value is missing. + pub static ID: &str = "id"; + /// `-f, --file `: read input from file. + pub static FILE: &str = "file"; + /// `-e, --skip-empty`: ignore empty lines when processing files/stdin. + pub static SKIP_EMPTY: &str = "skip-empty"; + /// `--no-act`: do everything except the actual write. + pub static NO_ACT: &str = "no-act"; + /// `-p, --priority `: set the message facility/level. + pub static PRIORITY: &str = "priority"; + /// `--octet-count`: TCP RFC6587 octet counting. + pub static OCTET_COUNT: &str = "octet-count"; + /// `--prio-prefix`: parse `` prefix per-line from stdin/file. + pub static PRIO_PREFIX: &str = "prio-prefix"; + /// `-s, --stderr`: mirror sent payload to stderr. + pub static STDERR: &str = "stderr"; + /// `-S, --size `: maximum size for a single message body. + pub static SIZE: &str = "size"; + /// `-t, --tag `: tag/app-name for the message. + pub static TAG: &str = "tag"; + /// `-n, --server `: remote syslog server host/IP. + pub static SERVER: &str = "server"; + /// `-P, --port `: remote port; defaults to 514 (UDP) or 601 (TCP). + pub static PORT: &str = "port"; + /// `-T, --tcp`: force TCP transport. + pub static TCP: &str = "tcp"; + /// `-d, --udp`: force UDP transport. + pub static UDP: &str = "udp"; + /// `--rfc3164`: use RFC3164 header format. + pub static RFC3164: &str = "rfc3164"; + /// `--rfc5424[=]`: use RFC5424 header format; `snip` can be `notime`, `notq`, `nohost`. + pub static RFC5424: &str = "rfc5424"; + /// `--sd-id `: RFC5424 structured data element ID (repeatable). + pub static SD_ID: &str = "sd-id"; + /// `--sd-param name="value"`: RFC5424 structured data parameter (repeatable). + pub static SD_PARAM: &str = "sd-param"; + /// `--msgid `: RFC5424 MSGID field. + pub static MSGID: &str = "msgid"; + /// `-u, --socket `: Unix datagram/stream socket to write to. + pub static SOCKET: &str = "socket"; + /// `--socket-errors[=on|off|auto]`: how to handle socket errors. + pub static SOCKET_ERRORS: &str = "socket-errors"; + /// `--journald[=]`: write a journald native entry from key=value lines. + pub static JOURNALD: &str = "journald"; + /// Positional message (hidden in clap usage). + pub static MESSAGE: &str = "message"; +} + +/// Parsed configuration for one invocation of the logger. +#[derive(Debug, Clone)] +pub struct Config { + /// Process id selection (`-i`, `--id`). + pub log_id: Option, + /// Input file to read from (`-f/--file`); otherwise stdin. + pub file: Option, + /// Skip empty lines when reading from stdin/file (`-e`). + pub skip_empty: bool, + /// Do not actually write; only preview to stderr if requested. + pub no_act: bool, + /// Raw priority string provided via `-p/--priority`. + pub priority: Option, + /// Use RFC6587 octet counting on TCP. + pub octet_count: bool, + /// Parse `` prefix on each line when reading stdin/file. + pub prio_prefix: bool, + /// Numeric composed priority (facility<<3|level) used for header ``. + pub pri: u8, + /// Mirror final payload to stderr (`-s`). + pub stderr: bool, + /// Maximum message body size (in bytes). + pub size: usize, + /// Tag/app-name. + pub tag: Option, + /// Remote server hostname/IP. + pub server: Option, + /// Remote port if specified. + pub port: Option, + /// Force TCP (`-T`). + pub use_tcp: bool, + /// Force UDP (`-d`). + pub use_udp: bool, + /// Force RFC3164 header. + pub rfc3164: bool, + /// RFC5424 options (`--rfc5424[=]`). + pub rfc5424: Option, + /// Final structured data string (pre-rendered). + pub structured_user: Option, + /// RFC5424 MSGID value. + pub msgid: Option, + /// Explicit Unix socket path (`-u/--socket`). + pub socket: Option, + /// How to handle socket errors (on/off/auto). + pub socket_errors: Option, + /// Journald input file path or `-` for stdin. + pub journald_path: Option, + /// Collected positional message arguments (before join). + pub inline_args: Option>, + /// Joined positional message string (for convenience). + pub inline_msg: Option, + /// Selected header generator. + pub syslogfp: Option, + /// Generated header prefix (set by header generator). + pub hdr: Option, +} + +impl Config { + /// Build `Config` from clap matches. Performs semantic validation, + /// computes defaults, and prepares structured data. + pub fn from_matches(m: &ArgMatches) -> UResult { + // ... unchanged logic ... + // (full body kept as in your source; only documentation added) + // The full function body continues below: + let log_id: Option = if m.is_present(options::ID) { + match m.value_of(options::ID) { + None | Some("") | Some("__PID__") => Some(LogId::Pid), + Some(raw) => { + let ltrim = raw.trim_start(); + let ok = !ltrim.is_empty() && ltrim.chars().all(|c| c.is_ascii_digit()); + if ok { + Some(LogId::Explicit(ltrim.to_string())) + } else { + eprintln!("{}: failed to parse id: '{}'", progname(), raw); + std::process::exit(1); + } + } + } + } else if m.is_present(options::PID_FLAG) { + Some(LogId::Pid) + } else { + None + }; + + let mut file = m.get_one::(options::FILE).map(PathBuf::from); + let inline_args = m + .get_many::(options::MESSAGE) + .map(|it| it.cloned().collect::>()); + let inline_msg = inline_args.as_ref().map(|v| v.join(" ")); + + if file.is_some() && inline_msg.is_some() { + eprintln!( + "{}: --file and are mutually exclusive, message is ignored", + progname() + ); + file = None; + } + if let Some(ref p) = file { + if !Path::new(p).exists() { + return Err(USimpleError::new( + 1, + format!("{}: No such file or directory", p.maybe_quote()), + )); + } + } + + let (priority_raw, pri_val) = match m.get_one::(options::PRIORITY) { + Some(s) => match parse_priority_for_p(s) { + Ok(v) => (Some(s.clone()), v), + Err(msg) => { + eprintln!("{}: {}", progname(), msg); + std::process::exit(1); + } + }, + None => (None, (1 << 3) | 5), // user.notice = 13 + }; + + let size = match m + .value_of(options::SIZE) + .or_else(|| m.get_one::(options::SIZE).map(|s| s.as_str())) + { + Some(s) => { + let n: isize = s.parse().map_err(|_| { + USimpleError::new( + 1, + format!( + "failed to parse message size: {}: Invalid argument", + s.quote() + ), + ) + })?; + if n < 0 { + return Err(USimpleError::new( + 1, + format!( + "failed to parse message size: {}: Invalid argument", + s.quote() + ), + )); + } + n as usize + } + None => 1024, + }; + + let port = match m.get_one::(options::PORT) { + Some(p) => Some( + p.parse::() + .map_err(|_| USimpleError::new(1, format!("invalid port: {}", p.quote())))?, + ), + None => None, + }; + + let syslogfp = if m.contains_id("rfc3164") { + Some(syslog_rfc3164_header as SyslogHeaderFn) + } else if m.contains_id("rfc5424") { + Some(syslog_rfc5424_header as SyslogHeaderFn) + } else { + None + }; + + let rfc5424 = if m.occurrences_of("rfc5424") > 0 { + let mut snip = Rfc5424Snip { + notime: false, + notq: false, + nohost: false, + }; + if let Some(s) = m.get_one::(options::RFC5424) { + for part in s.split(',').map(|x| x.trim()).filter(|x| !x.is_empty()) { + match part { + "notime" => { + snip.notime = true; + snip.notq = true; + } + "notq" => snip.notq = true, + "nohost" => snip.nohost = true, + other => { + return Err(USimpleError::new( + 1, + format!("invalid rfc5424 option: {}", other.quote()), + )) + } + } + } + } + Some(snip) + } else { + None + }; + + let sd_stream = collect_sd_stream(&m)?; + let sd_elems = bind_sd(&sd_stream)?; + let sd_elems = prune_empty_sd_elems(sd_elems); + let sd_final = maybe_inject_time_quality(sd_elems, rfc5424.as_ref()); + let user_structured = if sd_final.is_empty() { + None + } else { + Some(render_sd(&sd_final)) + }; + + let msgid_opt = m.get_one::(options::MSGID).map(|s| s.as_str()); + let msgid = validate_msgid(msgid_opt); + + let socket_path: Option = m + .get_one::(options::SOCKET) + .map(|s| PathBuf::from(s)); + let socket_errors = if let Some(s) = m.get_one::(options::SOCKET_ERRORS) { + Some(match s.as_str() { + "on" => SocketErrorsMode::On, + "off" => SocketErrorsMode::Off, + _ => SocketErrorsMode::Auto, + }) + } else if m.occurrences_of("socket-errors") > 0 { + Some(SocketErrorsMode::Auto) + } else { + None + }; + + let journald_path = if m.contains_id(options::JOURNALD) { + m.get_one::(options::JOURNALD) + .map(|s| PathBuf::from(s)) + } else { + None + }; + + if m.contains_id("udp") && m.contains_id("tcp") { + return Err(UUsageError::new(1, "cannot use --udp and --tcp together")); + } + if m.contains_id("server") && m.contains_id("socket") { + return Err(UUsageError::new(1, "cannot combine --server with --socket")); + } + + Ok(Self { + log_id, + file, + skip_empty: m.contains_id("skip-empty"), + no_act: m.contains_id("no-act"), + priority: priority_raw, + pri: pri_val, + octet_count: m.contains_id("octet-count"), + prio_prefix: m.contains_id("prio-prefix"), + stderr: m.contains_id("stderr"), + size, + tag: m.get_one::(options::TAG).cloned(), + server: m.get_one::(options::SERVER).cloned(), + port, + use_tcp: m.contains_id("tcp"), + use_udp: m.contains_id("udp"), + rfc3164: m.contains_id("rfc3164"), + rfc5424, + structured_user: user_structured, + msgid, + socket: socket_path, + socket_errors, + journald_path, + inline_args, + inline_msg, + syslogfp, + hdr: None, + }) + } +} + +fn prune_empty_sd_elems(elems: Vec) -> Vec { + elems.into_iter().filter(|e| !e.params.is_empty()).collect() +} + +fn collect_sd_stream(m: &clap::ArgMatches) -> UResult> { + let mut toks: Vec<(usize, SdTok)> = Vec::new(); + + if let (Some(pos), Some(vals)) = (m.indices_of("sd-id"), m.get_many::("sd-id")) { + for (i, v) in pos.zip(vals) { + validate_sd_id(v)?; + toks.push((i, SdTok::Id(v.clone()))); + } + } + + if let (Some(pos), Some(vals)) = (m.indices_of("sd-param"), m.get_many::("sd-param")) { + for (i, raw) in pos.zip(vals) { + let (k, v) = parse_sd_param(raw)?; + toks.push((i, SdTok::Param(k, v))); + } + } + + toks.sort_by_key(|(i, _)| *i); + Ok(toks.into_iter().map(|(_, t)| t).collect()) +} + +fn bind_sd(stream: &[SdTok]) -> UResult> { + let mut out: Vec = Vec::new(); + let mut cur: Option = None; + + for tok in stream { + match tok { + SdTok::Id(id) => { + out.push(SdElem { + id: id.clone(), + params: Vec::new(), + }); + cur = Some(out.len() - 1); + } + SdTok::Param(k, v) => { + let Some(ix) = cur else { + return Err(USimpleError::new( + 1, + String::from("--sd-param requires at least one preceding --sd-id"), + )); + }; + out[ix].params.push((k.clone(), v.clone())); + } + } + } + Ok(out) +} + +fn render_sd(elems: &[SdElem]) -> String { + let mut s = String::new(); + for e in elems { + s.push('['); + s.push_str(&e.id); + for (k, v) in &e.params { + s.push(' '); + s.push_str(k); + s.push_str("=\""); + s.push_str(&esc_val(v)); + s.push('"'); + } + s.push(']'); + } + s +} + +fn maybe_inject_time_quality(mut elems: Vec, rfc5424: Option<&Rfc5424Snip>) -> Vec { + let Some(snip) = rfc5424 else { + return elems; + }; + + if snip.notime || snip.notq { + return elems; + } + + if elems.iter().any(|e| e.id == "timeQuality") { + return elems; + } + + elems.insert( + 0, + SdElem { + id: "timeQuality".into(), + params: vec![ + ("tzKnown".into(), "1".into()), + ("isSynced".into(), "0".into()), + ], + }, + ); + elems +} + +fn is_valid_name(name: &str) -> bool { + let len = name.len(); + if len == 0 || len > 32 { + return false; + } + name.bytes() + .all(|b| (0x21..=0x7e).contains(&b) && b != b'=' && b != b'"' && b != b']' && b != b' ') +} + +fn validate_sd_id(id: &str) -> UResult<()> { + if let Some((left, right)) = id.split_once('@') { + if !is_valid_name(left) || right.is_empty() || !right.chars().all(|c| c.is_ascii_digit()) { + return Err(USimpleError::new( + 1, + format!("invalid structured data ID: '{id}'"), + )); + } + } else if !is_valid_name(id) { + return Err(USimpleError::new( + 1, + format!("invalid structured data ID: '{id}'"), + )); + } + Ok(()) +} + +fn parse_sd_param(raw: &str) -> UResult<(String, String)> { + let (k, v0) = raw.split_once('=').ok_or_else(|| { + USimpleError::new(1, format!("invalid structured data parameter: '{raw}'")) + })?; + + if !is_valid_name(k) { + return Err(USimpleError::new( + 1, + format!("invalid structured data parameter: '{raw}'"), + )); + } + + let v0 = v0.trim(); + if !(v0.starts_with('"') && v0.ends_with('"') && v0.len() >= 2) { + return Err(USimpleError::new( + 1, + format!("invalid structured data parameter: '{raw}'"), + )); + } + + let inner = &v0[1..v0.len() - 1]; + let mut out = String::with_capacity(inner.len()); + let mut it = inner.chars(); + while let Some(c) = it.next() { + if c == '\\' { + match it.next() { + Some('"') => out.push('"'), + Some('\\') => out.push('\\'), + Some(']') => out.push(']'), + _ => { + return Err(USimpleError::new( + 1, + format!("invalid structured data parameter: '{raw}'"), + )) + } + } + } else if c == '"' { + return Err(USimpleError::new( + 1, + format!("invalid structured data parameter: '{raw}'"), + )); + } else { + out.push(c); + } + } + + Ok((k.to_string(), out)) +} + +fn esc_val(s: &str) -> String { + s.replace('\\', "\\\\") + .replace('"', "\\\"") + .replace(']', "\\]") +} + +/// Best-effort program name extracted from argv[0]. +pub fn progname() -> String { + "logger".to_owned() +} + +fn validate_msgid(raw: Option<&str>) -> Option { + match raw { + None => None, + Some(s) => { + if s.is_empty() { + return None; + } + if s.chars().any(|c| c.is_ascii_whitespace()) { + eprintln!("{}: --msgid cannot contain space", progname()); + std::process::exit(1); + } + Some(s.to_string()) + } + } +} + +/// Parse a `-p/--priority` token into a numeric `PRIO` (facility<<3 | level). +/// +/// Examples: +/// - `user.info` +/// - `kern.emerg` +/// - `13` (invalid: numeric must be level-only 0..7; prefer `user.notice`) +pub fn parse_priority_for_p(s: &str) -> Result { + // ... unchanged logic ... + fn sev(x: &str) -> Option { + if let Ok(n) = x.parse::() { + return (n <= 7).then_some(n); + } + Some(match x { + "emerg" | "panic" => 0, + "alert" => 1, + "crit" => 2, + "err" | "error" => 3, + "warning" | "warn" => 4, + "notice" => 5, + "info" => 6, + "debug" => 7, + _ => return None, + }) + } + fn fac_name(x: &str) -> Option { + Some(match x { + "kern" => 0, + "user" => 1, + "mail" => 2, + "daemon" => 3, + "auth" | "security" => 4, + "syslog" => 5, + "lpr" => 6, + "news" => 7, + "uucp" => 8, + "cron" => 9, + "authpriv" => 10, + "ftp" => 11, + "local0" => 16, + "local1" => 17, + "local2" => 18, + "local3" => 19, + "local4" => 20, + "local5" => 21, + "local6" => 22, + "local7" => 23, + _ => return None, + }) + } + fn fac_token(x: &str) -> Option { + if let Some(f) = fac_name(x) { + return Some(f); + } + if let Ok(n) = x.parse::() { + if n % 8 == 0 && n <= 23 * 8 { + return Some((n / 8) as u8); + } + } + None + } + + let s_trim = s.trim(); + + if let Some((f_raw, l_raw)) = s_trim.split_once('.') { + let f_tok = f_raw.trim(); + let l_tok = l_raw.trim(); + let f_lc = f_tok.to_ascii_lowercase(); + let l_lc = l_tok.to_ascii_lowercase(); + + let mut fac = + fac_token(&f_lc).ok_or_else(|| format!("unknown facility name: {}", f_tok))?; + let sev = sev(&l_lc).ok_or_else(|| format!("unknown priority name: {}", l_tok))?; + + if fac == 0 { + fac = 1; + } + + return Ok((fac << 3) | sev); + } + + let w_lc = s_trim.to_ascii_lowercase(); + if let Some(level) = sev(&w_lc) { + return Ok((1 << 3) | level); // user.level + } + + if w_lc.chars().all(|c| c.is_ascii_digit()) { + return Err(format!("unknown priority name: {}", s_trim)); + } + + Err(format!("unknown priority name: {}", s_trim)) +} + +fn normalize_single_dash_longs(mut args: Vec) -> Vec { + if args.is_empty() { + return args; + } + + let known_longs: HashSet<&'static str> = HashSet::from([ + "id", + "file", + "skip-empty", + "no-act", + "priority", + "octet-count", + "prio-prefix", + "stderr", + "size", + "tag", + "server", + "port", + "tcp", + "udp", + "rfc3164", + "rfc5424", + "sd-id", + "sd-param", + "msgid", + "socket", + "socket-errors", + "journald", + ]); + + for i in 1..args.len() { + let s = &args[i]; + if !s.starts_with('-') || s.starts_with("--") { + continue; + } + if s == "-" { + continue; + } + if s.len() == 2 { + continue; + } + + let body = &s[1..]; + let (name, rest) = match body.split_once('=') { + Some((n, r)) => (n, Some(r)), + None => (body, None), + }; + + if known_longs.contains(name) { + let mut replaced = String::with_capacity(s.len() + 1); + replaced.push_str("--"); + replaced.push_str(name); + if let Some(r) = rest { + replaced.push('='); + replaced.push_str(r); + } + args[i] = replaced; + } + } + args +} + +/// Build `Config` from process args and help text; used by main and tests. +pub fn parse_logger_cmd_args(args: impl uucore::Args, about: &str, usage: &str) -> UResult { + let command = logger_app(about, usage); + let mut arg_list = args.collect_lossy(); + arg_list = normalize_single_dash_longs(arg_list); + Config::from_matches(&command.try_get_matches_from(arg_list)?) +} + +/// Build the clap `Command` including all options and help text. +pub fn logger_app<'a>(about: &'a str, usage: &'a str) -> Command<'a> { + Command::new(uucore::util_name()) + .version(crate_version!()) + .about(about) + .infer_long_args(true) + .override_usage(format_usage(usage)) + // (args definition unchanged) + .arg( + Arg::new(options::PID_FLAG) + .short('i') + .help("log the logger command's PID") + .takes_value(false) + .display_order(1), + ) + .arg( + Arg::new(options::ID) + .long("id") + .help("log the given , or otherwise the PID") + .max_values(1) + .min_values(0) + .value_name("ID") + .require_equals(true) + .default_missing_value("__PID__") + .display_order(2), + ) + .arg( + Arg::new(options::FILE) + .short('f') + .long(options::FILE) + .takes_value(true) + .value_name("file") + .value_hint(clap::ValueHint::FilePath) + .help("log the contents of this file") + .display_order(3), + ) + .arg( + Arg::new(options::SKIP_EMPTY) + .short('e') + .long(options::SKIP_EMPTY) + .help("do not log empty lines when processing files") + .display_order(4), + ) + .arg( + Arg::new(options::NO_ACT) + .long(options::NO_ACT) + .help("do everything except the write the log") + .display_order(5), + ) + .arg( + Arg::new(options::PRIORITY) + .short('p') + .long(options::PRIORITY) + .takes_value(true) + .value_name("prio") + .help("mark given message with this priority") + .display_order(6), + ) + .arg( + Arg::new(options::OCTET_COUNT) + .long(options::OCTET_COUNT) + .help("use rfc6587 octet counting") + .display_order(7), + ) + .arg( + Arg::new(options::PRIO_PREFIX) + .long(options::PRIO_PREFIX) + .help("look for a prefix on every buf read from stdin") + .display_order(8), + ) + .arg( + Arg::new(options::STDERR) + .short('s') + .long(options::STDERR) + .takes_value(false) + .help("output message to standard error as well") + .multiple_occurrences(true) + .display_order(9), + ) + .arg( + Arg::new(options::SIZE) + .short('S') + .long(options::SIZE) + .takes_value(true) + .value_name("size") + .help("maximum size for a single message") + .allow_hyphen_values(true) + .display_order(10), + ) + .arg( + Arg::new(options::TAG) + .short('t') + .long(options::TAG) + .takes_value(true) + .value_name("tag") + .help("mark every buf with this tag") + .display_order(11), + ) + .arg( + Arg::new(options::SERVER) + .short('n') + .long(options::SERVER) + .takes_value(true) + .value_name("name") + .conflicts_with(options::SOCKET) + .help("write to this remote syslog server") + .display_order(12), + ) + .arg( + Arg::new(options::PORT) + .short('P') + .long(options::PORT) + .takes_value(true) + .value_name("port") + .help("use this port for UDP or TCP connection") + .display_order(13), + ) + .arg( + Arg::new(options::TCP) + .short('T') + .long(options::TCP) + .conflicts_with(options::UDP) + .help("use TCP only") + .display_order(14), + ) + .arg( + Arg::new(options::UDP) + .short('d') + .long(options::UDP) + .conflicts_with(options::TCP) + .help("use UDP only") + .display_order(15), + ) + .arg( + Arg::new(options::RFC3164) + .long(options::RFC3164) + .help("use the obsolete BSD syslog protocol") + .display_order(16), + ) + .arg( + Arg::new(options::RFC5424) + .long(options::RFC5424) + .require_equals(true) + .takes_value(true) + .min_values(0) + .max_values(1) + .value_name("snip") + .help( + "use the syslog protocol (the default for remote); can be notime, or notq, and/or nohost", + ) + .display_order(17), + ) + .arg( + Arg::new(options::SD_ID) + .long(options::SD_ID) + .takes_value(true) + .action(clap::ArgAction::Append) + .multiple_occurrences(true) + .value_name("id") + .help("rfc5424 structured data ID") + .display_order(18), + ) + .arg( + Arg::new(options::SD_PARAM) + .long(options::SD_PARAM) + .takes_value(true) + .multiple_occurrences(true) + .value_name("name=value") + .action(clap::ArgAction::Append) + .help("rfc5424 structured data name=value") + .display_order(19), + ) + .arg( + Arg::new(options::MSGID) + .long(options::MSGID) + .takes_value(true) + .value_name("msgid") + .help("set rfc5424 message id field") + .display_order(20), + ) + .arg( + Arg::new(options::SOCKET) + .short('u') + .long(options::SOCKET) + .value_name("socket") + .value_hint(clap::ValueHint::FilePath) + .conflicts_with(options::SERVER) + .action(clap::ArgAction::Set) + .overrides_with(options::SOCKET) + .help("write to this Unix socket") + .display_order(21), + ) + .arg( + Arg::new(options::SOCKET_ERRORS) + .long(options::SOCKET_ERRORS) + .require_equals(true) + .takes_value(true) + .min_values(0) + .max_values(1) + .possible_values(&["on", "off", "auto"]) + .default_missing_value("auto") + .help("print connection errors when using Unix sockets") + .display_order(22), + ) + .arg( + Arg::new(options::JOURNALD) + .long(options::JOURNALD) + .require_equals(true) + .min_values(0) + .max_values(1) + .value_name("file") + .default_missing_value("-") + .value_hint(clap::ValueHint::FilePath) + .help("write journald entry") + .display_order(23), + ) + .arg( + Arg::new(options::MESSAGE) + .help("message to send") + .index(1) + .multiple_values(true) + .required(false) + .use_value_delimiter(false) + .hide(true), + ) +} + + +/// Initialize missing fields (header generator and default tag). +pub fn logger_open(cfg: &mut Config) { + if cfg.syslogfp.is_none() { + cfg.syslogfp = Some(match cfg.server { + Some(_) => syslog_rfc5424_header, + None => syslog_local_header, + }); + } + + if cfg.tag.is_none() { + cfg.tag = username().ok(); + } + if cfg.tag.is_none() { + cfg.tag = Some("".to_string()); + } +} + +fn mirror_to_stderr(cfg: &Config, payload: &[u8]) -> io::Result<()> { + if !cfg.stderr { + return Ok(()); + } + let mut err = io::stderr().lock(); + err.write_all(payload)?; + err.write_all(b"\n")?; + Ok(()) +} +fn send_unix_dgram(path: &Path, payload: &[u8]) -> io::Result<()> { + let sock = UnixDatagram::unbound()?; + sock.connect(path)?; + sock.send(payload)?; + Ok(()) +} + +fn send_unix_stream(path: &Path, payload: &[u8]) -> io::Result<()> { + let mut s = UnixStream::connect(path)?; + s.write_all(payload)?; + s.write_all(&[0])?; + s.flush()?; + Ok(()) +} + +fn try_send_unix(path: &Path, payload: &[u8], mode: LocalSockMode) -> io::Result<()> { + match mode { + LocalSockMode::DatagramOnly => send_unix_dgram(path, payload), + LocalSockMode::StreamOnly => send_unix_stream(path, payload), + LocalSockMode::Auto => { + send_unix_dgram(path, payload).or_else(|_| send_unix_stream(path, payload)) + } + } +} + +fn try_send_udp(host: &str, port: u16, payload: &[u8]) -> io::Result<()> { + let mut last = None; + for addr in (host, port).to_socket_addrs()? { + let bind = if addr.is_ipv4() { + "0.0.0.0:0" + } else { + "[::]:0" + }; + let sock = UdpSocket::bind(bind)?; + if let Err(e) = sock.connect(addr) { + last = Some(e); + continue; + } + sock.set_write_timeout(Some(Duration::from_secs(2)))?; + match sock.send(payload) { + Ok(_) => return Ok(()), + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or_else(|| io::Error::new(io::ErrorKind::Other, "udp send failed"))) +} + +fn try_send_tcp(host: &str, port: u16, payload: &[u8], octet_counting: bool) -> io::Result<()> { + let mut last = None; + for addr in (host, port).to_socket_addrs()? { + match TcpStream::connect_timeout(&addr, Duration::from_secs(3)) { + Ok(mut s) => { + let _ = s.set_nodelay(true); + if octet_counting { + write!(s, "{} ", payload.len())?; + s.write_all(payload)?; + } else { + s.write_all(payload)?; + s.write_all(b"\n")?; + } + s.flush()?; + return Ok(()); + } + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or_else(|| io::Error::new(io::ErrorKind::Other, "tcp connect failed"))) +} + +fn try_send_network(cfg: &Config, payload: &[u8]) -> io::Result<()> { + let host = cfg.server.as_deref().expect("server must be set"); + + if cfg.use_udp { + let port = net_effective_port(cfg, NetProto::Udp); // P or 514 + return try_send_udp(host, port, payload); + } + if cfg.use_tcp { + let port = net_effective_port(cfg, NetProto::Tcp); // P or 601 + return try_send_tcp(host, port, payload, cfg.octet_count); + } + + let udp_port = net_effective_port(cfg, NetProto::Udp); // P or 514 + match try_send_udp(host, udp_port, payload) { + Ok(()) => Ok(()), + Err(_e_udp) => { + let tcp_port = net_effective_port(cfg, NetProto::Tcp); // P or 601 + try_send_tcp(host, tcp_port, payload, cfg.octet_count) + } + } +} + +#[inline] +fn errno_only_message(code: i32) -> String { + let s = std::io::Error::from_raw_os_error(code).to_string(); + if let Some(idx) = s.rfind(" (os error ") { + if s.ends_with(')') { + return s[..idx].to_string(); + } + } + s +} + +#[inline] +fn errno_msg(e: &io::Error) -> String { + e.raw_os_error() + .map(errno_only_message) + .unwrap_or_else(|| e.to_string()) +} + +fn probe_unix(path: &Path, mode: LocalSockMode) -> io::Result<()> { + match mode { + LocalSockMode::DatagramOnly => { + let s = UnixDatagram::unbound()?; + s.connect(path)?; + Ok(()) + } + LocalSockMode::StreamOnly => { + let _ = UnixStream::connect(path)?; + Ok(()) + } + LocalSockMode::Auto => { + match UnixDatagram::unbound().and_then(|s| { + s.connect(path)?; + Ok(()) + }) { + Ok(()) => Ok(()), + Err(_) => { + let _ = UnixStream::connect(path)?; + Ok(()) + } + } + } + } +} + +fn probe_remote(cfg: &Config) -> io::Result<()> { + let host = cfg.server.as_deref().expect("server must be set"); + let port = net_effective_port(cfg, net_effective_proto(cfg)); + match net_effective_proto(cfg) { + NetProto::Udp => { + let addr_iter = (host, port).to_socket_addrs()?; + let mut last = None; + for addr in addr_iter { + let bind = if addr.is_ipv4() { + "0.0.0.0:0" + } else { + "[::]:0" + }; + let sock = UdpSocket::bind(bind)?; + match sock.connect(addr) { + Ok(()) => return Ok(()), + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or_else(|| io::Error::new(io::ErrorKind::Other, "udp connect failed"))) + } + NetProto::Tcp => { + let mut last = None; + for addr in (host, port).to_socket_addrs()? { + match TcpStream::connect(addr) { + Ok(_) => return Ok(()), + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or_else(|| io::Error::new(io::ErrorKind::Other, "tcp connect failed"))) + } + } +} + +#[inline] +fn display_remote_port(cfg: &Config) -> u16 { + if cfg.use_udp { + net_effective_port(cfg, NetProto::Udp) + } else { + net_effective_port(cfg, NetProto::Tcp) + } +} +fn with_octet_prefix(buf: &[u8]) -> Vec { + let mut v = Vec::with_capacity(buf.len() + 24); + let len_str = buf.len().to_string(); + v.extend_from_slice(len_str.as_bytes()); + v.push(b' '); + v.extend_from_slice(buf); + v +} + +fn write_output(cfg: &Config, bytes: &[u8]) -> io::Result<()> { + let header = cfg.hdr.as_deref().unwrap_or_default().as_bytes(); + let line_len = header.len() + bytes.len(); + + let mut payload: Vec = Vec::with_capacity(line_len); + payload.extend_from_slice(header); + payload.extend_from_slice(bytes); + + if cfg.no_act { + if cfg.server.is_some() { + if let Err(e) = probe_remote(cfg) { + eprintln!( + "{}: remote {}:{}: {}", + progname(), + cfg.server.as_deref().unwrap(), + net_effective_port(cfg, net_effective_proto(cfg)), + errno_msg(&e) + ); + return Err(e); + } + } else { + let mode = choose_local_mode(cfg); + let (candidates, primary_for_err): (Vec<&Path>, &Path) = if let Some(ref p) = cfg.socket + { + let p: &Path = p.as_path(); + (vec![p], p) + } else { + let devlog = Path::new("/dev/log"); + match mode { + LocalSockMode::StreamOnly | LocalSockMode::DatagramOnly => { + (vec![devlog], devlog) + } + LocalSockMode::Auto => { + let journal = Path::new("/run/systemd/journal/syslog"); + (vec![devlog, journal], devlog) + } + } + }; + + let mut ok = false; + let mut last_err: Option = None; + + for path in &candidates { + match probe_unix(path, mode) { + Ok(()) => { + ok = true; + break; + } + Err(e) => last_err = Some(e), + } + } + if !ok { + let err = last_err.unwrap_or_else(|| { + io::Error::new(io::ErrorKind::Other, "no syslog sink reachable") + }); + let mode = cfg.socket_errors.unwrap_or(SocketErrorsMode::On); + if !matches!(mode, SocketErrorsMode::Off) { + eprintln!( + "{}: socket {}: {}", + progname(), + primary_for_err.display(), + errno_msg(&err) + ); + } + if matches!(mode, SocketErrorsMode::On) { + return Err(err); + } + } + } + + if cfg.octet_count { + let preview = with_octet_prefix(&payload); + mirror_to_stderr(cfg, &preview)?; + } else { + mirror_to_stderr(cfg, &payload)?; + } + return Ok(()); + } + + if cfg.server.is_some() { + let sock_mode = cfg.socket_errors.unwrap_or(SocketErrorsMode::On); + let r = try_send_network(cfg, &payload); + match r { + Ok(()) => { + if cfg.octet_count { + let preview = with_octet_prefix(&payload); + mirror_to_stderr(cfg, &preview)?; + } else { + mirror_to_stderr(cfg, &payload)?; + } + return Ok(()); + } + Err(e) => { + if !matches!(sock_mode, SocketErrorsMode::Off) { + eprintln!( + "{}: remote {}:{}: {}", + progname(), + cfg.server.as_deref().unwrap(), + display_remote_port(cfg), + errno_msg(&e) + ); + } + return match sock_mode { + SocketErrorsMode::On => Err(e), + SocketErrorsMode::Auto | SocketErrorsMode::Off => Ok(()), + }; + } + } + } + + let mode = choose_local_mode(cfg); + let (candidates, primary_for_err): (Vec<&Path>, &Path) = if let Some(ref p) = cfg.socket { + let p: &Path = p.as_path(); + (vec![p], p) + } else { + let devlog = Path::new("/dev/log"); + match mode { + LocalSockMode::StreamOnly | LocalSockMode::DatagramOnly => (vec![devlog], devlog), + LocalSockMode::Auto => { + let journal = Path::new("/run/systemd/journal/syslog"); + (vec![devlog, journal], devlog) + } + } + }; + + let mut sent = false; + let mut err_primary: Option = None; + let mut err_other: Option = None; + + let mode = choose_local_mode(cfg); + for path in &candidates { + match try_send_unix(path, &payload, mode) { + Ok(()) => { + sent = true; + break; + } + Err(e) => { + if *path == primary_for_err { + err_primary = Some(e); + } else { + err_other = Some(e); + } + } + } + } + + if sent { + if cfg.octet_count { + let preview = with_octet_prefix(&payload); + mirror_to_stderr(cfg, &preview)?; + } else { + mirror_to_stderr(cfg, &payload)?; + } + return Ok(()); + } + + let err = err_primary + .or(err_other) + .unwrap_or_else(|| io::Error::new(io::ErrorKind::Other, "no syslog sink reachable")); + + let mode = cfg.socket_errors.unwrap_or(SocketErrorsMode::On); + match mode { + SocketErrorsMode::On => { + eprintln!( + "{}: socket {}: {}", + progname(), + primary_for_err.display(), + errno_msg(&err) + ); + Err(err) + } + SocketErrorsMode::Auto => { + eprintln!( + "{}: socket {}: {}", + progname(), + primary_for_err.display(), + errno_msg(&err) + ); + Ok(()) + } + SocketErrorsMode::Off => { + if cfg.octet_count { + let preview = with_octet_prefix(&payload); + mirror_to_stderr(cfg, &preview)?; + } else { + mirror_to_stderr(cfg, &payload)?; + } + Ok(()) + } + } +} + +/// Send the positional inline message (if any), chunking or joining as needed. +pub fn logger_command_line(cfg: &mut Config) -> io::Result<()> { + let args: Vec = match cfg.inline_args.take() { + Some(v) => v, + None => return Ok(()), + }; + + let max = cfg.size; + let mut buf: Vec = Vec::with_capacity(max.saturating_add(1)); + + for a in &args { + let ab = a.as_bytes(); + let alen = ab.len(); + + if alen > max { + if !buf.is_empty() { + write_output(cfg, &buf)?; + buf.clear(); + } + write_output(cfg, &ab[..max])?; + continue; + } + + let need_space = !buf.is_empty(); + let added = alen + if need_space { 1 } else { 0 }; + + if buf.len() + added > max { + write_output(cfg, &buf)?; + buf.clear(); + } + if !buf.is_empty() { + buf.push(b' '); + } + buf.extend_from_slice(ab); + } + + if !buf.is_empty() { + write_output(cfg, &buf)?; + } + + Ok(()) +} + +/// Read from stdin or `--file`, split into lines, and send messages. +/// Supports optional `` per-line prefix when `--prio-prefix` is set. +pub fn logger_stdin(cfg: &mut Config) -> io::Result<()> { + let input: Box = match cfg.file.as_deref() { + Some(path) => Box::new(File::open(path)?), + None => Box::new(io::stdin()), + }; + let mut rdr = BufReader::new(input); + + let default_pri = cfg.pri as u16; + let max = cfg.size; + let mut buf: Vec = Vec::with_capacity(max.saturating_add(4)); + + loop { + buf.clear(); + + let n = rdr.read_until(b'\n', &mut buf)?; + if n == 0 { + break; + } // EOF + + if buf.last() == Some(&b'\n') { + buf.pop(); + } + + // cfg.pri = default_pri as u8; + + let mut start = 0usize; + if cfg.prio_prefix && buf.first() == Some(&b'<') { + let mut i = 1usize; + let mut pri: u16 = 0; + while i < buf.len() && buf[i].is_ascii_digit() && pri <= 191 { + pri = pri * 10 + (buf[i] - b'0') as u16; + i += 1; + } + if i < buf.len() && buf[i] == b'>' && pri <= 191 { + let mut new_pri = pri; + if (new_pri & LOG_FACMASK) == 0 { + new_pri |= default_pri & LOG_FACMASK; + } + cfg.pri = new_pri as u8; + start = i + 1; + } else { + cfg.pri = default_pri as u8; + } + } + + let msg = &buf[start..]; + + if msg.is_empty() { + if !cfg.skip_empty { + if let Some(gen) = cfg.syslogfp { + gen(cfg); + } + write_output(cfg, &[])?; + } + continue; + } else if msg.len() <= max { + if let Some(gen) = cfg.syslogfp { + gen(cfg); + } + write_output(cfg, msg)?; + } else { + let mut off = 0usize; + while off < msg.len() { + if let Some(gen) = cfg.syslogfp { + gen(cfg); + } + let end = (off + max).min(msg.len()); + write_output(cfg, &msg[off..end])?; + off = end; + } + } + } + + Ok(()) +} + +fn journald_socket_path() -> std::borrow::Cow<'static, str> { + if let Ok(p) = std::env::var("JOURNALD_SOCKET") { + return p.into(); + } + "/run/systemd/journal/socket".into() +} + +fn build_journald_native_payload(fields: &[Vec]) -> io::Result> { + let mut total = 0usize; + for f in fields { + total += f.len() + 1; + } + let mut out = Vec::with_capacity(total); + + for f in fields { + let Some(eq) = f.iter().position(|&b| b == b'=') else { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "invalid field (no '=')", + )); + }; + let (key, val_with_eq) = f.split_at(eq); + let val = &val_with_eq[1..]; + + let needs_len = val.iter().any(|&b| b == b'\n' || b == 0); + if needs_len { + out.extend_from_slice(key); + out.push(b'\n'); + let len = (val.len() as u64).to_le_bytes(); + out.extend_from_slice(&len); + out.extend_from_slice(val); + out.push(b'\n'); + } else { + out.extend_from_slice(key); + out.push(b'='); + out.extend_from_slice(val); + out.push(b'\n'); + } + } + + Ok(out) +} + +/// Submit one native journald entry built from KEY=VALUE byte buffers. +/// Each element in `fields` must be a single `KEY=VALUE` byte vector. +/// For values that contain '\n' or NUL, `build_journald_native_payload` will +/// encode them per systemd's native protocol (`KEY\n\n\n`). +// #[cfg(target_os = "linux")] +fn send_to_journald(fields: Vec>) -> io::Result<()> { + if fields.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "no journald fields", + )); + } + + // 1) Build one datagram that contains all fields for this entry. + let payload = build_journald_native_payload(&fields)?; + + // 2) Send the datagram to journald's native socket. + let sock_path = journald_socket_path(); + let sock = UnixDatagram::unbound()?; + sock.connect(sock_path.as_ref())?; + + let n = sock.send(&payload)?; + if n != payload.len() { + return Err(io::Error::new( + io::ErrorKind::WriteZero, + "short write to journald", + )); + } + Ok(()) +} + +/// +pub fn journald_entry(cfg: &Config) -> io::Result<()> { + let Some(ref p) = cfg.journald_path else { + return Ok(()); + }; + + let reader: Box = if p.as_os_str() == "-" { + Box::new(io::stdin()) + } else { + Box::new(File::open(p)?) + }; + let mut br = BufReader::new(reader); + + let mut iovecs: Vec> = Vec::new(); + let mut msg_index: Option = None; + let mut line = String::new(); + + loop { + line.clear(); + let n = br.read_line(&mut line)?; + if n == 0 { + break; // EOF + } + + // util-linux: rtrim only; keep leading spaces intact + let l = line.trim_end(); + if l.is_empty() { + break; // empty line terminates this entry + } + + if let Some(rest) = l.strip_prefix("MESSAGE=") { + if let Some(idx) = msg_index { + // Append only the value (not "MESSAGE=") with a leading '\n' + let v = &mut iovecs[idx]; + v.push(b'\n'); + v.extend_from_slice(rest.as_bytes()); + continue; // do NOT push a new iovec item + } else { + // Remember first MESSAGE= line position; push full line below + msg_index = Some(iovecs.len()); + } + } + + iovecs.push(l.as_bytes().to_vec()); + } + + if iovecs.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "no journald fields", + )); + } + + // --no-act: mirror only, exit 0 + if cfg.no_act { + if cfg.stderr { + for v in &iovecs { + eprintln!("{}", String::from_utf8_lossy(v)); + } + } + return Ok(()); + } + + // send + let res = send_to_journald(iovecs.clone()); + + // mirror after send (matches util-linux ordering; harmless either way) + if cfg.stderr { + for v in &iovecs { + eprintln!("{}", String::from_utf8_lossy(v)); + } + } + + res +} diff --git a/src/oe/logger/src/main.rs b/src/oe/logger/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..1995fd5fe0707ca2a83e1ca4d82bd982df51a760 --- /dev/null +++ b/src/oe/logger/src/main.rs @@ -0,0 +1,8 @@ +// Copyright (c) 2025 Sun Yuhang +// [logger] is licensed under Mulan PSL v2. +// You can use this software according to the terms and conditions of the Mulan PSL v2. +// You may obtain a copy of Mulan PSL v2 at: +// http://license.coscl.org.cn/MulanPSL2 +// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. +// See the Mulan PSL v2 for more details. +uucore::bin!(oe_logger); diff --git a/src/oe/logger/src/syslog_header.rs b/src/oe/logger/src/syslog_header.rs new file mode 100644 index 0000000000000000000000000000000000000000..373786e9d809603896383df116f519b1758f9655 --- /dev/null +++ b/src/oe/logger/src/syslog_header.rs @@ -0,0 +1,203 @@ +// Copyright (c) 2025 Sun Yuhang +// [logger] is licensed under Mulan PSL v2. +// You can use this software according to the terms and conditions of the Mulan PSL v2. +// You may obtain a copy of Mulan PSL v2 at: +// http://license.coscl.org.cn/MulanPSL2 +// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. +// See the Mulan PSL v2 for more details. + +use crate::logger_common::{Config, LogId}; +use std::os::raw::{c_char, c_int}; +use time::{format_description, Month, OffsetDateTime, UtcOffset}; + +extern "C" { + fn gethostname(name: *mut c_char, len: usize) -> c_int; +} + +#[cfg(unix)] +fn hostname() -> String { + let mut buf = [0u8; 256]; + + let ret = unsafe { gethostname(buf.as_mut_ptr() as *mut c_char, buf.len()) }; + if ret != 0 { + return "-".to_string(); + } + + let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); + let bytes = &buf[..end]; + + let s = String::from_utf8_lossy(bytes).into_owned(); + if s.is_empty() { + "-".to_string() + } else { + s + } +} + +fn make_tag(tag_base: &str, log_id: Option<&LogId>) -> String { + let pid = std::process::id(); + match log_id { + Some(LogId::Pid) => format!("{tag_base}[{}]", pid), + Some(LogId::Explicit(s)) => format!("{tag_base}[{s}]"), + None => tag_base.to_string(), + } +} + +fn month_abbr(m: Month) -> &'static str { + match m { + Month::January => "Jan", + Month::February => "Feb", + Month::March => "Mar", + Month::April => "Apr", + Month::May => "May", + Month::June => "Jun", + Month::July => "Jul", + Month::August => "Aug", + Month::September => "Sep", + Month::October => "Oct", + Month::November => "Nov", + Month::December => "Dec", + } +} + +fn rfc3164_ts() -> String { + let off = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC); + let t = OffsetDateTime::now_utc().to_offset(off); + format!( + "{} {:>2} {:02}:{:02}:{:02}", + month_abbr(t.month()), + t.day(), + t.hour(), + t.minute(), + t.second() + ) +} + +fn rfc5424_ts() -> String { + let off = UtcOffset::current_local_offset().unwrap_or(UtcOffset::UTC); + let t = OffsetDateTime::now_utc().to_offset(off); + let fmt = format_description::parse( + "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:6][offset_hour sign:mandatory]:[offset_minute]" + ).unwrap(); + t.format(&fmt).unwrap_or_else(|_| "-".to_string()) +} + +fn msgid_string(s: Option<&str>) -> String { + match s { + None => "-".to_string(), + Some(x) if x.is_empty() => "-".to_string(), + Some(x) => x.to_string(), + } +} + +fn ensure_appname_len(app: &str) { + if app.len() > 48 { + panic!("tag '{}' is too long", app); + } +} + +fn ensure_host_len(host: &str) { + if host != "-" && host.len() > 255 { + panic!("hostname '{}' is too long", host); + } +} + +fn sanitize_printusascii(s: &str, max: usize) -> String { + let mut out: String = s + .chars() + .map(|c| { + if (33..=126).contains(&(c as u32)) { + c + } else { + '_' + } + }) + .collect(); + if out.is_empty() { + return "-".to_string(); + } + if out.len() > max { + out.truncate(max); + } + out +} +fn procid_5424(log_id: Option<&LogId>) -> String { + match log_id { + Some(LogId::Pid) => std::process::id().to_string(), + Some(LogId::Explicit(s)) => sanitize_printusascii(s, 128), + None => "-".to_string(), + } +} + +/// call syslog_header +pub fn generate_syslog_header(cfg: &mut Config) { + (cfg.syslogfp.expect("syslogfp not set"))(cfg); +} + +/// local header +pub fn syslog_local_header(cfg: &mut Config) { + let pri = cfg.pri; + let ts = rfc3164_ts(); + let tag = make_tag(cfg.tag.as_deref().unwrap_or(""), cfg.log_id.as_ref()); + cfg.hdr = Some(format!("<{pri}>{ts} {tag}: ")); +} + +/// rfc3164_header +pub fn syslog_rfc3164_header(cfg: &mut Config) { + let pri = cfg.pri; + let ts = rfc3164_ts(); + let hostname = hostname(); + let tag = make_tag(cfg.tag.as_deref().unwrap_or(""), cfg.log_id.as_ref()); + cfg.hdr = Some(format!("<{pri}>{ts} {hostname} {tag}: ")); +} + +/// rfc5424 header +pub fn syslog_rfc5424_header(cfg: &mut Config) { + let (use_time, use_tq, use_host) = match cfg.rfc5424.as_ref() { + Some(snip) => (!snip.notime, !snip.notq, !snip.nohost), + None => (true, true, true), + }; + + let add_time_quality = use_tq && use_time && cfg.structured_user.is_none(); + + // PRI + let pri = cfg.pri; + + // TIMESTAMP + let ts = if use_time { + rfc5424_ts() + } else { + "-".to_string() + }; + + // HOST + let host = if use_host { + hostname() + } else { + "-".to_string() + }; + ensure_host_len(&host); + + let app = cfg.tag.as_deref().unwrap_or(""); + ensure_appname_len(app); + // APPNAME + let app_name = if app.is_empty() { "-" } else { app }; + + let procid = procid_5424(cfg.log_id.as_ref()); + + let msgid = msgid_string(cfg.msgid.as_deref()); + + let structured = if !use_time { + "-".to_string() + } else if let Some(sd) = cfg.structured_user.clone() { + sd + } else if add_time_quality { + r#"[timeQuality tzKnown="1" isSynced="0"]"#.to_string() + } else { + "-".to_string() + }; + + cfg.hdr = Some(format!( + "<{pri}>1 {ts} {host} {app_name} {procid} {msgid} {structured} " + )); +} diff --git a/src/oe/mount/src/mount_common.rs b/src/oe/mount/src/mount_common.rs index c0ac5ebb908eb953999d42bcda47ef3cfe40dd78..9d1b61922607b043cedead8a478663f3010fcd81 100755 --- a/src/oe/mount/src/mount_common.rs +++ b/src/oe/mount/src/mount_common.rs @@ -688,7 +688,7 @@ impl ConfigHandler { } let _mount_source = Some(prepare_mount_source_res.unwrap()); let target = &line_vec[1]; - let fstype = line_vec[2].as_str().clone(); + let fstype = line_vec[2].as_str(); let _flags = MsFlags::MS_NOEXEC | MsFlags::MS_NOSUID; let fstab_options = &line_vec[3]; if let Some(test_opts) = &self.config.options.test_opts { diff --git a/src/oe/xargs/xargs.md b/src/oe/xargs/xargs.md index f40675346163673fe525cd95503580cc36f7c1e7..8b8002bf58801ce80db60a8e503d8d176ddd89d7 100644 --- a/src/oe/xargs/xargs.md +++ b/src/oe/xargs/xargs.md @@ -12,88 +12,88 @@ xargs -V Build and execute command lines from standard input. ## Arguments -- **-0**, **--null** - +- **-0**, **--null** + Items are separated by a null, not white space;disables quote and backslash processing and logical EOF processing. - + - **-a**, **--arg-file=FILE** - + Read arguments from FILE, not standard input. - **-d**, **--delimiter=CHARACTER** - + Items in input stream are separated by CHARACTER,not by white space; disables quote and backslash processing and logical EOF processing. - - -- **-E END** - + + +- **-E END** + Set logical EOF string; if END occurs as a line of input, the rest of the input is ignored (ignored if -0 or -d was specified). - -- **-e**, **--e of[=END]** - + +- **-e**, **--e of[=END]** + Equivalent to -E END if END is specified; otherwise, there is no end-of-file string. - -- **-I R** - + +- **-I R** + Same as --replace=R. -- **-i**, **--replace[=R]** - +- **-i**, **--replace[=R]** + Replace R in INITIAL-ARGS with names read from standard input, split at newlines; if R is unspecified, assume {}. - -- **-L**, **--max-lines=MAX-LINES** + +- **-L**, **--max-lines=MAX-LINES** Use at most MAX-LINES non-blank input lines per command line. - -- **-l[MAX-LINES]** + +- **-l[MAX-LINES]** similar to -L but defaults to at most one non-blank input line if MAX-LINES is not specified. - -- **-n**, **--max-args=MAX-ARGS** - + +- **-n**, **--max-args=MAX-ARGS** + Use at most MAX-ARGS arguments per command line. -- **-o**, **--open-tty** +- **-o**, **--open-tty** Reopen stdin as /dev/tty in the child process before executing the command; useful to run an interactive application. - + - **-P**, **--max-procs=MAX-PROCS** run at most MAX-PROCS processes at a time. - **-p**, **--interactive** - + Prompt before running commands. -- **--process-slot-var=VAR** +- **--process-slot-var=VAR** Set environment variable VAR in child processes. -- **-r**, **--no-run-if-empty** - +- **-r**, **--no-run-if-empty** + If there are no arguments, then do not run COMMAND;if this option is not given, COMMAND will be run at least once. - - -- **-s**, **--max-chars=MAX-CHARS** - + + +- **-s**, **--max-chars=MAX-CHARS** + Limit length of command line to MAX-CHARS. -- **--show-limits** +- **--show-limits** + + show limits on command-line length. + +- **-t**, **--verbose** - show limits on command-line length. - -- **-t**, **--verbose** - print commands before executing them. -- **-x**, **--exit** +- **-x**, **--exit** Exit if the size (see -s) is exceeded. - - **--help** - + - **--help** + display this help and exit. - _ **--version** - + _ **--version** + output version information and exit. diff --git a/tests/by-util/test_logger.rs b/tests/by-util/test_logger.rs new file mode 100644 index 0000000000000000000000000000000000000000..7b816783debbc6e85b0008dd073a51d459de33ca --- /dev/null +++ b/tests/by-util/test_logger.rs @@ -0,0 +1,645 @@ +use crate::common::util::*; +use regex::Regex; +use std::fs; + +const SYS_LOGGER: &str = "/usr/bin/logger"; + +fn strip_ts(line: &str) -> String { + let re_5424 = Regex::new(r#"^(<\d+>1)\s+\S+(\s+)"#).unwrap(); + let re_3164 = Regex::new(r#"^(<\d+>)\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}(\s+)"#).unwrap(); + if re_5424.is_match(line) { + re_5424.replace(line, "$1 TS$2").to_string() + } else if re_3164.is_match(line) { + re_3164.replace(line, "$1TS$2").to_string() + } else { + line.to_string() + } +} + +fn create_file() { + let _ = fs::write("/tmp/input_simple", "{a..c}{1..5}"); + let _ = fs::write("/tmp/input_empty_line", "{a..c}{1..5}\n\n{5..1}{c..1}"); + let _ = fs::write("/tmp/input_prio_prefix", "'<66>' prio_prefix"); +} + +#[test] +fn options_simple() { + let args = ["--stderr", "--no-act", "test"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn options_log_pid() { + let args = ["--stderr", "--no-act", "--id=98765", "-t", "hyl", "test"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn options_log_pid_long() { + let args = ["--stderr", "--no-act", "--id=98765", "test"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn options_log_pid_define() { + let args = ["--stderr", "--no-act", "--id=12345", "test"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} +#[test] +fn options_log_pid_no_arg() { + let args = ["--stderr", "--no-act", "-is", "--id=98765", "test"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn options_input_file_simple() { + create_file(); + let args = [ + "--stderr", + "--no-act", + "-t", + "test_tag", + "-f", + "/tmp/input_simple", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn options_input_file_empty_line() { + let args = [ + "--stderr", + "--no-act", + "-t", + "test_tag", + "-f", + "/tmp/input_empty_line", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn options_input_file_skip_empty() { + let args = [ + "--stderr", + "--no-act", + "-t", + "test_tag", + "-f", + "/tmp/input_empty_line", + "-e", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn options_input_file_prio_prefix() { + let args = [ + "--stderr", + "--no-act", + "-t", + "test_tag", + "--file", + "/tmp/input_prio_prefix", + "--skip-empty", + "--prio-prefix", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn formats_rfc3164() { + let args = [ + "--stderr", + "--no-act", + "-t", + "rfc3164", + "--rfc3164", + "message", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn formats_rfc5424_simple() { + let args = [ + "--stderr", + "--no-act", + "-t", + "rfc5424", + "--rfc5424", + "message", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn formats_rfc5424_notime() { + let args = [ + "--stderr", + "--no-act", + "-t", + "rfc5424", + "--rfc5424=notime", + "message", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn formats_rfc5424_nohost() { + let args = [ + "--stderr", + "--no-act", + "-t", + "rfc5424", + "--rfc5424=nohost", + "message", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn formats_rfc5424_msgid() { + let args = [ + "--stderr", + "--no-act", + "-t", + "rfc5424", + "--rfc5424", + "--msgid", + "MSGID", + "message", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn formats_octet_counting() { + let args = [ + "--stderr", + "--no-act", + "-t", + "octen", + "--octet-count", + "message", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn formats_priorities() { + let faci = [ + "auth", "authpriv", "cron", "daemon", "ftp", "lpr", "mail", "news", "syslog", "user", + "uucp", "local0", "local1", "local2", "local3", "local4", "local5", "local6", "local7", + ]; + let levels = [ + "emerg", "alert", "crit", "err", "warning", "notice", "info", "debug", + ]; + let t = TestScenario::new(util_name!()); + for &fac in &faci { + for &lvl in &levels { + let prio = format!("{fac}.{lvl}"); + let args = ["--stderr", "--no-act", "-t", "prio", "-p", &prio, &prio]; + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); + } + } +} + +#[test] +fn errors_kern_priority() { + let args = ["--stderr", "-t", "prio", "-p", "kern.emerg", "message"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn errors_kern_priority_numeric() { + let args = ["--stderr", "-t", "prio", "-p", "0", "message"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn errors_invalid_prio() { + let args = ["--stderr", "-t", "prio", "-p", "8", "message"]; + let t = TestScenario::new(util_name!()); + + let sys = t.cmd(SYS_LOGGER).args(&args).fails(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("unknown priority"), + "stderr was: {}", + sys_line + ); + + let rust = t.ucmd().args(&args).fails(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("unknown priority"), + "stderr was: {}", + sys_line + ); +} + +#[test] +fn errors_rfc5424_exceed_size() { + let args = [ + "--stderr", + "-t", + "rfc5424_exceed_size", + "--rfc5424", + "--size", + "3", + "abcd", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn errors_id_with_space() { + let t = TestScenario::new(util_name!()); + + //id_with_space + let args = ["--stderr", "-t", "id_with_space", "--id='A B'", "message"]; + let mut sys = t.cmd(SYS_LOGGER).args(&args).fails(); + let mut sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("failed to parse id:"), + "stderr was: {}", + sys_line + ); + let mut rust = t.ucmd().args(&args).fails(); + let mut rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("failed to parse id:"), + "stderr was: {}", + rust_line + ); + + //rfc5424_id_with_space + let args1 = [ + "--stderr", + "-t", + "rfc5424_id_with_space", + "--rfc5424", + "--id='A B'", + "message", + ]; + sys = t.cmd(SYS_LOGGER).args(&args1).fails(); + sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("failed to parse id:"), + "stderr was: {}", + sys_line + ); + rust = t.ucmd().args(&args1).fails(); + rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("failed to parse id:"), + "stderr was: {}", + rust_line + ); + + //id_with_space + let args2 = ["--stderr", "-t", "id_with_space", "--id='1 23'", "message"]; + sys = t.cmd(SYS_LOGGER).args(&args2).fails(); + sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("failed to parse id:"), + "stderr was: {}", + sys_line + ); + rust = t.ucmd().args(&args2).fails(); + rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("failed to parse id:"), + "stderr was: {}", + rust_line + ); + + //id_with_leading space + let args3 = ["--stderr", "-t", "id_with_space", "--id=' 123'", "message"]; + sys = t.cmd(SYS_LOGGER).args(&args3).fails(); + sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("failed to parse id:"), + "stderr was: {}", + sys_line + ); + rust = t.ucmd().args(&args3).fails(); + rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("failed to parse id:"), + "stderr was: {}", + rust_line + ); + + let args4 = [ + "--stderr", + "-t", + "id_with_leading space", + "--id='123 '", + "message", + ]; + sys = t.cmd(SYS_LOGGER).args(&args4).fails(); + sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("failed to parse id:"), + "stderr was: {}", + sys_line + ); + rust = t.ucmd().args(&args4).fails(); + rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("failed to parse id:"), + "stderr was: {}", + rust_line + ); +} + +#[test] +fn errors_tag_with_space() { + let t = TestScenario::new(util_name!()); + + let args = ["--stderr", "-t", "A B", "tag_with_space"]; + let mut sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let mut sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let mut rust = t.ucmd().args(&args).succeeds(); + let mut rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let mut sys_norm = strip_ts(&sys_line); + let mut rust_norm = strip_ts(&rust_line); + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); + + let args1 = [ + "--stderr", + "-t", + "A B", + "--rfc5424", + "tag_with_space_rfc5424", + ]; + sys = t.cmd(SYS_LOGGER).args(&args1).succeeds(); + sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + rust = t.ucmd().args(&args1).succeeds(); + rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + sys_norm = strip_ts(&sys_line); + rust_norm = strip_ts(&rust_line); + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn errors_tcp() { + let args = ["--stderr", "--tcp", "-t", "tcp", "message"]; + let t = TestScenario::new(util_name!()); + + let sys = t.cmd(SYS_LOGGER).args(&args).fails(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("Protocol wrong type for socket"), + "stderr was: {}", + sys_line + ); + + let rust = t.ucmd().args(&args).fails(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("Protocol wrong type for socket"), + "stderr was: {}", + rust_line + ); +} + +#[test] +fn errors_multi_line() { + let args = ["--stderr", "AAA\nBBB\nCCC\n", "-t", "multi"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!(sys_norm, rust_norm, "SYS:{sys_line:?}RUST:{rust_line:?}"); +} + +#[test] +fn errors_rfc5424_msgid_with_space() { + let args = [ + "--stderr", + "-t", + "rfc5424_msgid_with_space", + "--rfc5424", + "--msgid='A B'", + "message", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).fails(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("--msgid cannot contain space"), + "stderr was: {}", + sys_line + ); + let rust = t.ucmd().args(&args).fails(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("--msgid cannot contain space"), + "stderr was: {}", + rust_line + ); +} + +#[test] +fn errors_invalid_socket() { + let args = [ + "--stderr", + "-u", + "/bad/boy", + "-t", + "invalid_socket", + "message", + ]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).fails(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + assert!( + sys_line.contains("No such file or directory"), + "stderr was: {}", + sys_line + ); + let rust = t.ucmd().args(&args).fails(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + assert!( + rust_line.contains("No such file or directory"), + "stderr was: {}", + rust_line + ); +} +/* +test template +#[test] +fn () { + let args = ["--stderr", "--no-act", "test"]; + let t = TestScenario::new(util_name!()); + let sys = t.cmd(SYS_LOGGER).args(&args).succeeds(); + let sys_line = String::from_utf8_lossy(sys.stderr()).into_owned(); + let rust = t.ucmd().args(&args).succeeds(); + let rust_line = String::from_utf8_lossy(rust.stderr()).into_owned(); + let sys_norm = strip_ts(&sys_line); + let rust_norm = strip_ts(&rust_line); + + assert_eq!( + sys_norm, rust_norm, + "SYS:{sys_line:?}RUST:{rust_line:?}" + ); +} +*/ diff --git a/tests/fixtures/logger/file_prio_prefix.in b/tests/fixtures/logger/file_prio_prefix.in new file mode 100644 index 0000000000000000000000000000000000000000..d838ec77649b93a22955fb8b4a73d836e07e69e3 --- /dev/null +++ b/tests/fixtures/logger/file_prio_prefix.in @@ -0,0 +1 @@ +<66> prio_prefix\n<13> default\n diff --git a/tests/fixtures/logger/file_simple.in b/tests/fixtures/logger/file_simple.in new file mode 100644 index 0000000000000000000000000000000000000000..aabd0edd4e5bfdbfcd126a3d5e77acfd9c7c97f2 --- /dev/null +++ b/tests/fixtures/logger/file_simple.in @@ -0,0 +1 @@ +a1 a2 a3\nb1 b2 b3\n diff --git a/tests/fixtures/logger/file_with_empty.in b/tests/fixtures/logger/file_with_empty.in new file mode 100644 index 0000000000000000000000000000000000000000..2bf67357c0bbe7e78423dc555127622fe5deb92e --- /dev/null +++ b/tests/fixtures/logger/file_with_empty.in @@ -0,0 +1 @@ +x1 x2\n\nx3 x4\n diff --git a/tests/fixtures/logger/stdin_msg.in b/tests/fixtures/logger/stdin_msg.in new file mode 100644 index 0000000000000000000000000000000000000000..a87457c4a2828b4ab6f65a2ea83fe9d770e2c855 --- /dev/null +++ b/tests/fixtures/logger/stdin_msg.in @@ -0,0 +1 @@ +stdin default line\n diff --git a/tests/tests.rs b/tests/tests.rs index d6a9c9dfeed3a35089103cc3bcd7d04d545efe4e..be423ea1322865c4960eeb3787713fa10a8b124d 100755 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -127,3 +127,7 @@ mod test_find; #[cfg(feature = "less")] #[path = "by-util/test_less.rs"] mod test_less; + +#[cfg(feature = "logger")] +#[path = "by-util/test_logger.rs"] +mod test_logger;