libsystemd-0.5.0/.cargo_vcs_info.json0000644000000001360000000000100132150ustar { "git": { "sha1": "75a867b708037b88178a2cbe7b6cf3ced44abf47" }, "path_in_vcs": "" }libsystemd-0.5.0/.github/dependabot.yml000064400000000000000000000002210072674642500162200ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: daily time: "04:00" open-pull-requests-limit: 10 libsystemd-0.5.0/.github/workflows/rust.yml000064400000000000000000000041440072674642500171550ustar 00000000000000--- name: Rust on: [push, pull_request] env: CARGO_TERM_COLOR: always # Minimum supported Rust version (MSRV) ACTION_MSRV_TOOLCHAIN: 1.46.0 # Pinned toolchain for linting ACTION_LINTS_TOOLCHAIN: 1.55.0 jobs: tests-stable: name: "Tests, stable toolchain" runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: "stable" default: true - name: cargo build run: cargo build - name: cargo test run: cargo test - name: cargo build (release) run: cargo build --release tests-minimum-toolchain: name: "Tests, minimum supported toolchain (MSRV)" runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ env['ACTION_MSRV_TOOLCHAIN'] }} default: true - name: cargo test (release) run: cargo test --release linting: name: "Lints, pinned toolchain" runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ env['ACTION_LINTS_TOOLCHAIN'] }} default: true components: rustfmt, clippy - name: cargo clippy (warnings) run: cargo clippy -- -D warnings - name: cargo fmt (check) run: cargo fmt -- --check -l tests-other-channels: name: "Tests, unstable toolchain" runs-on: ubuntu-latest continue-on-error: true strategy: matrix: channel: - "beta" - "nightly" steps: - name: Checkout repository uses: actions/checkout@v2 - name: Install toolchain uses: actions-rs/toolchain@v1 with: toolchain: ${{ matrix.channel }} default: true - name: cargo build run: cargo build - name: cargo test run: cargo test libsystemd-0.5.0/COPYRIGHT000064400000000000000000000003500072674642500133260ustar 00000000000000Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: libsystemd Source: https://www.github.com/lucab/libsystemd-rs Files: * Copyright: 2017-2019, Project contributors License: MIT or Apache-2.0 libsystemd-0.5.0/Cargo.lock0000644000000301020000000000100111640ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" dependencies = [ "memchr", ] [[package]] name = "ansi_term" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d52a9bb7ec0cf484c551830a7ce27bd20d67eac647e1befb56b0be4ee39a55d2" dependencies = [ "winapi", ] [[package]] name = "autocfg" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "block-buffer" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1d36a02058e76b040de25a4464ba1c80935655595b661505c8b39b664828b95" dependencies = [ "generic-array", ] [[package]] name = "cc" version = "1.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22a9137b95ea06864e018375b72adfb7db6e6f68cfc8df5a04d00288050485ee" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cpufeatures" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95059428f66df56b63431fdb4e1947ed2190586af5c5a8a8b71122bdf5a7f469" dependencies = [ "libc", ] [[package]] name = "crypto-common" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d6b536309245c849479fba3da410962a43ed8e51c26b729208ec0ac2798d0" dependencies = [ "generic-array", ] [[package]] name = "ctor" version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccc0a48a9b826acdf4028595adc9db92caea352f7af011a3034acd172a52a0aa" dependencies = [ "quote", "syn", ] [[package]] name = "diff" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e25ea47919b1560c4e3b7fe0aaab9becf5b84a10325ddf7db0f0ba5e1026499" [[package]] name = "digest" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b697d66081d42af4fba142d56918a3cb21dc8eb63372c6b85d14f44fb9c5979b" dependencies = [ "block-buffer", "crypto-common", "generic-array", "subtle", ] [[package]] name = "env_logger" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" dependencies = [ "log", "regex", ] [[package]] name = "generic-array" version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" dependencies = [ "typenum", "version_check", ] [[package]] name = "getrandom" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fcd999463524c52659517fe2cea98493cfe485d10565e7b0fb07dbba7ad2753" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "hmac" version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddca131f3e7f2ce2df364b57949a9d47915cfbd35e46cfee355ccebbf794d6a2" dependencies = [ "digest", ] [[package]] name = "itoa" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35" [[package]] name = "libc" version = "0.2.112" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b03d17f364a3a042d5e5d46b053bbbf82c92c9430c592dd4c064dc6ee997125" [[package]] name = "libsystemd" version = "0.5.0" dependencies = [ "hmac", "libc", "log", "nix", "nom", "once_cell", "pretty_assertions", "quickcheck", "rand", "serde", "serde_json", "sha2", "thiserror", "uuid", ] [[package]] name = "log" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" dependencies = [ "cfg-if", ] [[package]] name = "memchr" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "308cc39be01b73d0d18f82a0e7b2a3df85245f84af96fdddc5d202d27e47b86a" [[package]] name = "memoffset" version = "0.6.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5aa361d4faea93603064a027415f07bd8e1d5c88c9fbf68bf56a285428fd79ce" dependencies = [ "autocfg", ] [[package]] name = "minimal-lexical" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "nix" version = "0.23.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f866317acbd3a240710c63f065ffb1e4fd466259045ccb504130b7f668f35c6" dependencies = [ "bitflags", "cc", "cfg-if", "libc", "memoffset", ] [[package]] name = "nom" version = "7.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b1d11e1ef389c76fe5b81bcaf2ea32cf88b62bc494e19f493d0b30e7a930109" dependencies = [ "memchr", "minimal-lexical", "version_check", ] [[package]] name = "once_cell" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da32515d9f6e6e489d7bc9d84c71b060db7247dc035bbe44eac88cf87486d8d5" [[package]] name = "output_vt100" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53cdc5b785b7a58c5aad8216b3dfa114df64b0b06ae6e1501cef91df2fbdf8f9" dependencies = [ "winapi", ] [[package]] name = "ppv-lite86" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" [[package]] name = "pretty_assertions" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0cfe1b2403f172ba0f234e500906ee0a3e493fb81092dac23ebefe129301cc" dependencies = [ "ansi_term", "ctor", "diff", "output_vt100", ] [[package]] name = "proc-macro2" version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029" dependencies = [ "unicode-xid", ] [[package]] name = "quickcheck" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6" dependencies = [ "env_logger", "log", "rand", ] [[package]] name = "quote" version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47aa80447ce4daf1717500037052af176af5d38cc3e571d9ec1c7353fc10c87d" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e7573632e6454cf6b99d7aac4ccca54be06da05aca2ef7423d22d27d4d4bcd8" dependencies = [ "libc", "rand_chacha", "rand_core", "rand_hc", ] [[package]] name = "rand_chacha" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" dependencies = [ "getrandom", ] [[package]] name = "rand_hc" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d51e9f596de227fda2ea6c84607f5558e196eeaf43c986b724ba4fb8fdf497e7" dependencies = [ "rand_core", ] [[package]] name = "regex" version = "1.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-syntax" version = "0.6.25" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" [[package]] name = "ryu" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f" [[package]] name = "serde" version = "1.0.133" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97565067517b60e2d1ea8b268e59ce036de907ac523ad83a0475da04e818989a" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.133" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed201699328568d8d08208fdd080e3ff594e6c422e438b6705905da01005d537" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.74" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee2bb9cd061c5865d345bb02ca49fcef1391741b672b54a0bf7b679badec3142" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "sha2" version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99c3bd8169c58782adad9290a9af5939994036b76187f7b4f0e6de91dbbfc0ec" dependencies = [ "cfg-if", "cpufeatures", "digest", ] [[package]] name = "subtle" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" [[package]] name = "syn" version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a684ac3dcd8913827e18cd09a68384ee66c1de24157e3c556c9ab16d85695fb7" dependencies = [ "proc-macro2", "quote", "unicode-xid", ] [[package]] name = "thiserror" version = "1.0.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "854babe52e4df1653706b98fcfc05843010039b406875930a70e4d9644e5c417" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "1.0.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa32fd3f627f367fe16f893e2597ae3c05020f8bba2666a4e6ea73d377e5714b" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "typenum" version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" [[package]] name = "unicode-xid" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" [[package]] name = "uuid" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" dependencies = [ "serde", ] [[package]] name = "version_check" version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "wasi" version = "0.10.2+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" libsystemd-0.5.0/Cargo.toml0000644000000035550000000000100112230ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "libsystemd" version = "0.5.0" authors = ["Luca Bruno ", "Sebastian Wiesner "] exclude = [".gitignore", ".travis.yml"] description = "A pure-Rust client library to interact with systemd" documentation = "https://docs.rs/libsystemd" readme = "README.md" keywords = ["systemd", "linux"] categories = ["api-bindings", "os::unix-apis"] license = "MIT/Apache-2.0" repository = "https://github.com/lucab/libsystemd-rs" [package.metadata.release] post-release-commit-message = "cargo: development version bump" pre-release-commit-message = "cargo: libsystemd release {{version}}" publish = false push = false sign-commit = true sign-tag = true tag-message = "libsystemd {{version}}" [[test]] name = "connected_to_journal" harness = false [dependencies.hmac] version = "^0.12" [dependencies.libc] version = "^0.2" [dependencies.log] version = "^0.4" [dependencies.nix] version = "^0.23" [dependencies.nom] version = "7" [dependencies.once_cell] version = "^1.8" [dependencies.serde] version = "^1.0.91" features = ["derive"] [dependencies.sha2] version = "^0.10" [dependencies.thiserror] version = "^1.0" [dependencies.uuid] version = "^0.8.1" features = ["serde"] [dev-dependencies.pretty_assertions] version = "^1.0" [dev-dependencies.quickcheck] version = "^1.0" [dev-dependencies.rand] version = "^0.8" [dev-dependencies.serde_json] version = "^1.0" libsystemd-0.5.0/Cargo.toml.orig000064400000000000000000000022020072674642500147200ustar 00000000000000[package] name = "libsystemd" version = "0.5.0" authors = ["Luca Bruno ", "Sebastian Wiesner "] license = "MIT/Apache-2.0" repository = "https://github.com/lucab/libsystemd-rs" documentation = "https://docs.rs/libsystemd" description = "A pure-Rust client library to interact with systemd" keywords = ["systemd", "linux"] categories = ["api-bindings", "os::unix-apis"] readme = "README.md" exclude = [ ".gitignore", ".travis.yml", ] edition = "2018" [dependencies] hmac = "^0.12" libc = "^0.2" log = "^0.4" nix = "^0.23" nom = "7" serde = { version = "^1.0.91", features = ["derive"] } sha2 = "^0.10" thiserror = "^1.0" uuid = { version = "^0.8.1", features = ["serde"] } once_cell = "^1.8" [dev-dependencies] quickcheck = "^1.0" serde_json = "^1.0" rand = "^0.8" pretty_assertions = "^1.0" [[test]] name = "connected_to_journal" harness = false [package.metadata.release] publish = false push = false post-release-commit-message = "cargo: development version bump" pre-release-commit-message = "cargo: libsystemd release {{version}}" sign-commit = true sign-tag = true tag-message = "libsystemd {{version}}" libsystemd-0.5.0/LICENSE-APACHE-2.0000064400000000000000000000261360072674642500142660ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. libsystemd-0.5.0/LICENSE-MIT000064400000000000000000000017770072674642500135050ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. libsystemd-0.5.0/README.md000064400000000000000000000024620072674642500133200ustar 00000000000000# libsystemd [![crates.io](https://img.shields.io/crates/v/libsystemd.svg)](https://crates.io/crates/libsystemd) [![LoC](https://tokei.rs/b1/github/lucab/libsystemd-rs?category=code)](https://github.com/lucab/libsystemd-rs) [![Documentation](https://docs.rs/libsystemd/badge.svg)](https://docs.rs/libsystemd) A pure-Rust client library to work with systemd. It provides support to interact with systemd components available on modern Linux systems. This crate is entirely implemented in Rust, and does not require the libsystemd C library. NB: this crate is not yet features-complete. If you don't care about C dependency, check [rust-systemd](https://github.com/jmesmon/rust-systemd) instead. ## Example ```rust extern crate libsystemd; use libsystemd::daemon::{self, NotifyState}; fn main() { if !daemon::booted() { panic!("Not running systemd, early exit."); }; let sent = daemon::notify(true, &[NotifyState::Ready]).expect("notify failed"); if !sent { panic!("Notification not sent, early exit."); }; std::thread::park(); } ``` Some more examples are available under [examples](examples). ## License Licensed under either of * MIT license - * Apache License, Version 2.0 - at your option. libsystemd-0.5.0/examples/notify.rs000064400000000000000000000011610072674642500155300ustar 00000000000000extern crate libsystemd; use libsystemd::daemon::{self, NotifyState}; use std::{env, thread}; /* cargo build --example notify systemd-run --user --wait -p Type=notify ./target/debug/examples/notify [CUSTOM_STATUS] */ fn main() { if !daemon::booted() { println!("Not running systemd, early exit."); return; }; let state = match env::args().nth(1) { Some(s) => NotifyState::Status(s), None => NotifyState::Ready, }; let sent = daemon::notify(true, &[state]).expect("notify failed"); if !sent { println!("Notification not sent!"); } thread::park(); } libsystemd-0.5.0/examples/watchdog.rs000064400000000000000000000013700072674642500160220ustar 00000000000000extern crate libsystemd; use libsystemd::daemon::{self, NotifyState}; use std::thread; /* ``` [Service] WatchdogSec=1s ExecStart=/home/user/libsystemd-rs/target/debug/examples/watchdog ``` cargo build --example watchdog ; systemctl start --wait --user watchdog; systemctl status --user watchdog */ fn main() { if !daemon::booted() { println!("Not running systemd, early exit."); return; }; let timeout = daemon::watchdog_enabled(true).expect("watchdog disabled"); for i in 0..20 { let _sent = daemon::notify(false, &[NotifyState::Watchdog]).expect("notify failed"); println!("Notification #{} sent...", i); thread::sleep(timeout / 2); } println!("Blocking forever!"); thread::park(); } libsystemd-0.5.0/src/activation.rs000064400000000000000000000173350072674642500153440ustar 00000000000000use crate::errors::SdError; use nix::mqueue::mq_getattr; use nix::sys::socket::getsockname; use nix::sys::socket::SockAddr; use nix::sys::stat::fstat; use std::convert::TryFrom; use std::env; use std::os::unix::io::{IntoRawFd, RawFd}; use std::process; /// Minimum FD number used by systemd for passing sockets. const SD_LISTEN_FDS_START: RawFd = 3; /// Trait for checking the type of a file descriptor. pub trait IsType { /// Returns true if a file descriptor is a FIFO. fn is_fifo(&self) -> bool; /// Returns true if a file descriptor is a special file. fn is_special(&self) -> bool; /// Returns true if a file descriptor is a `PF_INET` socket. fn is_inet(&self) -> bool; /// Returns true if a file descriptor is a `PF_UNIX` socket. fn is_unix(&self) -> bool; /// Returns true if a file descriptor is a POSIX message queue descriptor. fn is_mq(&self) -> bool; } /// File descriptor passed by systemd to socket-activated services. /// /// See . #[derive(Debug, Clone)] pub struct FileDescriptor(SocketFd); /// Possible types of sockets. #[derive(Debug, Clone)] enum SocketFd { /// A FIFO named pipe (see `man 7 fifo`) Fifo(RawFd), /// A special file, such as character device nodes or special files in /// `/proc` and `/sys`. Special(RawFd), /// A `PF_INET` socket, such as UDP/TCP sockets. Inet(RawFd), /// A `PF_UNIX` socket (see `man 7 unix`). Unix(RawFd), /// A POSIX message queue (see `man 7 mq_overview`). Mq(RawFd), /// An unknown descriptor (possibly invalid, use with caution). Unknown(RawFd), } impl IsType for FileDescriptor { fn is_fifo(&self) -> bool { matches!(self.0, SocketFd::Fifo(_)) } fn is_special(&self) -> bool { matches!(self.0, SocketFd::Special(_)) } fn is_unix(&self) -> bool { matches!(self.0, SocketFd::Unix(_)) } fn is_inet(&self) -> bool { matches!(self.0, SocketFd::Inet(_)) } fn is_mq(&self) -> bool { matches!(self.0, SocketFd::Mq(_)) } } /// Check for file descriptors passed by systemd. /// /// Invoked by socket activated daemons to check for file descriptors needed by the service. /// If `unset_env` is true, the environment variables used by systemd will be cleared. pub fn receive_descriptors(unset_env: bool) -> Result, SdError> { let pid = env::var("LISTEN_PID"); let fds = env::var("LISTEN_FDS"); log::trace!("LISTEN_PID = {:?}; LISTEN_FDS = {:?}", pid, fds); if unset_env { env::remove_var("LISTEN_PID"); env::remove_var("LISTEN_FDS"); env::remove_var("LISTEN_FDNAMES"); } let pid = pid .map_err(|e| format!("failed to get LISTEN_PID: {}", e))? .parse::() .map_err(|e| format!("failed to parse LISTEN_PID: {}", e))?; let fds = fds .map_err(|e| format!("failed to get LISTEN_FDS: {}", e))? .parse::() .map_err(|e| format!("failed to parse LISTEN_FDS: {}", e))?; if process::id() != pid { return Err("PID mismatch".into()); } socks_from_fds(fds) } /// Check for named file descriptors passed by systemd. /// /// Like `receive_descriptors`, but this will also return a vector of names /// associated with each file descriptor. pub fn receive_descriptors_with_names( unset_env: bool, ) -> Result, SdError> { let pid = env::var("LISTEN_PID"); let fds = env::var("LISTEN_FDS"); let fdnames = env::var("LISTEN_FDNAMES"); log::trace!( "LISTEN_PID = {:?}; LISTEN_FDS = {:?}; LISTEN_FDNAMES = {:?}", pid, fds, fdnames ); if unset_env { env::remove_var("LISTEN_PID"); env::remove_var("LISTEN_FDS"); env::remove_var("LISTEN_FDNAMES"); } let pid = pid .map_err(|e| format!("failed to get LISTEN_PID: {}", e))? .parse::() .map_err(|e| format!("failed to parse LISTEN_PID: {}", e))?; let fds = fds .map_err(|e| format!("failed to get LISTEN_FDS: {}", e))? .parse::() .map_err(|e| format!("failed to parse LISTEN_FDS: {}", e))?; if process::id() != pid { return Err("PID mismatch".into()); } let fdnames = fdnames.map_err(|e| format!("failed to get LISTEN_FDNAMES: {}", e))?; let names = fdnames.split(':').map(String::from); let vec = socks_from_fds(fds)?; let out = vec.into_iter().zip(names).collect(); Ok(out) } fn socks_from_fds(num_fds: usize) -> Result, SdError> { let mut descriptors = Vec::with_capacity(num_fds); for fd_offset in 0..num_fds { let index = SD_LISTEN_FDS_START .checked_add(fd_offset as i32) .ok_or_else(|| format!("overlarge file descriptor index: {}", num_fds))?; let fd = FileDescriptor::try_from(index).unwrap_or_else(|(msg, val)| { log::warn!("{}", msg); FileDescriptor(SocketFd::Unknown(val)) }); descriptors.push(fd); } Ok(descriptors) } impl IsType for RawFd { fn is_fifo(&self) -> bool { fstat(*self) .map(|stat| (stat.st_mode & 0o0_170_000) == 0o010_000) .unwrap_or(false) } fn is_special(&self) -> bool { fstat(*self) .map(|stat| (stat.st_mode & 0o0_170_000) == 0o100_000) .unwrap_or(false) } fn is_inet(&self) -> bool { getsockname(*self) .map(|addr| matches!(addr, SockAddr::Inet(_))) .unwrap_or(false) } fn is_unix(&self) -> bool { getsockname(*self) .map(|addr| matches!(addr, SockAddr::Unix(_))) .unwrap_or(false) } fn is_mq(&self) -> bool { mq_getattr(*self).is_ok() } } impl TryFrom for FileDescriptor { type Error = (SdError, RawFd); fn try_from(value: RawFd) -> Result { if value.is_fifo() { return Ok(FileDescriptor(SocketFd::Fifo(value))); } else if value.is_special() { return Ok(FileDescriptor(SocketFd::Special(value))); } else if value.is_inet() { return Ok(FileDescriptor(SocketFd::Inet(value))); } else if value.is_unix() { return Ok(FileDescriptor(SocketFd::Unix(value))); } else if value.is_mq() { return Ok(FileDescriptor(SocketFd::Mq(value))); } let err_msg = format!( "conversion failure, possibly invalid or unknown file descriptor {}", value ); Err((err_msg.into(), value)) } } // TODO(lucab): replace with multiple safe `TryInto` helpers plus an `unsafe` fallback. impl IntoRawFd for FileDescriptor { fn into_raw_fd(self) -> RawFd { match self.0 { SocketFd::Fifo(fd) => fd, SocketFd::Special(fd) => fd, SocketFd::Inet(fd) => fd, SocketFd::Unix(fd) => fd, SocketFd::Mq(fd) => fd, SocketFd::Unknown(fd) => fd, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_socketype_is_unix() { let sock = FileDescriptor(SocketFd::Unix(0i32)); assert!(sock.is_unix()); } #[test] fn test_socketype_is_special() { let sock = FileDescriptor(SocketFd::Special(0i32)); assert!(sock.is_special()); } #[test] fn test_socketype_is_inet() { let sock = FileDescriptor(SocketFd::Inet(0i32)); assert!(sock.is_inet()); } #[test] fn test_socketype_is_fifo() { let sock = FileDescriptor(SocketFd::Fifo(0i32)); assert!(sock.is_fifo()); } #[test] fn test_socketype_is_mq() { let sock = FileDescriptor(SocketFd::Mq(0i32)); assert!(sock.is_mq()); } } libsystemd-0.5.0/src/daemon.rs000064400000000000000000000107360072674642500144440ustar 00000000000000use crate::errors::SdError; use libc::pid_t; use nix::unistd; use std::os::unix::net::UnixDatagram; use std::{env, fmt, fs, path, time}; /// Check for systemd presence at runtime. /// /// Return true if the system was booted with systemd. /// This check is based on the presence of the systemd /// runtime directory. pub fn booted() -> bool { fs::symlink_metadata("/run/systemd/system") .map(|p| p.is_dir()) .unwrap_or(false) } /// Check for watchdog support at runtime. /// /// Return a timeout before which the watchdog expects a /// response from the process, or `None` if watchdog support is /// not enabled. If `unset_env` is true, environment will be cleared. pub fn watchdog_enabled(unset_env: bool) -> Option { let env_usec = env::var("WATCHDOG_USEC").ok(); let env_pid = env::var("WATCHDOG_PID").ok(); if unset_env { env::remove_var("WATCHDOG_USEC"); env::remove_var("WATCHDOG_PID"); }; let timeout = { if let Some(usec) = env_usec.and_then(|usec_str| usec_str.parse::().ok()) { time::Duration::from_millis(usec / 1_000) } else { return None; } }; let pid = { if let Some(pid_str) = env_pid { if let Ok(p) = pid_str.parse::() { unistd::Pid::from_raw(p) } else { return None; } } else { return Some(timeout); } }; if unistd::getpid() == pid { Some(timeout) } else { None } } /// Notify service manager about status changes. /// /// Send a notification to the manager about service status changes. /// The returned boolean show whether notifications are supported for /// this service. If `unset_env` is true, environment will be cleared /// and no further notifications are possible. pub fn notify(unset_env: bool, state: &[NotifyState]) -> Result { let env_sock = env::var("NOTIFY_SOCKET").ok(); if unset_env { env::remove_var("NOTIFY_SOCKET"); }; let path = { if let Some(p) = env_sock.map(path::PathBuf::from) { p } else { return Ok(false); } }; let sock = UnixDatagram::unbound().map_err(|e| format!("failed to open datagram socket: {}", e))?; let msg = state .iter() .fold(String::new(), |res, s| res + &format!("{}\n", s)); let msg_len = msg.len(); let sent_len = sock .send_to(msg.as_bytes(), path) .map_err(|e| format!("failed to send datagram: {}", e))?; if sent_len != msg_len { return Err(format!("incomplete write, sent {} out of {}", sent_len, msg_len).into()); } Ok(true) } #[derive(Clone, Debug, PartialEq, Eq, Hash)] /// Status changes, see `sd_notify(3)`. pub enum NotifyState { /// D-Bus error-style error code. Buserror(String), /// errno-style error code. Errno(u8), /// A name for the submitted file descriptors. Fdname(String), /// Stores additional file descriptors in the service manager. Fdstore, /// The main process ID of the service, in case of forking applications. Mainpid(unistd::Pid), /// Custom state change, as a `KEY=VALUE` string. Other(String), /// Service startup is finished. Ready, /// Service is reloading. Reloading, /// Custom status change. Status(String), /// Service is beginning to shutdown. Stopping, /// Tell the service manager to update the watchdog timestamp. Watchdog, /// Reset watchdog timeout value during runtime. WatchdogUsec(u64), } impl fmt::Display for NotifyState { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { NotifyState::Buserror(ref s) => write!(f, "BUSERROR={}", s), NotifyState::Errno(e) => write!(f, "ERRNO={}", e), NotifyState::Fdname(ref s) => write!(f, "FDNAME={}", s), NotifyState::Fdstore => write!(f, "FDSTORE=1"), NotifyState::Mainpid(ref p) => write!(f, "MAINPID={}", p), NotifyState::Other(ref s) => write!(f, "{}", s), NotifyState::Ready => write!(f, "READY=1"), NotifyState::Reloading => write!(f, "RELOADING=1"), NotifyState::Status(ref s) => write!(f, "STATUS={}", s), NotifyState::Stopping => write!(f, "STOPPING=1"), NotifyState::Watchdog => write!(f, "WATCHDOG=1"), NotifyState::WatchdogUsec(u) => write!(f, "WATCHDOG_USEC={}", u), } } } libsystemd-0.5.0/src/errors.rs000064400000000000000000000012220072674642500145030ustar 00000000000000use thiserror::Error; /// Library errors. #[derive(Error, Debug)] #[error("libsystemd error: {msg}")] pub struct SdError { pub(crate) kind: ErrorKind, pub(crate) msg: String, } impl From<&str> for SdError { fn from(arg: &str) -> Self { Self { kind: ErrorKind::Generic, msg: arg.to_string(), } } } impl From for SdError { fn from(arg: String) -> Self { Self { kind: ErrorKind::Generic, msg: arg, } } } /// Markers for recoverable error kinds. #[derive(Debug, PartialEq, Eq)] pub(crate) enum ErrorKind { Generic, SysusersUnknownType, } libsystemd-0.5.0/src/id128.rs000064400000000000000000000111660072674642500140260ustar 00000000000000use crate::errors::SdError; use serde::{Deserialize, Serialize}; use std::io::Read; use std::{fmt, fs}; use uuid::Uuid; /// A 128-bits ID. #[derive(Clone, Eq, PartialEq, Deserialize, Serialize)] #[serde(transparent)] pub struct Id128 { #[serde(flatten, serialize_with = "Id128::ser_uuid")] uuid_v4: Uuid, } impl Id128 { /// Build an `Id128` from a slice of bytes. pub fn try_from_slice(bytes: &[u8]) -> Result { let uuid_v4 = Uuid::from_slice(bytes) .map_err(|e| format!("failed to parse ID from bytes slice: {}", e))?; // TODO(lucab): check for v4. Ok(Self { uuid_v4 }) } /// Parse an `Id128` from string. pub fn parse_str(input: S) -> Result where S: AsRef, { let uuid_v4 = Uuid::parse_str(input.as_ref()) .map_err(|e| format!("failed to parse ID from string: {}", e))?; // TODO(lucab): check for v4. Ok(Self { uuid_v4 }) } /// Hash this ID with an application-specific ID. pub fn app_specific(&self, app: &Self) -> Result { use hmac::{Hmac, Mac}; use sha2::Sha256; let mut mac = Hmac::::new_from_slice(self.uuid_v4.as_bytes()) .map_err(|_| "failed to prepare HMAC")?; mac.update(app.uuid_v4.as_bytes()); let mut hashed = mac.finalize().into_bytes(); if hashed.len() != 32 { return Err("short hash".into()); }; // Set version to 4. hashed[6] = (hashed[6] & 0x0F) | 0x40; // Set variant to DCE. hashed[8] = (hashed[8] & 0x3F) | 0x80; Self::try_from_slice(&hashed[..16]) } /// Return this ID as a lowercase hexadecimal string, without dashes. pub fn lower_hex(&self) -> String { let mut hex = String::new(); for byte in self.uuid_v4.as_bytes() { hex.push_str(&format!("{:02x}", byte)); } hex } /// Return this ID as a lowercase hexadecimal string, with dashes. pub fn dashed_hex(&self) -> String { format!("{}", self.uuid_v4.to_hyphenated_ref()) } /// Custom serialization (lower hex). fn ser_uuid(field: &Uuid, s: S) -> ::std::result::Result where S: ::serde::Serializer, { let mut hex = String::new(); for byte in field.as_bytes() { hex.push_str(&format!("{:02x}", byte)); } s.serialize_str(&hex) } } impl fmt::Debug for Id128 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.dashed_hex()) } } /// Return this machine unique ID. pub fn get_machine() -> Result { let mut buf = String::new(); let mut fd = fs::File::open("/etc/machine-id") .map_err(|e| format!("failed to open machine-id: {}", e))?; fd.read_to_string(&mut buf) .map_err(|e| format!("failed to read machine-id: {}", e))?; Id128::parse_str(buf.trim_end()) } /// Return this machine unique ID, hashed with an application-specific ID. pub fn get_machine_app_specific(app_id: &Id128) -> Result { let machine_id = get_machine()?; machine_id.app_specific(app_id) } #[cfg(test)] mod test { use super::*; #[test] fn basic_parse_str() { let input = "2e074e9b299c41a59923c51ae16f279b"; let id = Id128::parse_str(input).unwrap(); assert_eq!(id.lower_hex(), input); Id128::parse_str("").unwrap_err(); } #[test] fn basic_keyed_hash() { let input = "2e074e9b299c41a59923c51ae16f279b"; let machine_id = Id128::parse_str(input).unwrap(); assert_eq!(input, machine_id.lower_hex()); let key = "033b1b9b264441fcaa173e9e5bf35c5a"; let app_id = Id128::parse_str(key).unwrap(); assert_eq!(key, app_id.lower_hex()); let expected = "4d4a86c9c6644a479560ded5d19a30c5"; let hashed_id = Id128::parse_str(expected).unwrap(); let output = machine_id.app_specific(&app_id).unwrap(); assert_eq!(output, hashed_id); } #[test] fn basic_from_slice() { let input_str = "d86a4e9e4dca45c5bcd9846409bfa1ae"; let input = [ 0xd8, 0x6a, 0x4e, 0x9e, 0x4d, 0xca, 0x45, 0xc5, 0xbc, 0xd9, 0x84, 0x64, 0x09, 0xbf, 0xa1, 0xae, ]; let id = Id128::try_from_slice(&input).unwrap(); assert_eq!(input_str, id.lower_hex()); Id128::try_from_slice(&[]).unwrap_err(); } #[test] fn basic_debug() { let input = "0b37f793-aeb9-4d67-99e1-6e678d86781f"; let id = Id128::parse_str(input).unwrap(); assert_eq!(id.dashed_hex(), input); } } libsystemd-0.5.0/src/lib.rs000064400000000000000000000020230072674642500137350ustar 00000000000000//! A pure-Rust client library to work with systemd. //! //! It provides support to interact with systemd components available //! on modern Linux systems. This crate is entirely implemented //! in Rust, and does not require an external libsystemd dynamic library. //! //! ```rust //! use libsystemd::daemon::{self, NotifyState}; //! //! fn notify_ready() -> bool { //! if !daemon::booted() { //! println!("Not running systemd, early exit."); //! return false; //! }; //! //! let sent = daemon::notify(true, &[NotifyState::Ready]).expect("notify failed"); //! if !sent { //! println!("Notification not sent!"); //! }; //! sent //! } //! ``` /// Interfaces for socket-activated services. pub mod activation; /// Interfaces for systemd-aware daemons. pub mod daemon; /// Error handling. pub mod errors; /// APIs for processing 128-bits IDs. pub mod id128; /// Helpers for logging to `systemd-journald`. pub mod logging; pub mod sysusers; /// Helpers for working with systemd units. pub mod unit; libsystemd-0.5.0/src/logging.rs000064400000000000000000000372450072674642500146330ustar 00000000000000use crate::errors::SdError; use libc::{dev_t, ino_t}; use nix::fcntl::*; use nix::sys::memfd::memfd_create; use nix::sys::memfd::MemFdCreateFlag; use nix::sys::socket::{sendmsg, ControlMessage, MsgFlags, SockAddr}; use once_cell::sync::OnceCell; use std::collections::HashMap; use std::ffi::{CString, OsStr}; use std::fs::File; use std::io::Write; use std::os::unix::io::AsRawFd; use std::os::unix::io::FromRawFd; use std::os::unix::net::UnixDatagram; use std::str::FromStr; /// Default path of the systemd-journald `AF_UNIX` datagram socket. pub static SD_JOURNAL_SOCK_PATH: &str = "/run/systemd/journal/socket"; /// The shared socket to journald. static SD_SOCK: OnceCell = OnceCell::new(); /// Trait for checking the type of a file descriptor. /// Log priority values. /// /// See `man 3 syslog`. #[derive(Clone, Copy, Debug)] #[repr(u8)] pub enum Priority { /// System is unusable. Emergency = 0, /// Action must be taken immediately. Alert, /// Critical condition, Critical, /// Error condition. Error, /// Warning condition. Warning, /// Normal, but significant, condition. Notice, /// Informational message. Info, /// Debug message. Debug, } impl std::convert::From for u8 { fn from(p: Priority) -> Self { match p { Priority::Emergency => 0, Priority::Alert => 1, Priority::Critical => 2, Priority::Error => 3, Priority::Warning => 4, Priority::Notice => 5, Priority::Info => 6, Priority::Debug => 7, } } } #[inline(always)] fn is_valid_char(c: char) -> bool { c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_' } /// The variable name must be in uppercase and consist only of characters, /// numbers and underscores, and may not begin with an underscore. /// /// See /// for the reference implementation of journal_field_valid. fn is_valid_field(input: &str) -> bool { // journald doesn't allow empty fields or fields with more than 64 bytes if input.is_empty() || 64 < input.len() { return false; } // Fields starting with underscores are protected by journald if input.starts_with('_') { return false; } // Journald doesn't allow fields to start with digits if input.starts_with(|c: char| c.is_ascii_digit()) { return false; } input.chars().all(is_valid_char) } /// Add `field` and `payload` to journal fields `data` with explicit length encoding. /// /// Write /// /// 1. the field name, /// 2. an ASCII newline, /// 3. the payload size as LE encoded 64 bit integer, /// 4. the payload, and /// 5. a final ASCII newline /// /// to `data`. /// /// See for details. fn add_field_and_payload_explicit_length(data: &mut Vec, field: &str, payload: &str) { data.extend(field.as_bytes()); data.push(b'\n'); data.extend(&(payload.len() as u64).to_le_bytes()); data.extend(payload.as_bytes()); data.push(b'\n'); } /// Add a journal `field` and its `payload` to journal fields `data` with appropriate encoding. /// /// If `payload` does not contain a newline character use the simple journal field encoding, and /// write the field name and the payload separated by `=` and suffixed by a final new line. /// /// Otherwise encode the payload length explicitly with [[`add_field_and_payload_explicit_length`]]. /// /// See for details. fn add_field_and_payload(data: &mut Vec, field: &str, payload: &str) { if is_valid_field(field) { if payload.contains('\n') { add_field_and_payload_explicit_length(data, field, payload); } else { // If payload doesn't contain an newline directly write the field name and the payload data.extend(field.as_bytes()); data.push(b'='); data.extend(payload.as_bytes()); data.push(b'\n'); } } } /// Send a message with structured properties to the journal. /// /// The PRIORITY or MESSAGE fields from the vars iterator are always ignored in favour of the priority and message arguments. pub fn journal_send( priority: Priority, msg: &str, vars: impl Iterator, ) -> Result<(), SdError> where K: AsRef, V: AsRef, { let sock = SD_SOCK.get_or_try_init(|| { UnixDatagram::unbound().map_err(|e| format!("failed to open datagram socket: {}", e)) })?; let mut data = Vec::new(); add_field_and_payload(&mut data, "PRIORITY", &(u8::from(priority)).to_string()); add_field_and_payload(&mut data, "MESSAGE", msg); for (ref k, ref v) in vars { if k.as_ref() != "PRIORITY" && k.as_ref() != "MESSAGE" { add_field_and_payload(&mut data, k.as_ref(), v.as_ref()) } } // Message sending logic: // * fast path: data within datagram body. // * slow path: data in a sealed memfd, which is sent as an FD in ancillary data. // // Maximum data size is system dependent, thus this always tries the fast path and // falls back to the slow path if the former fails with `EMSGSIZE`. let fast_res = sock.send_to(&data, SD_JOURNAL_SOCK_PATH); let res = match fast_res { // `EMSGSIZE` (errno code 90) means the message was too long for a UNIX socket, Err(ref err) if err.raw_os_error() == Some(90) => send_memfd_payload(sock, &data), r => r.map_err(|err| err.to_string().into()), }; res.map_err(|e| { format!( "failed to print to journal at '{}': {}", SD_JOURNAL_SOCK_PATH, e ) })?; Ok(()) } /// Print a message to the journal with the given priority. pub fn journal_print(priority: Priority, msg: &str) -> Result<(), SdError> { let map: HashMap<&str, &str> = HashMap::new(); journal_send(priority, msg, map.iter()) } /// Send an overlarge payload to systemd-journald socket. /// /// This is a slow-path for sending a large payload that could not otherwise fit /// in a UNIX datagram. Payload is thus written to a memfd, which is sent as ancillary /// data. fn send_memfd_payload(sock: &UnixDatagram, data: &[u8]) -> Result { let memfd = { let fdname = &CString::new("libsystemd-rs-logging").map_err(|e| e.to_string())?; let tmpfd = memfd_create(fdname, MemFdCreateFlag::MFD_ALLOW_SEALING).map_err(|e| e.to_string())?; // SAFETY: `memfd_create` just returned this FD. let mut file = unsafe { File::from_raw_fd(tmpfd) }; file.write_all(data).map_err(|e| e.to_string())?; file }; // Seal the memfd, so that journald knows it can safely mmap/read it. fcntl(memfd.as_raw_fd(), FcntlArg::F_ADD_SEALS(SealFlag::all())).map_err(|e| e.to_string())?; let fds = &[memfd.as_raw_fd()]; let ancillary = [ControlMessage::ScmRights(fds)]; let path = SockAddr::new_unix(SD_JOURNAL_SOCK_PATH).map_err(|e| e.to_string())?; sendmsg( sock.as_raw_fd(), &[], &ancillary, MsgFlags::empty(), Some(&path), ) .map_err(|e| e.to_string())?; // Close our side of the memfd after we send it to systemd. drop(memfd); Ok(data.len()) } /// A systemd journal stream. #[derive(Debug, PartialEq)] pub struct JournalStream { /// The device number of the journal stream. device: dev_t, /// The inode number of the journal stream. inode: ino_t, } impl JournalStream { /// Parse the device and inode number from a systemd journal stream specification. /// /// This value is typically extracted from `$JOURNAL_STREAM`, and consists of the device and inode /// numbers of the systemd journal stream, separated by `:`. /// /// See also [`JournalStream::from_env()`] and [`JournalStream::from_env_default()`]. pub fn parse>(value: S) -> Result { let s = value.as_ref().to_str().ok_or_else(|| { format!( "Failed to parse journal stream: Value {:?} not UTF-8 encoded", value.as_ref() ) })?; let (device_s, inode_s) = s.find(':').map(|i| (&s[..i], &s[i + 1..])).ok_or_else(|| { format!( "Failed to parse journal stream: Missing separator ':' in value '{}'", s ) })?; let device = dev_t::from_str(device_s).map_err(|err| { format!( "Failed to parse journal stream: Device part is not a number '{}': {}", device_s, err ) })?; let inode = ino_t::from_str(inode_s).map_err(|err| { format!( "Failed to parse journal stream: Inode part is not a number '{}': {}", inode_s, err ) })?; Ok(JournalStream { device, inode }) } /// Parse the device and inode number of the systemd journal stream denoted by the given environment variable. /// /// See [`JournalStream::parse()`] for more information. pub fn from_env>(key: S) -> Result { Self::parse(std::env::var_os(&key).ok_or_else(|| { format!( "Failed to parse journal stream: Environment variable {:?} unset", key.as_ref() ) })?) } /// Parse the device and inode number of the systemd journal stream denoted by the default `$JOURNAL_STREAM` variable. /// /// See [`JournalStream::from_env()`] and [`JournalStream::parse()`]. pub fn from_env_default() -> Result { Self::from_env("JOURNAL_STREAM") } /// Get the journal stream that would correspond to the given file descriptor. /// /// Return a journal stream struct containing the device and inode number of the given file descriptor. pub fn from_fd(fd: F) -> std::io::Result { nix::sys::stat::fstat(fd.as_raw_fd()) .map(|stat| JournalStream { device: stat.st_dev, inode: stat.st_ino, }) .map_err(std::io::Error::from) } } /// Whether this process is directly connected to the journal. /// /// Inspects the `$JOURNAL_STREAM` environment variable and compares the device and inode /// numbers in this variable against the stdout and stderr file descriptors. /// /// Return `true` if either stream matches the device and inode numbers in `$JOURNAL_STREAM`, /// and `false` otherwise (or in case of any IO error). /// /// Systemd sets `$JOURNAL_STREAM` to the device and inode numbers of the standard output /// or standard error streams of the current process if either of these streams is connected /// to the systemd journal. /// /// Systemd explicitly recommends that services check this variable to upgrade their logging /// to the native systemd journal protocol. /// /// See section “Environment Variables Set or Propagated by the Service Manager” in /// [systemd.exec(5)][1] for more information. /// /// [1]: https://www.freedesktop.org/software/systemd/man/systemd.exec.html#Environment%20Variables%20Set%20or%20Propagated%20by%20the%20Service%20Manager pub fn connected_to_journal() -> bool { let stream = JournalStream::from_env_default().ok(); stream == JournalStream::from_fd(std::io::stderr()).ok() || stream == JournalStream::from_fd(std::io::stdout()).ok() } #[cfg(test)] mod tests { use super::*; fn ensure_journald_socket() -> bool { match std::fs::metadata(SD_JOURNAL_SOCK_PATH) { Ok(_) => true, Err(_) => { eprintln!( "skipped, journald socket not found at '{}'", SD_JOURNAL_SOCK_PATH ); false } } } #[test] fn test_journal_print_simple() { if !ensure_journald_socket() { return; } journal_print(Priority::Info, "TEST LOG!").unwrap(); } #[test] fn test_journal_print_large_buffer() { if !ensure_journald_socket() { return; } let data = "A".repeat(212995); journal_print(Priority::Debug, &data).unwrap(); } #[test] fn test_journal_send_simple() { if !ensure_journald_socket() { return; } let mut map: HashMap<&str, &str> = HashMap::new(); map.insert("TEST_JOURNALD_LOG1", "foo"); map.insert("TEST_JOURNALD_LOG2", "bar"); journal_send(Priority::Info, "Test Journald Log", map.iter()).unwrap() } #[test] fn test_journal_skip_fields() { if !ensure_journald_socket() { return; } let mut map: HashMap<&str, &str> = HashMap::new(); let priority = format!("{}", u8::from(Priority::Warning)); map.insert("TEST_JOURNALD_LOG3", "result"); map.insert("PRIORITY", &priority); map.insert("MESSAGE", "Duplicate value"); journal_send(Priority::Info, "Test Skip Fields", map.iter()).unwrap() } #[test] fn test_is_valid_field_lowercase_invalid() { let field = "test"; assert_eq!(is_valid_field(&field), false); } #[test] fn test_is_valid_field_uppercase_non_ascii_invalid() { let field = "TRÖT"; assert_eq!(is_valid_field(&field), false); } #[test] fn test_is_valid_field_uppercase_valid() { let field = "TEST"; assert_eq!(is_valid_field(&field), true); } #[test] fn test_is_valid_field_uppercase_non_alpha_invalid() { let field = "TE!ST"; assert_eq!(is_valid_field(&field), false); } #[test] fn test_is_valid_field_uppercase_leading_underscore_invalid() { let field = "_TEST"; assert_eq!(is_valid_field(&field), false); } #[test] fn test_is_valid_field_uppercase_leading_digit_invalid() { assert_eq!(is_valid_field("1TEST"), false); } #[test] fn add_field_and_payload_explicit_length_simple() { let mut data = Vec::new(); add_field_and_payload_explicit_length(&mut data, "FOO", "BAR"); assert_eq!( data, vec![b'F', b'O', b'O', b'\n', 3, 0, 0, 0, 0, 0, 0, 0, b'B', b'A', b'R', b'\n'] ); } #[test] fn add_field_and_payload_explicit_length_internal_newline() { let mut data = Vec::new(); add_field_and_payload_explicit_length(&mut data, "FOO", "B\nAR"); assert_eq!( data, vec![b'F', b'O', b'O', b'\n', 4, 0, 0, 0, 0, 0, 0, 0, b'B', b'\n', b'A', b'R', b'\n'] ); } #[test] fn add_field_and_payload_explicit_length_trailing_newline() { let mut data = Vec::new(); add_field_and_payload_explicit_length(&mut data, "FOO", "BAR\n"); assert_eq!( data, vec![b'F', b'O', b'O', b'\n', 4, 0, 0, 0, 0, 0, 0, 0, b'B', b'A', b'R', b'\n', b'\n'] ); } #[test] fn add_field_and_payload_simple() { let mut data = Vec::new(); add_field_and_payload(&mut data, "FOO", "BAR"); assert_eq!(data, "FOO=BAR\n".as_bytes()); } #[test] fn add_field_and_payload_internal_newline() { let mut data = Vec::new(); add_field_and_payload(&mut data, "FOO", "B\nAR"); assert_eq!( data, vec![b'F', b'O', b'O', b'\n', 4, 0, 0, 0, 0, 0, 0, 0, b'B', b'\n', b'A', b'R', b'\n'] ); } #[test] fn add_field_and_payload_trailing_newline() { let mut data = Vec::new(); add_field_and_payload(&mut data, "FOO", "BAR\n"); assert_eq!( data, vec![b'F', b'O', b'O', b'\n', 4, 0, 0, 0, 0, 0, 0, 0, b'B', b'A', b'R', b'\n', b'\n'] ); } } libsystemd-0.5.0/src/sysusers/format.rs000064400000000000000000000061620072674642500163670ustar 00000000000000use super::*; use std::fmt::{self, Display}; impl Display for SysusersEntry { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { SysusersEntry::AddRange(v) => write!(f, "{}", v), SysusersEntry::AddUserToGroup(v) => write!(f, "{}", v), SysusersEntry::CreateGroup(v) => write!(f, "{}", v), SysusersEntry::CreateUserAndGroup(v) => write!(f, "{}", v), } } } impl Display for AddRange { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "r - {}-{} - - -", self.from, self.to) } } impl Display for AddUserToGroup { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "m {} {} - - -", self.username, self.groupname,) } } impl Display for CreateGroup { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "g {} {} - - -", self.groupname, self.gid,) } } impl Display for CreateUserAndGroup { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "u {} {} \"{}\" {} {}", self.name, self.id, self.gecos, self.home_dir .as_deref() .map(|p| p.to_string_lossy()) .unwrap_or(Cow::Borrowed("-")), self.shell .as_deref() .map(|p| p.to_string_lossy()) .unwrap_or(Cow::Borrowed("-")), ) } } impl Display for IdOrPath { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { IdOrPath::Id(i) => write!(f, "{}", i), IdOrPath::UidGid((u, g)) => write!(f, "{}:{}", u, g), IdOrPath::UidGroupname((u, g)) => write!(f, "{}:{}", u, g), IdOrPath::Path(p) => write!(f, "{}", p.display()), IdOrPath::Automatic => write!(f, "-",), } } } impl Display for GidOrPath { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { GidOrPath::Gid(g) => write!(f, "{}", g), GidOrPath::Path(p) => write!(f, "{}", p.display()), GidOrPath::Automatic => write!(f, "-",), } } } #[cfg(test)] mod test { use super::*; #[test] fn test_formatters() { { let type_u = CreateUserAndGroup::new("foo0".to_string(), "test".to_string(), None, None) .unwrap(); let expected = r#"u foo0 - "test" - -"#; assert_eq!(type_u.to_string(), expected); } { let type_g = CreateGroup::new("foo1".to_string()).unwrap(); let expected = r#"g foo1 - - - -"#; assert_eq!(type_g.to_string(), expected); } { let type_r = AddRange::new(10, 20).unwrap(); let expected = r#"r - 10-20 - - -"#; assert_eq!(type_r.to_string(), expected); } { let type_m = AddUserToGroup::new("foo3".to_string(), "bar".to_string()).unwrap(); let expected = r#"m foo3 bar - - -"#; assert_eq!(type_m.to_string(), expected); } } } libsystemd-0.5.0/src/sysusers/mod.rs000064400000000000000000000321520072674642500156540ustar 00000000000000//! Helpers for working with `sysusers.d` configuration files. //! //! For the complete documentation see //! . //! //! ## Example //! //! ```rust //! # fn doctest_parse() -> Result<(), libsystemd::errors::SdError> { //! use libsystemd::sysusers; //! //! let config_fragment = r#" //! #Type Name ID GECOS Home directory Shell //! u httpd 404 "HTTP User" //! u _authd /usr/bin/authd "Authorization user" //! u postgres - "Postgresql Database" /var/lib/pgsql /usr/libexec/postgresdb //! g input - - //! m _authd input //! u root 0 "Superuser" /root /bin/zsh //! r - 500-900 //! "#; //! //! let mut reader = config_fragment.as_bytes(); //! let entries = sysusers::parse_from_reader(&mut reader)?; //! assert_eq!(entries.len(), 7); //! //! let users_and_groups: Vec<_> = entries //! .into_iter() //! .filter_map(|v| { //! match v.type_signature() { //! "u" | "g" => Some(v.name().to_string()), //! _ => None, //! } //! }) //! .collect(); //! assert_eq!(users_and_groups, vec!["httpd", "_authd", "postgres", "input", "root"]); //! # Ok(()) //! # } //! # doctest_parse().unwrap(); //! ``` pub(crate) use self::serialization::SysusersData; use crate::errors::SdError; pub use parse::parse_from_reader; use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::io::BufRead; use std::path::PathBuf; use std::str::FromStr; mod format; mod parse; mod serialization; /// Single entry in `sysusers.d` configuration format. #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] #[serde(untagged)] pub enum SysusersEntry { AddRange(AddRange), AddUserToGroup(AddUserToGroup), CreateGroup(CreateGroup), CreateUserAndGroup(CreateUserAndGroup), } impl SysusersEntry { /// Return the single-character signature for the "Type" field of this entry. pub fn type_signature(&self) -> &str { match self { SysusersEntry::AddRange(v) => v.type_signature(), SysusersEntry::AddUserToGroup(v) => v.type_signature(), SysusersEntry::CreateGroup(v) => v.type_signature(), SysusersEntry::CreateUserAndGroup(v) => v.type_signature(), } } /// Return the value for the "Name" field of this entry. pub fn name(&self) -> &str { match self { SysusersEntry::AddRange(_) => "-", SysusersEntry::AddUserToGroup(v) => &v.username, SysusersEntry::CreateGroup(v) => &v.groupname, SysusersEntry::CreateUserAndGroup(v) => &v.name, } } } /// Sysusers entry of type `r`. #[derive(Clone, Debug, PartialEq, Deserialize)] #[serde(try_from = "SysusersData")] pub struct AddRange { pub(crate) from: u32, pub(crate) to: u32, } impl AddRange { /// Create a new `AddRange` entry. pub fn new(from: u32, to: u32) -> Result { Ok(Self { from, to }) } /// Return the single-character signature for the "Type" field of this entry. pub fn type_signature(&self) -> &str { "r" } /// Return the lower end for the range of this entry. pub fn from(&self) -> u32 { self.from } /// Return the upper end for the range of this entry. pub fn to(&self) -> u32 { self.to } pub(crate) fn into_sysusers_entry(self) -> SysusersEntry { SysusersEntry::AddRange(self) } } /// Sysusers entry of type `m`. #[derive(Clone, Debug, PartialEq, Deserialize)] #[serde(try_from = "SysusersData")] pub struct AddUserToGroup { pub(crate) username: String, pub(crate) groupname: String, } impl AddUserToGroup { /// Create a new `AddUserToGroup` entry. pub fn new(username: String, groupname: String) -> Result { validate_name_strict(&username)?; validate_name_strict(&groupname)?; Ok(Self { username, groupname, }) } /// Return the single-character signature for the "Type" field of this entry. pub fn type_signature(&self) -> &str { "m" } /// Return the user name ("Name" field) of this entry. pub fn username(&self) -> &str { &self.username } /// Return the group name ("ID" field) of this entry. pub fn groupname(&self) -> &str { &self.groupname } pub(crate) fn into_sysusers_entry(self) -> SysusersEntry { SysusersEntry::AddUserToGroup(self) } } /// Sysusers entry of type `g`. #[derive(Clone, Debug, PartialEq, Deserialize)] #[serde(try_from = "SysusersData")] pub struct CreateGroup { pub(crate) groupname: String, pub(crate) gid: GidOrPath, } impl CreateGroup { /// Create a new `CreateGroup` entry. pub fn new(groupname: String) -> Result { Self::impl_new(groupname, GidOrPath::Automatic) } /// Create a new `CreateGroup` entry, using a numeric ID. pub fn new_with_gid(groupname: String, gid: u32) -> Result { Self::impl_new(groupname, GidOrPath::Gid(gid)) } /// Create a new `CreateGroup` entry, using a filepath reference. pub fn new_with_path(groupname: String, path: PathBuf) -> Result { Self::impl_new(groupname, GidOrPath::Path(path)) } pub(crate) fn impl_new(groupname: String, gid: GidOrPath) -> Result { validate_name_strict(&groupname)?; Ok(Self { groupname, gid }) } /// Return the single-character signature for the "Type" field of this entry. pub fn type_signature(&self) -> &str { "g" } /// Return the group name ("Name" field) of this entry. pub fn groupname(&self) -> &str { &self.groupname } /// Return whether GID is dynamically allocated at runtime. pub fn has_dynamic_gid(&self) -> bool { matches!(self.gid, GidOrPath::Automatic) } /// Return the group identifier (GID) of this entry, if statically set. pub fn static_gid(&self) -> Option { match self.gid { GidOrPath::Gid(n) => Some(n), _ => None, } } pub(crate) fn into_sysusers_entry(self) -> SysusersEntry { SysusersEntry::CreateGroup(self) } } /// Sysusers entry of type `u`. #[derive(Clone, Debug, PartialEq, Deserialize)] #[serde(try_from = "SysusersData")] pub struct CreateUserAndGroup { pub(crate) name: String, pub(crate) id: IdOrPath, pub(crate) gecos: String, pub(crate) home_dir: Option, pub(crate) shell: Option, } impl CreateUserAndGroup { /// Create a new `CreateUserAndGroup` entry, using a filepath reference. pub fn new( name: String, gecos: String, home_dir: Option, shell: Option, ) -> Result { Self::impl_new(name, gecos, home_dir, shell, IdOrPath::Automatic) } /// Create a new `CreateUserAndrGroup` entry, using a numeric ID. pub fn new_with_id( name: String, id: u32, gecos: String, home_dir: Option, shell: Option, ) -> Result { Self::impl_new(name, gecos, home_dir, shell, IdOrPath::Id(id)) } /// Create a new `CreateUserAndGroup` entry, using a UID and a GID. pub fn new_with_uid_gid( name: String, uid: u32, gid: u32, gecos: String, home_dir: Option, shell: Option, ) -> Result { Self::impl_new(name, gecos, home_dir, shell, IdOrPath::UidGid((uid, gid))) } /// Create a new `CreateUserAndGroup` entry, using a UID and a groupname. pub fn new_with_uid_groupname( name: String, uid: u32, groupname: String, gecos: String, home_dir: Option, shell: Option, ) -> Result { validate_name_strict(&groupname)?; Self::impl_new( name, gecos, home_dir, shell, IdOrPath::UidGroupname((uid, groupname)), ) } /// Create a new `CreateUserAndGroup` entry, using a filepath reference. pub fn new_with_path( name: String, path: PathBuf, gecos: String, home_dir: Option, shell: Option, ) -> Result { Self::impl_new(name, gecos, home_dir, shell, IdOrPath::Path(path)) } pub(crate) fn impl_new( name: String, gecos: String, home_dir: Option, shell: Option, id: IdOrPath, ) -> Result { validate_name_strict(&name)?; Ok(Self { name, id, gecos, home_dir, shell, }) } /// Return the single-character signature for the "Type" field of this entry. pub fn type_signature(&self) -> &str { "u" } /// Return the user and group name ("Name" field) of this entry. pub fn name(&self) -> &str { &self.name } /// Return whether UID and GID are dynamically allocated at runtime. pub fn has_dynamic_ids(&self) -> bool { matches!(self.id, IdOrPath::Automatic) } /// Return the user identifier (UID) of this entry, if statically set. pub fn static_uid(&self) -> Option { match self.id { IdOrPath::Id(n) => Some(n), IdOrPath::UidGid((n, _)) => Some(n), IdOrPath::UidGroupname((n, _)) => Some(n), _ => None, } } /// Return the groups identifier (GID) of this entry, if statically set. pub fn static_gid(&self) -> Option { match self.id { IdOrPath::Id(n) => Some(n), IdOrPath::UidGid((_, n)) => Some(n), _ => None, } } pub(crate) fn into_sysusers_entry(self) -> SysusersEntry { SysusersEntry::CreateUserAndGroup(self) } } /// ID entity for `CreateUserAndGroup`. #[derive(Clone, Debug, PartialEq)] pub(crate) enum IdOrPath { Id(u32), UidGid((u32, u32)), UidGroupname((u32, String)), Path(PathBuf), Automatic, } impl FromStr for IdOrPath { type Err = SdError; fn from_str(value: &str) -> Result { if value == "-" { return Ok(IdOrPath::Automatic); } if value.starts_with('/') { return Ok(IdOrPath::Path(value.into())); } if let Ok(single_id) = value.parse() { return Ok(IdOrPath::Id(single_id)); } let tokens: Vec<_> = value.split(':').filter(|s| !s.is_empty()).collect(); if tokens.len() == 2 { let uid: u32 = tokens[0].parse().map_err(|_| "invalid user id")?; let id = match tokens[1].parse() { Ok(gid) => IdOrPath::UidGid((uid, gid)), _ => { let groupname = tokens[1].to_string(); validate_name_strict(&groupname)?; IdOrPath::UidGroupname((uid, groupname)) } }; return Ok(id); } Err(format!("unexpected user ID '{}'", value).into()) } } /// ID entity for `CreateGroup`. #[derive(Clone, Debug, PartialEq)] pub(crate) enum GidOrPath { Gid(u32), Path(PathBuf), Automatic, } impl FromStr for GidOrPath { type Err = SdError; fn from_str(value: &str) -> Result { if value == "-" { return Ok(GidOrPath::Automatic); } if value.starts_with('/') { return Ok(GidOrPath::Path(value.into())); } if let Ok(parsed_gid) = value.parse() { return Ok(GidOrPath::Gid(parsed_gid)); } Err(format!("unexpected group ID '{}'", value).into()) } } /// Validate a sysusers name in strict mode. pub fn validate_name_strict(input: &str) -> Result<(), SdError> { if input.is_empty() { return Err(SdError::from("empty name")); } if input.len() > 31 { let err_msg = format!( "overlong sysusers name '{}' (more than 31 characters)", input ); return Err(SdError::from(err_msg)); } for (index, ch) in input.char_indices() { if index == 0 { if !(ch.is_ascii_alphabetic() || ch == '_') { let err_msg = format!( "invalid starting character '{}' in sysusers name '{}'", ch, input ); return Err(SdError::from(err_msg)); } } else if !(ch.is_ascii_alphanumeric() || ch == '_' || ch == '-') { let err_msg = format!("invalid character '{}' in sysusers name '{}'", ch, input); return Err(SdError::from(err_msg)); } } Ok(()) } #[cfg(test)] mod test { use super::*; #[test] fn test_validate_name_strict() { let err_cases = vec!["-foo", "10bar", "42"]; for entry in err_cases { validate_name_strict(entry).unwrap_err(); } let ok_cases = vec!["_authd", "httpd"]; for entry in ok_cases { validate_name_strict(entry).unwrap(); } } } libsystemd-0.5.0/src/sysusers/parse.rs000064400000000000000000000175600072674642500162150ustar 00000000000000use super::*; use nom::bytes::complete::{tag, take_while1}; use nom::character::complete::{anychar, multispace0, multispace1}; use nom::{Finish, IResult}; use std::convert::TryInto; use std::str::FromStr; /// Parse `sysusers.d` configuration entries from a buffered reader. pub fn parse_from_reader(bufrd: &mut impl BufRead) -> Result, SdError> { use crate::errors::ErrorKind; let mut output = vec![]; for (index, item) in bufrd.lines().enumerate() { let linenumber = index.saturating_add(1); let line = item.map_err(|e| format!("failed to read line {}: {}", linenumber, e))?; let data = line.trim(); // Skip empty lines and comments. if data.is_empty() || data.starts_with('#') { continue; } match data.parse() { Ok(entry) => output.push(entry), Err(SdError { kind, msg }) if kind == ErrorKind::SysusersUnknownType => { log::warn!("skipped line {}: {}", linenumber, msg); } Err(e) => { let msg = format!( "failed to parse sysusers entry at line {}: {}", linenumber, e.msg ); return Err(msg.into()); } }; } Ok(output) } impl FromStr for SysusersEntry { type Err = SdError; fn from_str(s: &str) -> Result { use crate::errors::ErrorKind; let input = s.trim(); match input.chars().next() { Some('g') => CreateGroup::from_str(input).map(|v| v.into_sysusers_entry()), Some('m') => AddUserToGroup::from_str(input).map(|v| v.into_sysusers_entry()), Some('r') => AddRange::from_str(input).map(|v| v.into_sysusers_entry()), Some('u') => CreateUserAndGroup::from_str(input).map(|v| v.into_sysusers_entry()), Some(t) => { let unknown = SdError { kind: ErrorKind::SysusersUnknownType, msg: format!("unknown sysusers type signature '{}'", t), }; Err(unknown) } None => Err("missing sysusers type signature".into()), } } } impl FromStr for AddRange { type Err = SdError; fn from_str(s: &str) -> Result { let data = parse_to_sysusers_data(s)?; data.try_into() } } impl FromStr for AddUserToGroup { type Err = SdError; fn from_str(s: &str) -> Result { let data = parse_to_sysusers_data(s)?; data.try_into() } } impl FromStr for CreateGroup { type Err = SdError; fn from_str(s: &str) -> Result { let data = parse_to_sysusers_data(s)?; data.try_into() } } impl FromStr for CreateUserAndGroup { type Err = SdError; fn from_str(s: &str) -> Result { let data = parse_to_sysusers_data(s)?; data.try_into() } } /// Parse the content of a sysusers entry as `SysusersData`. fn parse_to_sysusers_data(line: &str) -> Result { let (rest, data) = parse_line(line).finish().map_err(|e| { format!( "parsing failed due to '{}' at '{}'", e.code.description(), e.input ) })?; if !rest.is_empty() { return Err(format!("invalid trailing data: '{}'", rest).into()); } Ok(data) } fn parse_line(input: &str) -> IResult<&str, SysusersData> { let rest = input; let (rest, kind) = { let (rest, kind) = anychar(rest)?; let (rest, _) = multispace1(rest)?; (rest, kind.to_string()) }; let (rest, name) = { let (rest, name) = take_while1(|c: char| !c.is_ascii_whitespace())(rest)?; let (rest, _) = multispace1(rest)?; (rest, name.to_string()) }; let (rest, id) = { let (rest, id) = take_while1(|c: char| !c.is_ascii_whitespace())(rest)?; let (rest, _) = multispace0(rest)?; (rest, id.to_string()) }; let (rest, gecos) = { let (rest, gecos) = parse_opt_string(rest)?; let (rest, _) = multispace0(rest)?; (rest, gecos.map(|s| s.to_string())) }; let (rest, home_dir) = { let (rest, home_dir) = parse_opt_string(rest)?; let (rest, _) = multispace0(rest)?; (rest, home_dir.map(|s| s.to_string())) }; let (rest, shell) = { let (rest, shell) = parse_opt_string(rest)?; let (rest, _) = multispace0(rest)?; (rest, shell.map(|s| s.to_string())) }; let data = SysusersData { kind, name, id, gecos, home_dir, shell, }; Ok((rest, data)) } fn parse_opt_string(input: &str) -> IResult<&str, Option<&str>> { match input.chars().next() { None => Ok((input, None)), Some('"') => parse_quoted_string(input), _ => parse_plain_string(input), } } // XXX(lucab): should this account for inner escaped quotes? fn parse_quoted_string(input: &str) -> IResult<&str, Option<&str>> { let rest = input; let (rest, _) = tag("\"")(rest)?; let (rest, txt) = take_while1(|c: char| c != '"')(rest)?; let (rest, _) = tag("\"")(rest)?; Ok((rest, Some(txt))) } fn parse_plain_string(input: &str) -> IResult<&str, Option<&str>> { let rest = input; let (rest, txt) = take_while1(|c: char| !c.is_ascii_whitespace())(rest)?; Ok((rest, Some(txt))) } #[cfg(test)] mod test { use super::*; use crate::sysusers; #[test] fn test_type_g() { { let input = r#"g input - - - -"#; let expected = CreateGroup::new("input".to_string()).unwrap(); let output: CreateGroup = input.parse().unwrap(); assert_eq!(output, expected); let line = output.to_string(); assert_eq!(line, input); } } #[test] fn test_type_m() { { let input = r#"m _authd input - - -"#; let expected = AddUserToGroup::new("_authd".to_string(), "input".to_string()).unwrap(); let output: AddUserToGroup = input.parse().unwrap(); assert_eq!(output, expected); let line = output.to_string(); assert_eq!(line, input); } } #[test] fn test_type_r() { { let input = r#"r - 500-900 - - -"#; let expected = AddRange::new(500, 900).unwrap(); let output: AddRange = input.parse().unwrap(); assert_eq!(output, expected); let line = output.to_string(); assert_eq!(line, input); } } #[test] fn test_type_u() { { let input = r#"u postgres - "Postgresql Database" /var/lib/pgsql /usr/libexec/postgresdb"#; let expected = CreateUserAndGroup::new( "postgres".to_string(), "Postgresql Database".to_string(), Some("/var/lib/pgsql".to_string().into()), Some("/usr/libexec/postgresdb".to_string().into()), ) .unwrap(); let output: CreateUserAndGroup = input.parse().unwrap(); assert_eq!(output, expected); let line = output.to_string(); assert_eq!(line, input); } } #[test] fn test_parse_from_reader() { let config_fragment = r#" #Type Name ID GECOS Home directory Shell u httpd 404 "HTTP User" u _authd /usr/bin/authd "Authorization user" # Test comment u postgres - "Postgresql Database" /var/lib/pgsql /usr/libexec/postgresdb g input - - m _authd input u root 0 "Superuser" /root /bin/zsh r - 500-900 "#; let mut reader = config_fragment.as_bytes(); let entries = sysusers::parse_from_reader(&mut reader).unwrap(); assert_eq!(entries.len(), 7); } } libsystemd-0.5.0/src/sysusers/serialization.rs000064400000000000000000000306030072674642500177510ustar 00000000000000use super::*; use serde::ser::SerializeStruct; use serde::{Deserialize, Serialize, Serializer}; use std::convert::TryFrom; /// Number of fields in each sysusers entry. const SYSUSERS_FIELDS: usize = 6; /// Intermediate format holding raw data for deserialization. #[derive(Clone, Debug, PartialEq, Deserialize)] pub(crate) struct SysusersData { #[serde(rename(deserialize = "Type"))] pub(crate) kind: String, #[serde(rename(deserialize = "Name"))] pub(crate) name: String, #[serde(rename(deserialize = "ID"))] pub(crate) id: String, #[serde(rename(deserialize = "GECOS"))] pub(crate) gecos: Option, #[serde(rename(deserialize = "Home directory"))] pub(crate) home_dir: Option, #[serde(rename(deserialize = "Shell"))] pub(crate) shell: Option, } impl TryFrom for AddRange { type Error = SdError; fn try_from(value: SysusersData) -> Result { if value.kind != "r" { return Err(format!("unexpected sysuser entry of type '{}'", value.kind).into()); }; ensure_field_none_or_automatic("GECOS", &value.gecos)?; ensure_field_none_or_automatic("Home directory", &value.home_dir)?; ensure_field_none_or_automatic("Shell", &value.shell)?; let tokens: Vec<_> = value.id.split('-').collect(); let (from, to) = match tokens.len() { 1 => (tokens[0], tokens[0]), 2 => (tokens[0], tokens[1]), _ => return Err(format!("invalid range specifier '{}'", value.id).into()), }; let from_id = from.parse().map_err(|_| "invalid starting range ID")?; let to_id = to.parse().map_err(|_| "invalid ending range ID")?; Self::new(from_id, to_id) } } impl TryFrom for AddUserToGroup { type Error = SdError; fn try_from(value: SysusersData) -> Result { if value.kind != "m" { return Err(format!("unexpected sysuser entry of type '{}'", value.kind).into()); } ensure_field_none_or_automatic("GECOS", &value.gecos)?; ensure_field_none_or_automatic("Home directory", &value.home_dir)?; ensure_field_none_or_automatic("Shell", &value.shell)?; Self::new(value.name, value.id) } } impl TryFrom for CreateGroup { type Error = SdError; fn try_from(value: SysusersData) -> Result { if value.kind != "g" { return Err(format!("unexpected sysuser entry of type '{}'", value.kind).into()); } ensure_field_none_or_automatic("GECOS", &value.gecos)?; ensure_field_none_or_automatic("Home directory", &value.home_dir)?; ensure_field_none_or_automatic("Shell", &value.shell)?; let gid: GidOrPath = value.id.parse()?; Self::impl_new(value.name, gid) } } impl TryFrom for CreateUserAndGroup { type Error = SdError; fn try_from(value: SysusersData) -> Result { if value.kind != "u" { return Err(format!("unexpected sysuser entry of type '{}'", value.kind).into()); } let id: IdOrPath = value.id.parse()?; Self::impl_new( value.name, value.gecos.unwrap_or_default(), value.home_dir.map(Into::into), value.shell.map(Into::into), id, ) } } impl Serialize for AddRange { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut state = serializer.serialize_struct("AddRange", SYSUSERS_FIELDS)?; state.serialize_field("Type", self.type_signature())?; state.serialize_field("Name", "-")?; state.serialize_field("ID", &format!("{}-{}", self.from, self.to))?; state.serialize_field("GECOS", &Option::::None)?; state.serialize_field("Home directory", &Option::::None)?; state.serialize_field("Shell", &Option::::None)?; state.end() } } impl Serialize for AddUserToGroup { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut state = serializer.serialize_struct("AddUserToGroup", SYSUSERS_FIELDS)?; state.serialize_field("Type", self.type_signature())?; state.serialize_field("Name", &self.username)?; state.serialize_field("ID", &self.groupname)?; state.serialize_field("GECOS", &Option::::None)?; state.serialize_field("Home directory", &Option::::None)?; state.serialize_field("Shell", &Option::::None)?; state.end() } } impl Serialize for CreateGroup { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut state = serializer.serialize_struct("CreateGroup", SYSUSERS_FIELDS)?; state.serialize_field("Type", self.type_signature())?; state.serialize_field("Name", &self.groupname)?; state.serialize_field("ID", &self.gid)?; state.serialize_field("GECOS", &Option::::None)?; state.serialize_field("Home directory", &Option::::None)?; state.serialize_field("Shell", &Option::::None)?; state.end() } } impl Serialize for CreateUserAndGroup { fn serialize(&self, serializer: S) -> Result where S: Serializer, { let mut state = serializer.serialize_struct("CreateUserAndGroup", SYSUSERS_FIELDS)?; state.serialize_field("Type", self.type_signature())?; state.serialize_field("Name", &self.name)?; state.serialize_field("ID", &self.id)?; state.serialize_field("GECOS", &self.gecos)?; state.serialize_field("Home directory", &self.home_dir)?; state.serialize_field("Shell", &self.shell)?; state.end() } } impl Serialize for IdOrPath { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(&self.to_string()) } } impl Serialize for GidOrPath { fn serialize(&self, serializer: S) -> Result where S: Serializer, { serializer.serialize_str(&self.to_string()) } } /// Ensure that a field value is either missing or using the default value `-`. fn ensure_field_none_or_automatic( field_name: &str, input: &Option>, ) -> Result<(), SdError> { if let Some(val) = input { if val.as_ref() != "-" { return Err(format!("invalid {} content: '{}'", field_name, val.as_ref()).into()); } } Ok(()) } #[cfg(test)] mod test { use super::*; #[test] fn test_serialization() { { let input = AddRange::new(10, 20).unwrap(); let expected = r#"{"Type":"r","Name":"-","ID":"10-20","GECOS":null,"Home directory":null,"Shell":null}"#; let output = serde_json::to_string(&input).unwrap(); assert_eq!(output, expected); let entry = SysusersEntry::AddRange(input); let output = serde_json::to_string(&entry).unwrap(); assert_eq!(output, expected); } { let input = AddUserToGroup::new("foo3".to_string(), "bar".to_string()).unwrap(); let expected = r#"{"Type":"m","Name":"foo3","ID":"bar","GECOS":null,"Home directory":null,"Shell":null}"#; let output = serde_json::to_string(&input).unwrap(); assert_eq!(output, expected); let entry = SysusersEntry::AddUserToGroup(input); let output = serde_json::to_string(&entry).unwrap(); assert_eq!(output, expected); } { let input = CreateGroup::new("foo1".to_string()).unwrap(); let expected = r#"{"Type":"g","Name":"foo1","ID":"-","GECOS":null,"Home directory":null,"Shell":null}"#; let output = serde_json::to_string(&input).unwrap(); assert_eq!(output, expected); let entry = SysusersEntry::CreateGroup(input); let output = serde_json::to_string(&entry).unwrap(); assert_eq!(output, expected); } { let input = CreateUserAndGroup::new("foo0".to_string(), "test".to_string(), None, None) .unwrap(); let expected = r#"{"Type":"u","Name":"foo0","ID":"-","GECOS":"test","Home directory":null,"Shell":null}"#; let output = serde_json::to_string(&input).unwrap(); assert_eq!(output, expected); let entry = SysusersEntry::CreateUserAndGroup(input); let output = serde_json::to_string(&entry).unwrap(); assert_eq!(output, expected); } } #[test] fn test_deserialization() { { let input = r#"{"Type":"r","Name":"-","ID":"50-200","GECOS":null,"Home directory":null,"Shell":null}"#; let expected = AddRange::new(50, 200).unwrap(); let output: AddRange = serde_json::from_str(input).unwrap(); assert_eq!(output, expected); let output: SysusersEntry = serde_json::from_str(input).unwrap(); assert_eq!(output, SysusersEntry::AddRange(expected)); } { let input = r#"{"Type":"m","Name":"foo3","ID":"bar","GECOS":null,"Home directory":null,"Shell":null}"#; let expected = AddUserToGroup::new("foo3".to_string(), "bar".to_string()).unwrap(); let output: AddUserToGroup = serde_json::from_str(input).unwrap(); assert_eq!(output, expected); let output: SysusersEntry = serde_json::from_str(input).unwrap(); assert_eq!(output, SysusersEntry::AddUserToGroup(expected)); } { let input = r#"{"Type":"g","Name":"foo1","ID":"-","GECOS":null,"Home directory":null,"Shell":null}"#; let expected = CreateGroup::new("foo1".to_string()).unwrap(); let output: CreateGroup = serde_json::from_str(input).unwrap(); assert_eq!(output, expected); let output: SysusersEntry = serde_json::from_str(input).unwrap(); assert_eq!(output, SysusersEntry::CreateGroup(expected)); } { let input = r#"{"Type":"u","Name":"foo0","ID":"-","GECOS":"test","Home directory":null,"Shell":null}"#; let expected = CreateUserAndGroup::new("foo0".to_string(), "test".to_string(), None, None) .unwrap(); let output: CreateUserAndGroup = serde_json::from_str(input).unwrap(); assert_eq!(output, expected); let output: SysusersEntry = serde_json::from_str(input).unwrap(); assert_eq!(output, SysusersEntry::CreateUserAndGroup(expected)); } } #[test] fn test_serde_roundtrip() { { let input = AddRange::new(10, 20).unwrap(); let json = serde_json::to_string(&input).unwrap(); let output: AddRange = serde_json::from_str(&json).unwrap(); assert_eq!(output, input); let output: SysusersEntry = serde_json::from_str(&json).unwrap(); assert_eq!(output, SysusersEntry::AddRange(input)); } { let input = AddUserToGroup::new("foo3".to_string(), "bar".to_string()).unwrap(); let json = serde_json::to_string(&input).unwrap(); let output: AddUserToGroup = serde_json::from_str(&json).unwrap(); assert_eq!(output, input); let output: SysusersEntry = serde_json::from_str(&json).unwrap(); assert_eq!(output, SysusersEntry::AddUserToGroup(input)); } { let input = CreateGroup::new("foo1".to_string()).unwrap(); let json = serde_json::to_string(&input).unwrap(); let output: CreateGroup = serde_json::from_str(&json).unwrap(); assert_eq!(output, input); let output: SysusersEntry = serde_json::from_str(&json).unwrap(); assert_eq!(output, SysusersEntry::CreateGroup(input)); } { let input = CreateUserAndGroup::new("foo0".to_string(), "test".to_string(), None, None) .unwrap(); let json = serde_json::to_string(&input).unwrap(); let output: CreateUserAndGroup = serde_json::from_str(&json).unwrap(); assert_eq!(output, input); let output: SysusersEntry = serde_json::from_str(&json).unwrap(); assert_eq!(output, SysusersEntry::CreateUserAndGroup(input)); } } } libsystemd-0.5.0/src/unit.rs000064400000000000000000000072030072674642500141530ustar 00000000000000/// Unit name escaping, like `systemd-escape`. pub fn escape_name(name: &str) -> String { if name.is_empty() { return "".to_string(); } let parts: Vec = name .bytes() .enumerate() .map(|(n, b)| escape_byte(b, n)) .collect(); parts.join("") } /// Path escaping, like `systemd-escape --path`. pub fn escape_path(name: &str) -> String { let trimmed = name.trim_matches('/'); if trimmed.is_empty() { return "-".to_string(); } let mut slash_seq = false; let parts: Vec = trimmed .bytes() .filter(|b| { let is_slash = *b == b'/'; let res = !(is_slash && slash_seq); slash_seq = is_slash; res }) .enumerate() .map(|(n, b)| escape_byte(b, n)) .collect(); parts.join("") } fn escape_byte(b: u8, index: usize) -> String { let c = char::from(b); match c { '/' => '-'.to_string(), ':' | '_' | '0'..='9' | 'a'..='z' | 'A'..='Z' => c.to_string(), '.' if index > 0 => c.to_string(), _ => format!(r#"\x{:02x}"#, b), } } #[cfg(test)] mod test { use crate::unit::*; use quickcheck::quickcheck; quickcheck! { fn test_byte_escape_length(xs: u8, n: usize) -> bool { let out = escape_byte(xs, n); out.len() == 1 || out.len() == 4 } } #[test] fn test_name_escape() { let cases = vec![ // leave empty string empty (r#""#, r#""#), // escape leading dot (r#".foo/.bar"#, r#"\x2efoo-.bar"#), // escape disallowed (r#"///..\-!#??///"#, r#"---..\x5c\x2d\x21\x23\x3f\x3f---"#), // escape real-world example ( r#"user-cloudinit@/var/lib/coreos/vagrant/vagrantfile-user-data.service"#, r#"user\x2dcloudinit\x40-var-lib-coreos-vagrant-vagrantfile\x2duser\x2ddata.service"#, ), ]; for t in cases { let res = escape_name(t.0); assert_eq!(res, t.1.to_string()); } } #[test] fn test_path_escape() { let cases = vec![ // turn empty string path into escaped / (r#""#, r#"-"#), // turn redundant ////s into single escaped / (r#"/////////"#, r#"-"#), // remove all redundant ////s (r#"///foo////bar/////tail//////"#, r#"foo-bar-tail"#), // escape leading dot (r#"."#, r#"\x2e"#), (r#"/."#, r#"\x2e"#), (r#"/////////.///////////////"#, r#"\x2e"#), (r#"....."#, r#"\x2e...."#), (r#"/.foo/.bar"#, r#"\x2efoo-.bar"#), (r#".foo/.bar"#, r#"\x2efoo-.bar"#), // escape disallowed (r#"///..\-!#??///"#, r#"\x2e.\x5c\x2d\x21\x23\x3f\x3f"#), ]; for t in cases { let res = escape_path(t.0); assert_eq!(res, t.1.to_string()); } } quickcheck! { fn test_path_escape_nonempty(xs: String) -> bool { let out = escape_path(&xs); !out.is_empty() } } quickcheck! { fn test_path_escape_no_slash(xs: String) -> bool { let out = escape_path(&xs); !out.contains('/') } } quickcheck! { fn test_path_escape_no_dash_runs(xs: String) -> bool { let out = escape_path(&xs); !out.contains("--") } } quickcheck! { fn test_path_escape_no_leading_dot(xs: String) -> bool { let out = escape_path(&xs); !out.starts_with('.') } } } libsystemd-0.5.0/tests/connected_to_journal.rs000064400000000000000000000062700072674642500177500ustar 00000000000000#![deny(warnings, clippy::all)] use std::collections::HashMap; use std::env::VarError; use std::process::Command; use pretty_assertions::assert_eq; use rand::distributions::Alphanumeric; use rand::Rng; use libsystemd::logging::*; fn random_target(prefix: &str) -> String { format!( "{}_{}", prefix, rand::thread_rng() .sample_iter(&Alphanumeric) .take(10) .map(char::from) .collect::() ) } #[derive(Debug, Copy, Clone)] enum Journal { User, System, } fn read_from_journal(journal: Journal, target: &str) -> Vec> { let stdout = String::from_utf8( Command::new("journalctl") .arg(match journal { Journal::User => "--user", Journal::System => "--system", }) .arg("--output=json") .arg(format!("TARGET={}", target)) .output() .unwrap() .stdout, ) .unwrap(); stdout .lines() .map(|l| serde_json::from_str(l).unwrap()) .collect() } fn main() { let env_name = "_TEST_LOG_TARGET"; // On Github Actions use the system instance for this test, because there's // no user instance running apparently. let journal_instance = if std::env::var_os("GITHUB_ACTIONS").is_some() { Journal::System } else { Journal::User }; match std::env::var(env_name) { Ok(target) => { journal_send( Priority::Info, &format!("connected_to_journal() -> {}", connected_to_journal()), vec![("TARGET", &target)].into_iter(), ) .unwrap(); } Err(VarError::NotUnicode(value)) => { panic!("Value of ${} not unicode: {:?}", env_name, value); } Err(VarError::NotPresent) => { // Restart this binary under systemd-run and then check the journal for the test result let exe = std::env::current_exe().unwrap(); let target = random_target("connected_to_journal"); let status = match journal_instance { Journal::User => { let mut cmd = Command::new("systemd-run"); cmd.arg("--user"); cmd } Journal::System => { let mut cmd = Command::new("sudo"); cmd.arg("systemd-run"); cmd } } .arg("--description=systemd-journal-logger integration test: journal_stream") .arg(format!("--setenv={}={}", env_name, target)) // Wait until the process exited and unload the entire unit afterwards to // leave no state behind .arg("--wait") .arg("--collect") .arg(exe) .status() .unwrap(); assert!(status.success()); let entries = read_from_journal(journal_instance, &target); assert_eq!(entries.len(), 1); assert_eq!(entries[0]["TARGET"], target); assert_eq!(entries[0]["MESSAGE"], "connected_to_journal() -> true"); } } } libsystemd-0.5.0/tests/journal.rs000064400000000000000000000077340072674642500152320ustar 00000000000000use std::process::Command; use libsystemd::logging::Priority; use rand::distributions::Alphanumeric; use rand::Rng; use std::collections::HashMap; use std::time::Duration; fn random_name(prefix: &str) -> String { format!( "{}_{}", prefix, rand::thread_rng() .sample_iter(&Alphanumeric) .take(10) .map(char::from) .collect::() ) } /// Retry `f` 10 times 100ms apart. /// /// When `f` returns an error wait 100ms and try it again, up to ten times. /// If the last attempt failed return the error returned by that attempt. /// /// If `f` returns Ok immediately return the result. fn retry(f: impl Fn() -> Result) -> Result { let attempts = 10; let interval = Duration::from_millis(100); for attempt in (0..attempts).rev() { match f() { Ok(result) => return Ok(result), Err(e) if attempt == 0 => return Err(e), Err(_) => std::thread::sleep(interval), } } unreachable!() } /// Read from journal with `journalctl`. /// /// `test_name` is the randomized name of the test being run, and gets /// added as `TEST_NAME` match to the `journalctl` call, to make sure to /// only select journal entries originating from and relevant to the /// current test. fn read_from_journal(test_name: &str) -> Vec> { let stdout = String::from_utf8( Command::new("journalctl") .args(&["--user", "--output=json"]) // Filter by the PID of the current test process .arg(format!("_PID={}", std::process::id())) .arg(format!("TEST_NAME={}", test_name)) .output() .unwrap() .stdout, ) .unwrap(); stdout .lines() .map(|l| serde_json::from_str(l).unwrap()) .collect() } /// Read exactly one line from journal for the given test name. /// /// Try to read lines for `testname` from journal, and `retry()` if the wasn't /// _exactly_ one matching line. fn retry_read_one_line_from_journal(testname: &str) -> HashMap { retry(|| { let mut messages = read_from_journal(testname); if messages.len() == 1 { Ok(messages.pop().unwrap()) } else { Err(format!( "one messages expected, got {} messages", messages.len() )) } }) .unwrap() } #[test] fn simple_message() { let test_name = random_name("simple_message"); libsystemd::logging::journal_send( Priority::Info, "Hello World", vec![ ("TEST_NAME", test_name.as_str()), ("FOO", "another piece of data"), ] .into_iter(), ) .unwrap(); let message = retry_read_one_line_from_journal(&test_name); assert_eq!(message["MESSAGE"], "Hello World"); assert_eq!(message["TEST_NAME"], test_name); assert_eq!(message["PRIORITY"], "6"); assert_eq!(message["FOO"], "another piece of data"); } #[test] fn multiline_message() { let test_name = random_name("multiline_message"); libsystemd::logging::journal_send( Priority::Info, "Hello\nMultiline\nWorld", vec![("TEST_NAME", test_name.as_str())].into_iter(), ) .unwrap(); let message = retry_read_one_line_from_journal(&test_name); assert_eq!(message["MESSAGE"], "Hello\nMultiline\nWorld"); assert_eq!(message["TEST_NAME"], test_name); assert_eq!(message["PRIORITY"], "6"); } #[test] fn multiline_message_trailing_newline() { let test_name = random_name("multiline_message_trailing_newline"); libsystemd::logging::journal_send( Priority::Info, "A trailing newline\n", vec![("TEST_NAME", test_name.as_str())].into_iter(), ) .unwrap(); let message = retry_read_one_line_from_journal(&test_name); assert_eq!(message["MESSAGE"], "A trailing newline\n"); assert_eq!(message["TEST_NAME"], test_name); assert_eq!(message["PRIORITY"], "6"); }