Compare commits

...
38 Commits
Author SHA1 Message Date
dietrich 70ee27a246 replace println! with trace! 2020-11-30 15:17:24 +01:00
dietrich 1e5a95a9f6 fix warnings 2020-11-30 13:21:22 +01:00
dietrich df2f51a24e add license 2020-11-29 17:35:24 +01:00
dietrich 80a41fc1a2 updating group membership on user deletion
until now groups had members without useraccount after the account has been deleted.

fixes: #5
2020-11-27 17:32:41 +01:00
dietrich e9fbbd91ce Enum to discriminate primary and reg. memberships 2020-11-24 19:20:48 +01:00
dietrich 93e958108b better tests for groups 2020-11-19 09:34:49 +01:00
dietrich 8b42c8c3b2 add group members 2020-11-19 09:14:00 +01:00
dietrich 65542c9b69 make Group a Rc<Inner> type 2020-11-17 07:53:49 +01:00
dietrich 98b1634924 adding new title 2020-11-16 14:35:06 +01:00
dietrich e5583bb378 add summary 2020-11-16 14:21:16 +01:00
dietrich 36f5e51811 updating dependencies 2020-11-16 14:13:25 +01:00
dietrich 0a1bb3bd7e fix clippy warning 2020-11-16 13:08:37 +01:00
dietrich 10d9e3e71e right parameters 2020-11-16 13:04:16 +01:00
dietrich 3583d89697 fix indentation 2020-11-16 12:57:23 +01:00
dietrich c056016d43 add clippy info 2020-11-16 12:52:12 +01:00
dietrich 5a678bc3d5 renaming the project adduser -> umanux 2020-11-16 10:37:18 +01:00
dietrich 05cbd2d139 better 2020-11-16 09:14:40 +00:00
dietrich 425de573d5 update readme 2020-11-16 10:12:51 +01:00
dietrich e13a81f814 use +nightly (#2)
* use +nightly
2020-11-16 08:46:34 +01:00
dietrich 95ce925286 Merge pull request #1 from umanux/enaut-add-rust-workflow
Add rust workflow
2020-11-16 08:11:18 +01:00
dietrich 60e6eb6fa4 Add rust workflow 2020-11-16 08:11:00 +01:00
dietrich 3dae3c4109 modify the shadow file and test the binary 2020-11-15 17:04:31 +01:00
dietrich ed77466bd6 add default shadow entry to default users 2020-11-15 17:02:35 +01:00
dietrich 32d02dcc81 add parameters for files to create_user 2020-11-15 17:01:47 +01:00
dietrich c21ba2fa39 return from main function 2020-11-11 08:20:09 +01:00
dietrich f7fc3229ed optimize release builds for size 2020-11-11 06:58:17 +01:00
dietrich 101dcbb649 first binary test not complete 2020-11-11 06:57:46 +01:00
dietrich de17ff12be first version of create_user 2020-11-10 13:45:21 +01:00
dietrich ed06c58913 remove debug and commented code 2020-11-09 20:25:42 +01:00
dietrich 8fcd32eca2 Fix missing lints - Docs need to be improved still 2020-11-09 13:58:13 +01:00
dietrich 467c8ee007 linting changes 2020-11-09 09:56:24 +01:00
dietrich 647881f022 Adding a first integrationtest for delete_user 2020-11-08 10:41:20 +01:00
dietrich 732893b5d4 first integration test try 2020-11-05 09:01:51 +01:00
dietrich 4062f7a6bb delete the home directory 2020-11-03 13:09:16 +01:00
dietrich f3a18641e0 make delete_user take a struct use derive_builder 2020-11-02 07:55:33 +01:00
dietrich 31fbfbe628 remove from groups 2020-10-31 16:40:26 +01:00
dietrich b72f292891 improve functionlength 2020-10-31 15:55:15 +01:00
dietrich d9fe8b8160 improve error handling 2020-10-31 11:15:29 +01:00
28 changed files with 1906 additions and 369 deletions
+45
View File
@@ -0,0 +1,45 @@
name: Rust
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install latest nightly
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
override: true
components: rustfmt, clippy
# `cargo check` command here will use installed `nightly`
# as it is set as an "override" for current directory
- name: Run cargo check
uses: actions-rs/cargo@v1
with:
command: check
- name: Annotate commit with clippy warnings
uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features -- -Wclippy::all -Wclippy::pedantic -Wclippy::nursery -Wclippy::cargo -Aclippy::non_ascii_literal -Aclippy::missing_errors_doc -Aclippy::multiple_crate_versions
- name: Run cargo Build
uses: actions-rs/cargo@v1
with:
command: build
- name: Run cargo test
uses: actions-rs/cargo@v1
with:
command: test
Generated
+376 -28
View File
@@ -1,22 +1,10 @@
# This file is automatically @generated by Cargo. # This file is automatically @generated by Cargo.
# It is not intended for manual editing. # It is not intended for manual editing.
[[package]]
name = "adduser"
version = "0.1.0"
dependencies = [
"chrono",
"env_logger",
"lazy_static",
"log",
"regex",
"simplelog",
]
[[package]] [[package]]
name = "aho-corasick" name = "aho-corasick"
version = "0.7.13" version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "043164d8ba5c4c3035fec9bbee8647c0261d788f3474306f93bb65901cae0e86" checksum = "7404febffaa47dac81aa44dba71523c9d069b1bdc50a77db41195149e17f68e5"
dependencies = [ dependencies = [
"memchr", "memchr",
] ]
@@ -38,6 +26,12 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "bitflags"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]] [[package]]
name = "cfg-if" name = "cfg-if"
version = "0.1.10" version = "0.1.10"
@@ -57,6 +51,98 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "clap"
version = "3.0.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bd1061998a501ee7d4b6d449020df3266ca3124b941ec56cf2005c3779ca142"
dependencies = [
"atty",
"bitflags",
"clap_derive",
"indexmap",
"lazy_static",
"os_str_bytes",
"strsim 0.10.0",
"termcolor",
"textwrap",
"unicode-width",
"vec_map",
]
[[package]]
name = "clap_derive"
version = "3.0.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "370f715b81112975b1b69db93e0b56ea4cd4e5002ac43b2da8474106a54096a1"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "darling"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d706e75d87e35569db781a9b5e2416cff1236a47ed380831f959382ccd5f858"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0c960ae2da4de88a91b2d920c2a7233b400bc33cb28453a2987822d8392519b"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim 0.9.3",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72"
dependencies = [
"darling_core",
"quote",
"syn",
]
[[package]]
name = "derive_builder"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2658621297f2cf68762a6f7dc0bb7e1ff2cfd6583daef8ee0fed6f7ec468ec0"
dependencies = [
"darling",
"derive_builder_core",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "derive_builder_core"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2791ea3e372c8495c0bc2033991d76b512cd799d07491fbd6890124db9458bef"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "env_logger" name = "env_logger"
version = "0.8.1" version = "0.8.1"
@@ -70,6 +156,38 @@ dependencies = [
"termcolor", "termcolor",
] ]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getrandom"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc587bc0ec293155d5bfa6b9891ec18a1e330c234f896ea47fbada4cadbe47e6"
dependencies = [
"cfg-if",
"libc",
"wasi 0.9.0+wasi-snapshot-preview1",
]
[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
[[package]]
name = "heck"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205"
dependencies = [
"unicode-segmentation",
]
[[package]] [[package]]
name = "hermit-abi" name = "hermit-abi"
version = "0.1.17" version = "0.1.17"
@@ -85,6 +203,22 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c1ad908cc71012b7bea4d0c53ba96a8cba9962f048fa68d143376143d863b7a" checksum = "3c1ad908cc71012b7bea4d0c53ba96a8cba9962f048fa68d143376143d863b7a"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "indexmap"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55e2e4c765aa53a0424761bf9f41aa7a6ac1efa87238f59560640e27fca028f2"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.4.0" version = "1.4.0"
@@ -93,9 +227,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.78" version = "0.2.80"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa7087f49d294270db4e1928fc110c976cd4b9e5a16348e0a1df09afa99e6c98" checksum = "4d58d1b70b004888f764dfbf6a26a3b0342a1632d33968e4a179d8011c760614"
[[package]] [[package]]
name = "log" name = "log"
@@ -108,15 +242,15 @@ dependencies = [
[[package]] [[package]]
name = "memchr" name = "memchr"
version = "2.3.3" version = "2.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3728d817d99e5ac407411fa471ff9800a778d88a24685968b36824eaf4bee400" checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525"
[[package]] [[package]]
name = "num-integer" name = "num-integer"
version = "0.1.43" version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d59457e662d541ba17869cf51cf177c0b5f0cbf476c66bdc90bf1edac4f875b" checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db"
dependencies = [ dependencies = [
"autocfg", "autocfg",
"num-traits", "num-traits",
@@ -124,18 +258,119 @@ dependencies = [
[[package]] [[package]]
name = "num-traits" name = "num-traits"
version = "0.2.12" version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac267bcc07f48ee5f8935ab0d24f316fb722d7a1292e2913f0cc196b29ffd611" checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290"
dependencies = [ dependencies = [
"autocfg", "autocfg",
] ]
[[package]] [[package]]
name = "regex" name = "os_str_bytes"
version = "1.3.9" version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c3780fcf44b193bc4d09f36d2a3c87b251da4a046c87795a0d35f4f927ad8e6" checksum = "afb2e1c3ee07430c2cf76151675e583e0f19985fa6efae47d6848a3e2c824f85"
[[package]]
name = "ppv-lite86"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857"
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
]
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03"
dependencies = [
"getrandom",
"libc",
"rand_chacha",
"rand_core",
"rand_hc",
]
[[package]]
name = "rand_chacha"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19"
dependencies = [
"getrandom",
]
[[package]]
name = "rand_hc"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c"
dependencies = [
"rand_core",
]
[[package]]
name = "redox_syscall"
version = "0.1.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce"
[[package]]
name = "regex"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38cf2c13ed4745de91a5eb834e11c00bcc3709e773173b2ce4c56c9fbde04b9c"
dependencies = [ dependencies = [
"aho-corasick", "aho-corasick",
"memchr", "memchr",
@@ -145,9 +380,18 @@ dependencies = [
[[package]] [[package]]
name = "regex-syntax" name = "regex-syntax"
version = "0.6.18" version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26412eb97c6b088a6997e05f69403a802a92d520de2f8e63c2b65f9e0f47c4e8" checksum = "3b181ba2dcf07aaccad5448e8ead58db5b742cf85dfe035e2227f137a539a189"
[[package]]
name = "remove_dir_all"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
dependencies = [
"winapi",
]
[[package]] [[package]]
name = "simplelog" name = "simplelog"
@@ -160,6 +404,43 @@ dependencies = [
"termcolor", "termcolor",
] ]
[[package]]
name = "strsim"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c"
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "1.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc371affeffc477f42a221a1e4297aedcea33d47d19b61455588bd9d8f6b19ac"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "tempfile"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9"
dependencies = [
"cfg-if",
"libc",
"rand",
"redox_syscall",
"remove_dir_all",
"winapi",
]
[[package]] [[package]]
name = "termcolor" name = "termcolor"
version = "1.1.0" version = "1.1.0"
@@ -169,6 +450,21 @@ dependencies = [
"winapi-util", "winapi-util",
] ]
[[package]]
name = "test_bin"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1937bab04b0bd0f2c19628d3408fb6dd78faf5aa60f4bdb03212507a9b7314ba"
[[package]]
name = "textwrap"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "203008d98caf094106cfaba70acfed15e18ed3ddb7d94e49baec153a2b462789"
dependencies = [
"unicode-width",
]
[[package]] [[package]]
name = "thread_local" name = "thread_local"
version = "1.0.1" version = "1.0.1"
@@ -185,10 +481,62 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
dependencies = [ dependencies = [
"libc", "libc",
"wasi", "wasi 0.10.0+wasi-snapshot-preview1",
"winapi", "winapi",
] ]
[[package]]
name = "umanux"
version = "0.1.1"
dependencies = [
"chrono",
"clap",
"derive_builder",
"env_logger",
"lazy_static",
"log",
"regex",
"simplelog",
"tempfile",
"test_bin",
]
[[package]]
name = "unicode-segmentation"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db8716a166f290ff49dabc18b44aa407cb7c6dbe1aa0971b44b8a24b0ca35aae"
[[package]]
name = "unicode-width"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
[[package]]
name = "wasi"
version = "0.9.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519"
[[package]] [[package]]
name = "wasi" name = "wasi"
version = "0.10.0+wasi-snapshot-preview1" version = "0.10.0+wasi-snapshot-preview1"
+20 -2
View File
@@ -1,8 +1,14 @@
[package] [package]
name = "adduser" name = "umanux"
version = "0.1.0" version = "0.1.1"
description = "Library for managing Linux users and their directories"
authors = ["Dietrich <dietrich@teilgedanken.de>"] authors = ["Dietrich <dietrich@teilgedanken.de>"]
edition = "2018" edition = "2018"
license = "MIT OR Apache-2.0"
keywords = ["user", "admin", "linux", "manage", "passwd"]
categories = ["os", "os::linux-apis", "parser-implementations", "command-line-utilities"]
repository = "https://github.com/umanux/umanux"
readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@@ -13,3 +19,15 @@ log = "0.4"
simplelog = "0.8" simplelog = "0.8"
chrono = "0.4" chrono = "0.4"
env_logger = "0.8" env_logger = "0.8"
derive_builder = "0.9"
clap = "3.0.0-beta"
[dev-dependencies]
tempfile = "3.1"
test_bin= "0.3"
# optimize for size at cost of compilation speed.
[profile.release]
lto = true
codegen-units = 1
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2020 Franz Dietrich
Permission 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.
+201
View File
@@ -0,0 +1,201 @@
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 2020 Franz Dietrich
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.
+51
View File
@@ -0,0 +1,51 @@
# **U**ser **MAN**ager for lin**UX**
### A Usermanager written in Rust
> This project is **very much** work in progress. Do **absolutely not** use in production systems!
When done this library intends to provide all the functionality needed to manage users on a linux system.
What is working so far:
* [x] Parsing:
* [x] `/etc/passwd`
* [x] `/etc/shadow` (root permission needed)
* [x] `/etc/group`
* Modifying:
* delete a user
* [x] passwd
* [x] shadow
* [X] group
* [x] own primary group
* [x] membership in other groups
* [x] home dir
* [x] delete
* [x] keep
* [ ] archive
* [ ] mail?
* [ ] multiple entries "Multiple entries named '%s' in %s. Please fix this with pwck or grpck."
* [ ] cancel jobs:
* [ ] cron
* [ ] at
* [ ] print
* create a user
- [x] passwd
- [x] shadow
- [ ] group
- [ ] own group
- [ ] home dir
- [ ] create from skeleton
- [ ] Skip
- [ ] create from directory
- [ ] mail?
- [ ] multiple entries (check uid duplication)
## License
Umanux is licensed under either of the following, at your option:
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT License ([LICENSE-MIT](LICENSE) or http://opensource.org/licenses/MIT)
`SPDX-License-Identifier: Apache-2.0 OR MIT`
+40
View File
@@ -0,0 +1,40 @@
#![allow(clippy::default_trait_access)]
use std::path::PathBuf;
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum CreateHome {
Create,
Skip,
HomeFromDir { path: PathBuf },
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum CreatePrimaryGroup {
Create,
Skip,
CreateIfEmptyOrAdd,
}
#[derive(Debug, Builder, Eq, PartialEq)]
#[builder(public)]
#[builder(default)]
pub struct CreateUserArgs<'a> {
pub username: &'a str,
pub delete_home: CreateHome,
pub delete_primary_group: CreatePrimaryGroup,
}
impl<'a> CreateUserArgs<'a> {
#[must_use]
pub fn builder() -> CreateUserArgsBuilder<'a> {
CreateUserArgsBuilder::default()
}
}
impl Default for CreateUserArgs<'_> {
fn default() -> Self {
Self {
username: "defaultuser",
delete_home: CreateHome::Create,
delete_primary_group: CreatePrimaryGroup::CreateIfEmptyOrAdd,
}
}
}
+40
View File
@@ -0,0 +1,40 @@
#![allow(clippy::default_trait_access)]
use std::path::PathBuf;
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum DeleteHome {
Delete,
Keep,
Archive { path: PathBuf },
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum DeletePrimaryGroup {
Delete,
Keep,
DeleteIfEmpty,
}
#[derive(Debug, Builder, Eq, PartialEq)]
#[builder(public)]
#[builder(default)]
pub struct DeleteUserArgs<'a> {
pub username: &'a str,
pub delete_home: DeleteHome,
pub delete_primary_group: DeletePrimaryGroup,
}
impl<'a> DeleteUserArgs<'a> {
#[must_use]
pub fn builder() -> DeleteUserArgsBuilder<'a> {
DeleteUserArgsBuilder::default()
}
}
impl Default for DeleteUserArgs<'_> {
fn default() -> Self {
Self {
username: "defaultuser",
delete_home: DeleteHome::Keep,
delete_primary_group: DeletePrimaryGroup::DeleteIfEmpty,
}
}
}
+8 -16
View File
@@ -1,8 +1,13 @@
pub mod createuser_args;
pub mod deleteuser_args;
pub use createuser_args::{CreateHome, CreatePrimaryGroup, CreateUserArgs};
pub use deleteuser_args::{DeleteHome, DeletePrimaryGroup, DeleteUserArgs};
pub trait UserDBRead { pub trait UserDBRead {
fn get_all_users(&self) -> Vec<&crate::User>; fn get_all_users(&self) -> Vec<&crate::User>;
fn get_user_by_name(&self, name: &str) -> Option<&crate::User>; fn get_user_by_name(&self, name: &str) -> Option<&crate::User>;
fn get_user_by_id(&self, uid: u32) -> Option<&crate::User>; fn get_user_by_id(&self, uid: u32) -> Option<&crate::User>;
fn get_all_groups(&self) -> Vec<&crate::Group>; fn get_all_groups(&self) -> Vec<crate::Group>;
fn get_group_by_name(&self, name: &str) -> Option<&crate::Group>; fn get_group_by_name(&self, name: &str) -> Option<&crate::Group>;
fn get_group_by_id(&self, name: u32) -> Option<&crate::Group>; fn get_group_by_id(&self, name: u32) -> Option<&crate::Group>;
} }
@@ -15,21 +20,8 @@ pub trait UserDBValidation {
} }
pub trait UserDBWrite { pub trait UserDBWrite {
fn delete_user(&mut self, user: &str) -> Result<crate::User, crate::UserLibError>; fn delete_user(&mut self, params: DeleteUserArgs) -> Result<crate::User, crate::UserLibError>;
fn new_user( fn new_user(&mut self, params: CreateUserArgs) -> Result<&crate::User, crate::UserLibError>;
&mut self, /*
username: String,
enc_password: String,
uid: u32,
gid: u32,
full_name: String,
room: String,
phone_work: String,
phone_home: String,
other: Option<Vec<String>>,
home_dir: String,
shell_path: String,*/
) -> Result<&crate::User, crate::UserLibError>;
fn delete_group(&mut self, group: &crate::Group) -> Result<(), crate::UserLibError>; fn delete_group(&mut self, group: &crate::Group) -> Result<(), crate::UserLibError>;
fn new_group(&mut self) -> Result<&crate::Group, crate::UserLibError>; fn new_group(&mut self) -> Result<&crate::Group, crate::UserLibError>;
} }
+63 -16
View File
@@ -1,22 +1,69 @@
extern crate adduser; use std::path::PathBuf;
fn main() { extern crate clap;
simplelog::CombinedLogger::init(vec![simplelog::TermLogger::new( use clap::{App, Arg};
simplelog::LevelFilter::Warn,
simplelog::Config::default(),
simplelog::TerminalMode::Mixed,
)])
.unwrap();
//use adduser::api::UserDBWrite;
let _db = adduser::UserDBLocal::load_files(adduser::Files::default()); extern crate umanux;
use umanux::{api::UserDBWrite, UserLibError};
let user = adduser::User::default() fn main() -> Result<(), UserLibError> {
.username("fest".into()) env_logger::init();
.shell_path("/bin/mash".into()) let matches = App::new("Create a new linux user")
.clone(); .version("0.1.0")
.author("Franz Dietrich <dietrich@teilgedanken.de>")
.about("Create a linux user do not use this in production (yet)")
.arg(
Arg::new("username")
.value_name("USERNAME")
.about("the new users name")
.takes_value(true)
.required(true),
)
.arg(
Arg::new("passwd")
.short('p')
.long("passwd")
.value_name("FILE")
.about("The passwd file")
.default_value("/etc/passwd")
.takes_value(true),
)
.arg(
Arg::new("shadow")
.short('s')
.long("shadow")
.value_name("FILE")
.about("The shadow file")
.default_value("/etc/shadow")
.takes_value(true),
)
.arg(
Arg::new("group")
.short('g')
.long("group")
.value_name("FILE")
.about("The group file")
.default_value("/etc/group")
.takes_value(true),
)
.get_matches();
println!("{}", user); let mf = umanux::Files {
passwd: Some(PathBuf::from(matches.value_of("passwd").unwrap())),
shadow: Some(PathBuf::from(matches.value_of("shadow").unwrap())),
group: Some(PathBuf::from(matches.value_of("group").unwrap())),
};
//db.new_user().expect("failed to create the user"); let mut db = umanux::UserDBLocal::load_files(mf).unwrap();
match db.new_user(
umanux::api::CreateUserArgs::builder()
.username(matches.value_of("username").unwrap())
// .delete_home(umanux::api::DeleteHome::Delete)
.build()
.unwrap(),
) {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
} }
+13 -7
View File
@@ -1,6 +1,9 @@
use std::path::PathBuf; use std::path::PathBuf;
extern crate adduser; extern crate umanux;
use umanux::api::UserDBWrite;
use umanux::api::UserRead;
extern crate env_logger; extern crate env_logger;
#[allow(unused_imports)] #[allow(unused_imports)]
@@ -9,18 +12,21 @@ use log::{debug, error, info, trace, warn};
fn main() { fn main() {
env_logger::init(); env_logger::init();
use adduser::api::UserDBWrite; let mf = umanux::Files {
use adduser::api::UserRead;
let mf = adduser::Files {
passwd: Some(PathBuf::from("./passwd")), passwd: Some(PathBuf::from("./passwd")),
shadow: Some(PathBuf::from("./shadow")), shadow: Some(PathBuf::from("./shadow")),
group: Some(PathBuf::from("./group")), group: Some(PathBuf::from("./group")),
}; };
let mut db = adduser::UserDBLocal::load_files(mf).unwrap(); let mut db = umanux::UserDBLocal::load_files(mf).unwrap();
let user_res: Result<adduser::User, adduser::UserLibError> = db.delete_user("teste"); let user_res: Result<umanux::User, umanux::UserLibError> = db.delete_user(
umanux::api::DeleteUserArgs::builder()
.username("teste")
// .delete_home(umanux::api::DeleteHome::Delete)
.build()
.unwrap(),
);
match user_res { match user_res {
Ok(u) => info!( Ok(u) => info!(
"The user <{}> has been deleted! ", "The user <{}> has been deleted! ",
+22 -3
View File
@@ -1,4 +1,6 @@
extern crate adduser; extern crate umanux;
use umanux::api::GroupRead;
use umanux::api::UserDBRead;
fn main() { fn main() {
simplelog::CombinedLogger::init(vec![simplelog::TermLogger::new( simplelog::CombinedLogger::init(vec![simplelog::TermLogger::new(
@@ -7,11 +9,28 @@ fn main() {
simplelog::TerminalMode::Mixed, simplelog::TerminalMode::Mixed,
)]) )])
.unwrap(); .unwrap();
use adduser::api::UserDBRead;
let db = adduser::UserDBLocal::load_files(adduser::Files::default()).unwrap(); let db = umanux::UserDBLocal::load_files(umanux::Files::default()).unwrap();
for u in db.get_all_users() { for u in db.get_all_users() {
println!("{}", u); println!("{}", u);
println!(
"Groups: {:?}",
u.get_groups()
.iter()
.map(|group| {
(
format!("{:?}", group.0),
group.1.borrow().get_groupname().unwrap().to_owned(),
)
})
.collect::<Vec<(String, String)>>()
);
}
for group in db.get_all_groups() {
let gp = group.borrow();
println!("{}", gp);
println!("{:?}", gp.get_member_names())
} }
} }
+18 -10
View File
@@ -1,6 +1,7 @@
use std::error::Error; use std::error::Error;
use std::fmt::{self, Display}; use std::fmt::{self, Display};
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum ParseError { pub enum ParseError {
Username, Username,
@@ -12,6 +13,7 @@ pub enum ParseError {
ShellDir, ShellDir,
} }
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum UserLibError { pub enum UserLibError {
NotFound, NotFound,
@@ -36,8 +38,8 @@ impl PartialEq for MyMessage {
impl Display for MyMessage { impl Display for MyMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
MyMessage::Simple(m) => write!(f, "{}", m), Self::Simple(m) => write!(f, "{}", m),
MyMessage::IOError(m, e) => write!(f, "{},{}", m, e), Self::IOError(m, e) => write!(f, "{},{}", m, e),
} }
} }
} }
@@ -47,7 +49,7 @@ impl Display for UserLibError {
match self { match self {
Self::NotFound => write!(f, "not found"), Self::NotFound => write!(f, "not found"),
Self::ParseError => write!(f, "failed to parse"), Self::ParseError => write!(f, "failed to parse"),
UserLibError::FilesRequired => write!( Self::FilesRequired => write!(
f, f,
"File locking is only possible if some files are specified" "File locking is only possible if some files are specified"
), ),
@@ -63,12 +65,12 @@ impl Display for UserLibError {
impl Error for UserLibError { impl Error for UserLibError {
fn source(&self) -> Option<&(dyn Error + 'static)> { fn source(&self) -> Option<&(dyn Error + 'static)> {
match *self { match *self {
UserLibError::NotFound Self::NotFound
| UserLibError::ParseError | Self::ParseError
| UserLibError::FilesChanged | Self::FilesChanged
| UserLibError::FilesRequired => None, | Self::FilesRequired
UserLibError::Message(MyMessage::IOError(_, ref e)) => Some(e), | Self::Message(MyMessage::Simple(_)) => None,
UserLibError::Message(MyMessage::Simple(_)) => None, Self::Message(MyMessage::IOError(_, ref e)) => Some(e),
} }
} }
} }
@@ -85,9 +87,15 @@ impl From<String> for UserLibError {
} }
} }
impl From<std::io::Error> for UserLibError {
fn from(e: std::io::Error) -> Self {
Self::Message(MyMessage::Simple(e.to_string()))
}
}
impl From<(String, std::io::Error)> for UserLibError { impl From<(String, std::io::Error)> for UserLibError {
fn from((m, e): (String, std::io::Error)) -> Self { fn from((m, e): (String, std::io::Error)) -> Self {
UserLibError::Message(MyMessage::IOError(m, e)) Self::Message(MyMessage::IOError(m, e))
} }
} }
/* /*
+67 -29
View File
@@ -1,19 +1,24 @@
#![warn(
clippy::all,
/* clippy::restriction,*/
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
#![allow(clippy::non_ascii_literal)] #![allow(clippy::non_ascii_literal)]
use crate::userlib::NewFromString; use crate::userlib::NewFromString;
use log::warn; use log::warn;
use crate::UserLibError; use crate::UserLibError;
use std::cmp::Eq;
use std::convert::TryFrom;
use std::fmt::{self, Debug, Display}; use std::fmt::{self, Debug, Display};
use std::{cell::RefCell, convert::TryFrom};
use std::{cmp::Eq, rc::Rc};
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MembershipKind {
Primary,
Member,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Membership {
kind: MembershipKind,
username: crate::Username,
}
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub struct Groupname { pub struct Groupname {
@@ -45,19 +50,45 @@ pub(crate) fn is_groupname_valid(name: &str) -> bool {
crate::user::passwd_fields::is_username_valid(name) crate::user::passwd_fields::is_username_valid(name)
} }
pub type Group = Rc<RefCell<Inner>>;
/// A record(line) in the user database `/etc/shadow` found in most linux systems. /// A record(line) in the user database `/etc/shadow` found in most linux systems.
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
pub struct Group { pub struct Inner {
pos: u32, pos: u32,
source: String, source: String,
groupname: Groupname, /* Username. */ groupname: Groupname, /* Username. */
pub(crate) password: crate::Password, /* Usually not used (disabled with x) */ pub(crate) password: crate::Password, /* Usually not used (disabled with x) */
gid: crate::Gid, /* Group ID. */ gid: crate::Gid, /* Group ID. */
members: Vec<crate::Username>, /* Real name. */ members: Vec<Membership>, /* Real name. */
}
impl Inner {
#[must_use]
pub fn remove_in(&self, content: &str) -> String {
content
.split(&self.source)
.map(str::trim)
.collect::<Vec<&str>>()
.join("\n")
}
pub(super) fn append_user(&mut self, username: &str) {
self.members.push(Membership {
kind: MembershipKind::Primary,
username: crate::Username {
username: username.to_owned(),
},
})
}
pub(super) fn remove_member(&mut self, kind: MembershipKind, username: &str) {
self.members
.retain(|u| !(u.username.username == username && u.kind == kind))
}
} }
use crate::api::GroupRead; use crate::api::GroupRead;
impl GroupRead for Group { impl GroupRead for Inner {
#[must_use] #[must_use]
fn get_groupname(&self) -> Option<&str> { fn get_groupname(&self) -> Option<&str> {
Some(&self.groupname.groupname) Some(&self.groupname.groupname)
@@ -65,8 +96,8 @@ impl GroupRead for Group {
#[must_use] #[must_use]
fn get_member_names(&self) -> Option<Vec<&str>> { fn get_member_names(&self) -> Option<Vec<&str>> {
let mut r: Vec<&str> = Vec::new(); let mut r: Vec<&str> = Vec::new();
for u in self.members.iter() { for u in &self.members {
r.push(&u.username); r.push(&u.username.username);
} }
Some(r) Some(r)
} }
@@ -80,7 +111,7 @@ impl GroupRead for Group {
} }
} }
impl Display for Group { impl Display for Inner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!( write!(
f, f,
@@ -90,7 +121,11 @@ impl Display for Group {
self.gid, self.gid,
self.members self.members
.iter() .iter()
.map(|mem| format!("{}", mem)) .filter_map(|mem| if mem.kind == MembershipKind::Member {
Some(format!("{}", mem.username))
} else {
None
})
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(",") .join(",")
) )
@@ -102,13 +137,13 @@ impl NewFromString for Group {
/// ///
/// # Example /// # Example
/// ``` /// ```
/// use crate::adduser::api::GroupRead; /// use crate::umanux::api::GroupRead;
/// use adduser::NewFromString; /// use umanux::NewFromString;
/// let grp = adduser::Group::new_from_string( /// let grp = umanux::Group::new_from_string(
/// "teste:x:1002:test,teste".to_owned(), /// "teste:x:1002:test,teste".to_owned(),
/// 0, /// 0,
/// ).unwrap(); /// ).unwrap();
/// assert_eq!(grp.get_groupname().unwrap(), "teste"); /// assert_eq!(grp.borrow().get_groupname().unwrap(), "teste");
/// ``` /// ```
/// ///
/// # Errors /// # Errors
@@ -116,14 +151,14 @@ impl NewFromString for Group {
fn new_from_string(line: String, position: u32) -> Result<Self, UserLibError> { fn new_from_string(line: String, position: u32) -> Result<Self, UserLibError> {
let elements: Vec<String> = line.split(':').map(ToString::to_string).collect(); let elements: Vec<String> = line.split(':').map(ToString::to_string).collect();
if elements.len() == 4 { if elements.len() == 4 {
Ok(Self { Ok(Self::new(RefCell::new(Inner {
pos: position, pos: position,
source: line.clone(), source: line,
groupname: Groupname::try_from(elements.get(0).unwrap().to_string())?, groupname: Groupname::try_from(elements.get(0).unwrap().to_string())?,
password: crate::Password::Disabled, password: crate::Password::Disabled,
gid: crate::Gid::try_from(elements.get(2).unwrap().to_string())?, gid: crate::Gid::try_from(elements.get(2).unwrap().to_string())?,
members: parse_members_list(elements.get(3).unwrap()), members: parse_members_list(elements.get(3).unwrap()),
}) })))
} else { } else {
Err(format!( Err(format!(
"Failed to parse: not enough elements ({}): {:?}", "Failed to parse: not enough elements ({}): {:?}",
@@ -135,7 +170,7 @@ impl NewFromString for Group {
} }
} }
fn parse_members_list(source: &str) -> Vec<crate::Username> { fn parse_members_list(source: &str) -> Vec<Membership> {
let mut res = vec![]; let mut res = vec![];
for mem in source.split(',').filter_map(|x| { for mem in source.split(',').filter_map(|x| {
if x.is_empty() { if x.is_empty() {
@@ -144,7 +179,10 @@ fn parse_members_list(source: &str) -> Vec<crate::Username> {
Some(x.to_string()) Some(x.to_string())
} }
}) { }) {
res.push(crate::Username::try_from(mem).expect("failed to parse username")); res.push(Membership {
kind: MembershipKind::Member,
username: crate::Username::try_from(mem).expect("failed to parse username"),
});
} }
res res
} }
@@ -152,19 +190,19 @@ fn parse_members_list(source: &str) -> Vec<crate::Username> {
#[test] #[test]
fn test_parse_and_back_identity() { fn test_parse_and_back_identity() {
let line = "teste:x:1002:test,teste"; let line = "teste:x:1002:test,teste";
let line2 = Group::new_from_string(line.to_owned(), 0).unwrap(); let line2: Group = Group::new_from_string(line.to_owned(), 0).unwrap();
assert_eq!(format!("{}", line2), line); assert_eq!(format!("{}", line2.borrow()), line);
} }
#[test] #[test]
fn test_groupname() { fn test_groupname() {
let line = "teste:x:1002:test,teste"; let line = "teste:x:1002:test,teste";
let line2 = Group::new_from_string(line.to_owned(), 0).unwrap(); let line2 = Group::new_from_string(line.to_owned(), 0).unwrap();
assert_eq!(line2.get_groupname().unwrap(), "teste"); assert_eq!(line2.borrow().get_groupname().unwrap(), "teste");
} }
#[test] #[test]
fn test_root_group() { fn test_root_group() {
let line = "root:x:0:"; let line = "root:x:0:";
let line2 = Group::new_from_string(line.to_owned(), 0).unwrap(); let line2 = Group::new_from_string(line.to_owned(), 0).unwrap();
assert_eq!(line2.get_groupname().unwrap(), "root"); assert_eq!(line2.borrow().get_groupname().unwrap(), "root");
} }
+13
View File
@@ -1,5 +1,18 @@
#![warn(
clippy::all,
//clippy::restriction,
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
//#![allow(clippy::non_ascii_literal)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::clippy::multiple_crate_versions)]
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
#[macro_use]
extern crate derive_builder;
extern crate log; extern crate log;
+21 -21
View File
@@ -1,3 +1,4 @@
#![allow(clippy::non_ascii_literal)]
use crate::UserLibError; use crate::UserLibError;
use std::cmp::Eq; use std::cmp::Eq;
use std::convert::TryFrom; use std::convert::TryFrom;
@@ -26,19 +27,19 @@ impl Gecos {
#[must_use] #[must_use]
pub fn get_comment(&self) -> Option<&str> { pub fn get_comment(&self) -> Option<&str> {
match &self { match &self {
Gecos::Simple { comment, .. } => Some(&comment), Self::Simple { comment, .. } => Some(comment),
Gecos::Detail { .. } => None, Self::Detail { .. } => None,
} }
} }
#[must_use] #[must_use]
pub fn get_full_name(&self) -> Option<&str> { pub fn get_full_name(&self) -> Option<&str> {
match &self { match &self {
Gecos::Simple { .. } => None, Self::Simple { .. } => None,
Gecos::Detail { full_name, .. } => { Self::Detail { full_name, .. } => {
if full_name.is_empty() { if full_name.is_empty() {
None None
} else { } else {
Some(&full_name) Some(full_name)
} }
} }
} }
@@ -46,12 +47,12 @@ impl Gecos {
#[must_use] #[must_use]
pub fn get_room(&self) -> Option<&str> { pub fn get_room(&self) -> Option<&str> {
match &self { match &self {
Gecos::Simple { .. } => None, Self::Simple { .. } => None,
Gecos::Detail { room, .. } => { Self::Detail { room, .. } => {
if room.is_empty() { if room.is_empty() {
None None
} else { } else {
Some(&room) Some(room)
} }
} }
} }
@@ -59,12 +60,12 @@ impl Gecos {
#[must_use] #[must_use]
pub fn get_phone_work(&self) -> Option<&str> { pub fn get_phone_work(&self) -> Option<&str> {
match &self { match &self {
Gecos::Simple { .. } => None, Self::Simple { .. } => None,
Gecos::Detail { phone_work, .. } => { Self::Detail { phone_work, .. } => {
if phone_work.is_empty() { if phone_work.is_empty() {
None None
} else { } else {
Some(&phone_work) Some(phone_work)
} }
} }
} }
@@ -72,12 +73,12 @@ impl Gecos {
#[must_use] #[must_use]
pub fn get_phone_home(&self) -> Option<&str> { pub fn get_phone_home(&self) -> Option<&str> {
match &self { match &self {
Gecos::Simple { .. } => None, Self::Simple { .. } => None,
Gecos::Detail { phone_home, .. } => { Self::Detail { phone_home, .. } => {
if phone_home.is_empty() { if phone_home.is_empty() {
None None
} else { } else {
Some(&phone_home) Some(phone_home)
} }
} }
} }
@@ -85,8 +86,8 @@ impl Gecos {
#[must_use] #[must_use]
pub const fn get_other(&self) -> Option<&Vec<String>> { pub const fn get_other(&self) -> Option<&Vec<String>> {
match self { match self {
Gecos::Simple { .. } => None, Self::Simple { .. } => None,
Gecos::Detail { other, .. } => match other { Self::Detail { other, .. } => match other {
None => None, None => None,
Some(comments) => Some(comments), Some(comments) => Some(comments),
}, },
@@ -97,8 +98,8 @@ impl Gecos {
impl Display for Gecos { impl Display for Gecos {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self { match &self {
Gecos::Simple { comment } => write!(f, "{}", comment), Self::Simple { comment } => write!(f, "{}", comment),
Gecos::Detail { Self::Detail {
full_name, full_name,
room, room,
phone_work, phone_work,
@@ -125,7 +126,7 @@ impl TryFrom<String> for Gecos {
fn try_from(source: String) -> std::result::Result<Self, Self::Error> { fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
let vals: Vec<String> = source.split(',').map(ToString::to_string).collect(); let vals: Vec<String> = source.split(',').map(ToString::to_string).collect();
if vals.len() > 3 { if vals.len() > 3 {
Ok(Gecos::Detail { Ok(Self::Detail {
full_name: vals[0].clone(), full_name: vals[0].clone(),
room: vals[1].clone(), room: vals[1].clone(),
phone_work: vals[2].clone(), phone_work: vals[2].clone(),
@@ -137,7 +138,7 @@ impl TryFrom<String> for Gecos {
}, },
}) })
} else if vals.len() == 1 { } else if vals.len() == 1 {
Ok(Gecos::Simple { Ok(Self::Simple {
comment: vals.get(0).unwrap().into(), comment: vals.get(0).unwrap().into(),
}) })
} else { } else {
@@ -145,7 +146,6 @@ impl TryFrom<String> for Gecos {
} }
} }
} }
#[test] #[test]
fn test_parse_gecos() { fn test_parse_gecos() {
// test if the Gecos field can be parsed and the resulting struct is populated correctly. // test if the Gecos field can be parsed and the resulting struct is populated correctly.
+41 -34
View File
@@ -21,45 +21,30 @@ pub struct User {
gecos: crate::Gecos, /* Real name. */ gecos: crate::Gecos, /* Real name. */
home_dir: crate::HomeDir, /* Home directory. */ home_dir: crate::HomeDir, /* Home directory. */
shell_path: crate::ShellPath, /* Shell program. */ shell_path: crate::ShellPath, /* Shell program. */
groups: Vec<(crate::group::MembershipKind, crate::Group)>,
} }
impl User { impl User {
pub fn get_shadow(&self) -> Option<&crate::Shadow> { #[must_use]
pub const fn get_shadow(&self) -> Option<&crate::Shadow> {
match self.password { match self.password {
crate::Password::Encrypted(_) => None, crate::Password::Encrypted(_) | crate::Password::Disabled => None,
crate::Password::Shadow(ref s) => Some(s), crate::Password::Shadow(ref s) => Some(s),
crate::Password::Disabled => None,
} }
} }
/*fn get_nth_line(content: &str, n: u32) -> (String, u64) { #[must_use]
use std::io::BufRead;
let mut cursor = std::io::Cursor::new(content);
let mut offset: u64 = 0;
let mut tmp = String::new();
for _ in 0..n + 1 {
tmp = String::new();
offset += cursor.read_line(&mut tmp).expect("failed to read line") as u64;
//trace!("reading user{}: {}", i, &tmp);
}
(tmp.trim().to_owned(), offset)
}
pub(crate) fn is_unchanged_in(&self, content: &str) -> (u64, usize, bool) {
let (line, offset) = Self::get_nth_line(content, self.pos);
trace!("Olduser:\n\t{}\nNewuser\n\t{}", &self.source, &line);
(offset, line.len(), line == self.source)
}*/
pub fn remove_in(&self, content: &str) -> String { pub fn remove_in(&self, content: &str) -> String {
content content
.split(&self.source) .split(&self.source)
.map(|x| x.trim()) .map(str::trim)
.collect::<Vec<&str>>() .collect::<Vec<&str>>()
.join("\n") .join("\n")
} }
pub fn username(&mut self, name: String) -> &mut Self { pub fn username(&mut self, name: String) -> &mut Self {
self.username = crate::Username { self.username = crate::Username { username: name };
username: name.into(), if let crate::Password::Shadow(ref mut s) = self.password {
}; s.set_username(self.username.clone());
}
self self
} }
pub fn disable_password(&mut self) -> &mut Self { pub fn disable_password(&mut self) -> &mut Self {
@@ -82,6 +67,20 @@ impl User {
self.shell_path = crate::ShellPath { shell: path }; self.shell_path = crate::ShellPath { shell: path };
self self
} }
pub fn add_group(
&mut self,
group_type: crate::group::MembershipKind,
group: crate::Group,
) -> &mut Self {
self.groups.push((group_type, group));
self
}
#[must_use]
pub const fn get_groups(&self) -> &Vec<(crate::group::MembershipKind, crate::Group)> {
&self.groups
}
} }
impl NewFromString for User { impl NewFromString for User {
@@ -89,9 +88,9 @@ impl NewFromString for User {
/// ///
/// # Example /// # Example
/// ``` /// ```
/// use crate::adduser::api::UserRead; /// use crate::umanux::api::UserRead;
/// use adduser::NewFromString; /// use umanux::NewFromString;
/// let pwd = adduser::User::new_from_string( /// let pwd = umanux::User::new_from_string(
/// "testuser:testpassword:1001:1001:full Name,,,,:/home/test:/bin/test".to_string(), 0).unwrap(); /// "testuser:testpassword:1001:1001:full Name,,,,:/home/test:/bin/test".to_string(), 0).unwrap();
/// assert_eq!(pwd.get_username().unwrap(), "testuser"); /// assert_eq!(pwd.get_username().unwrap(), "testuser");
/// ``` /// ```
@@ -116,6 +115,7 @@ impl NewFromString for User {
gecos: crate::Gecos::try_from(elements.get(4).unwrap().to_string())?, gecos: crate::Gecos::try_from(elements.get(4).unwrap().to_string())?,
home_dir: crate::HomeDir::try_from(elements.get(5).unwrap().to_string())?, home_dir: crate::HomeDir::try_from(elements.get(5).unwrap().to_string())?,
shell_path: crate::ShellPath::try_from(elements.get(6).unwrap().to_string())?, shell_path: crate::ShellPath::try_from(elements.get(6).unwrap().to_string())?,
groups: Vec::new(),
}) })
} else { } else {
Err("Failed to parse: not enough elements".into()) Err("Failed to parse: not enough elements".into())
@@ -131,7 +131,7 @@ impl crate::api::UserRead for User {
#[must_use] #[must_use]
fn get_password(&self) -> Option<&str> { fn get_password(&self) -> Option<&str> {
match &self.password { match &self.password {
crate::Password::Encrypted(crate::EncryptedPassword { password }) => Some(&password), crate::Password::Encrypted(crate::EncryptedPassword { password }) => Some(password),
crate::Password::Shadow(crate::Shadow { ref password, .. }) => Some(&password.password), crate::Password::Shadow(crate::Shadow { ref password, .. }) => Some(&password.password),
crate::Password::Disabled => None, crate::Password::Disabled => None,
} }
@@ -197,13 +197,18 @@ impl Ord for User {
impl Default for User { impl Default for User {
fn default() -> Self { fn default() -> Self {
let username = passwd_fields::Username {
username: "defaultusername".to_owned(),
};
let line = "defaultusername:!!:0:0:99999:7:::";
let password = passwd_fields::Password::Shadow(
shadow_fields::Shadow::new_from_string(line.to_owned(), u32::MAX).unwrap(),
);
Self { Self {
source: "".to_owned(), source: "".to_owned(),
pos: u32::MAX, pos: u32::MAX,
username: crate::Username { username,
username: "defaultusername".to_owned(), password,
},
password: crate::Password::Disabled,
uid: crate::Uid { uid: 1001 }, uid: crate::Uid { uid: 1001 },
gid: crate::Gid { gid: 1001 }, gid: crate::Gid { gid: 1001 },
gecos: crate::Gecos::Simple { gecos: crate::Gecos::Simple {
@@ -215,6 +220,7 @@ impl Default for User {
shell_path: crate::ShellPath { shell_path: crate::ShellPath {
shell: "/bin/nologin".to_owned(), shell: "/bin/nologin".to_owned(),
}, },
groups: Vec::new(),
} }
} }
} }
@@ -287,6 +293,7 @@ fn test_new_from_string() {
#[test] #[test]
fn test_parse_passwd() { fn test_parse_passwd() {
// Test wether the passwd file can be parsed and recreated without throwing an exception // Test wether the passwd file can be parsed and recreated without throwing an exception
use std::convert::TryInto;
use std::fs::File; use std::fs::File;
use std::io::{prelude::*, BufReader}; use std::io::{prelude::*, BufReader};
let file = File::open("/etc/passwd").unwrap(); let file = File::open("/etc/passwd").unwrap();
@@ -295,7 +302,7 @@ fn test_parse_passwd() {
for (n, line) in reader.lines().enumerate() { for (n, line) in reader.lines().enumerate() {
let lineorig: String = line.unwrap(); let lineorig: String = line.unwrap();
let linecopy = lineorig.clone(); let linecopy = lineorig.clone();
let pass_struc = User::new_from_string(linecopy, n as u32).unwrap(); let pass_struc = User::new_from_string(linecopy, n.try_into().unwrap()).unwrap();
assert_eq!( assert_eq!(
// ignoring the numbers of `,` since the implementation does not (yet) reproduce a missing comment field. // ignoring the numbers of `,` since the implementation does not (yet) reproduce a missing comment field.
lineorig, lineorig,
+4 -11
View File
@@ -1,10 +1,3 @@
#![warn(
clippy::all,
/* clippy::restriction,*/
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
#![allow(clippy::non_ascii_literal)] #![allow(clippy::non_ascii_literal)]
use log::warn; use log::warn;
@@ -65,8 +58,7 @@ impl Display for Password {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self { match self {
Self::Encrypted(EncryptedPassword { password }) => write!(f, "{}", password,), Self::Encrypted(EncryptedPassword { password }) => write!(f, "{}", password,),
Self::Shadow(_) => write!(f, "x"), Self::Shadow(_) | Self::Disabled => write!(f, "x"),
Self::Disabled => write!(f, "x"),
} }
} }
} }
@@ -85,11 +77,11 @@ impl Display for EncryptedPassword {
impl TryFrom<String> for EncryptedPassword { impl TryFrom<String> for EncryptedPassword {
type Error = UserLibError; type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> { fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
if source == "x" { /*if source == "x" {
//warn!("password from shadow not loaded!") //warn!("password from shadow not loaded!")
} else { } else {
//warn!("Password field has an unexpected value") //warn!("Password field has an unexpected value")
}; };*/
Ok(Self { password: source }) Ok(Self { password: source })
} }
} }
@@ -149,6 +141,7 @@ impl Gid {
self.gid < 1000 self.gid < 1000
} }
#[must_use]
pub const fn get_gid(&self) -> u32 { pub const fn get_gid(&self) -> u32 {
self.gid self.gid
} }
+12 -16
View File
@@ -1,14 +1,4 @@
#![warn(
clippy::all,
/* clippy::restriction,*/
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
#![allow(clippy::non_ascii_literal)]
use crate::userlib::NewFromString; use crate::userlib::NewFromString;
use log::warn;
use crate::UserLibError; use crate::UserLibError;
use std::cmp::Eq; use std::cmp::Eq;
@@ -36,14 +26,20 @@ impl Shadow {
pub fn get_username(&self) -> &str { pub fn get_username(&self) -> &str {
&self.username.username &self.username.username
} }
pub fn set_username(&mut self, username: crate::Username) {
self.username = username;
}
#[must_use] #[must_use]
pub fn get_password(&self) -> &str { pub fn get_password(&self) -> &str {
&self.password.password &self.password.password
} }
#[must_use]
pub fn remove_in(&self, content: &str) -> String { pub fn remove_in(&self, content: &str) -> String {
content content
.split(&self.source) .split(&self.source)
.map(|x| x.trim()) .map(str::trim)
.collect::<Vec<&str>>() .collect::<Vec<&str>>()
.join("\n") .join("\n")
} }
@@ -92,9 +88,9 @@ impl NewFromString for Shadow {
/// ///
/// # Example /// # Example
/// ``` /// ```
/// use adduser::NewFromString; /// use umanux::NewFromString;
/// let shad = adduser::Shadow::new_from_string( /// let shad = umanux::Shadow::new_from_string(
/// "test:!!$6$/RotIe4VZzzAun4W$7YUONvru1rDnllN5TvrnOMsWUD5wSDUPAD6t6/Xwsr/0QOuWF3HcfAhypRkGa8G1B9qqWV5kZSnCb8GKMN9N61:18260:0:99999:7:::".to_string(), /// "test:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18260:0:99999:7:::".to_string(),
/// 0, /// 0,
/// ).unwrap(); /// ).unwrap();
/// assert_eq!(shad.get_username(), "test"); /// assert_eq!(shad.get_username(), "test");
@@ -108,7 +104,7 @@ impl NewFromString for Shadow {
let extra = elements.get(8).unwrap(); let extra = elements.get(8).unwrap();
Ok(Self { Ok(Self {
pos: position, pos: position,
source: line.clone(), source: line,
username: crate::Username::try_from(elements.get(0).unwrap().to_string())?, username: crate::Username::try_from(elements.get(0).unwrap().to_string())?,
password: crate::EncryptedPassword::try_from(elements.get(1).unwrap().to_string())?, password: crate::EncryptedPassword::try_from(elements.get(1).unwrap().to_string())?,
last_change: date_since_epoch(elements.get(2).unwrap()), last_change: date_since_epoch(elements.get(2).unwrap()),
@@ -156,7 +152,7 @@ fn duration_for_days(days_source: &str) -> Option<chrono::Duration> {
#[test] #[test]
fn test_parse_and_back_identity() { fn test_parse_and_back_identity() {
let line = "test:!!$6$/RotIe4VZzzAun4W$7YUONvru1rDnllN5TvrnOMsWUD5wSDUPAD6t6/Xwsr/0QOuWF3HcfAhypRkGa8G1B9qqWV5kZSnCb8GKMN9N61:18260:0:99999:7:::"; let line = "test:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18260:0:99999:7:::";
let line2 = Shadow::new_from_string(line.to_owned(), 0).unwrap(); let line2 = Shadow::new_from_string(line.to_owned(), 0).unwrap();
assert_eq!(format!("{}", line2), line); assert_eq!(format!("{}", line2), line);
} }
+70 -37
View File
@@ -1,12 +1,13 @@
use std::path::PathBuf; use std::{io::Seek, io::SeekFrom, path::PathBuf};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use std::fs::File; use std::fs::{File, OpenOptions};
use std::io::Read; use std::io::Read;
use std::io::Write; use std::io::Write;
use std::ops::Deref; use std::ops::Deref;
#[derive(Debug)]
pub struct Files { pub struct Files {
pub passwd: Option<PathBuf>, pub passwd: Option<PathBuf>,
pub shadow: Option<PathBuf>, pub shadow: Option<PathBuf>,
@@ -26,7 +27,8 @@ impl Default for Files {
impl Files { impl Files {
/// Check if all the files are defined. Because some operations require the files to be present /// Check if all the files are defined. Because some operations require the files to be present
pub fn is_virtual(&self) -> bool { #[must_use]
pub const fn is_virtual(&self) -> bool {
!(self.group.is_some() & self.passwd.is_some() & self.shadow.is_some()) !(self.group.is_some() & self.passwd.is_some() & self.shadow.is_some())
} }
pub fn lock_and_get_passwd(&self) -> Result<LockedFileGuard, crate::UserLibError> { pub fn lock_and_get_passwd(&self) -> Result<LockedFileGuard, crate::UserLibError> {
@@ -61,12 +63,30 @@ impl Files {
} }
} }
#[derive(Debug)]
pub struct LockedFileGuard { pub struct LockedFileGuard {
lockfile: PathBuf, lockfile: PathBuf,
path: PathBuf, path: PathBuf,
pub(crate) file: File, pub(crate) file: File,
} }
#[derive(Debug)]
struct TempLockFile {
tlf: PathBuf,
}
impl Drop for TempLockFile {
fn drop(&mut self) {
info!("removing temporary lockfile {}", self.tlf.to_str().unwrap());
std::fs::remove_file(&self.tlf).unwrap();
}
}
impl Deref for TempLockFile {
type Target = PathBuf;
fn deref(&self) -> &PathBuf {
&self.tlf
}
}
impl LockedFileGuard { impl LockedFileGuard {
pub fn new(path: &PathBuf) -> Result<Self, crate::UserLibError> { pub fn new(path: &PathBuf) -> Result<Self, crate::UserLibError> {
let locked = Self::try_to_lock_file(path); let locked = Self::try_to_lock_file(path);
@@ -81,14 +101,39 @@ impl LockedFileGuard {
} }
pub fn replace_contents(&mut self, new_content: String) -> Result<(), crate::UserLibError> { pub fn replace_contents(&mut self, new_content: String) -> Result<(), crate::UserLibError> {
self.file = File::create(&self.path).expect("Failed to truncate file."); self.file = match File::create(&self.path) {
self.file Ok(file) => file,
.write_all(&new_content.into_bytes()) Err(e) => return Err(("Failed to truncate file.".to_owned(), e).into()),
.expect("Failed to write all users."); };
let _ = self.file.write("\n".as_bytes()); match self.file.write_all(&new_content.into_bytes()) {
Ok(_) => (),
Err(e) => return Err(("Could not write (all) users. ".to_owned(), e).into()),
};
let _ = self.file.write(b"\n");
Ok(()) Ok(())
} }
pub fn append(&mut self, appendee: String) -> Result<(), crate::UserLibError> {
// Seek to the last character.
self.file.seek(SeekFrom::End(-1)).map_or_else(
|e| Err(format!("Failed to append to file {}", e)),
|_| Ok(()),
)?;
// Read the last character
let mut b = [0_u8; 1];
self.file.read_exact(&mut b)?;
// Verify it is '\n' else append '\n' so in any case the file ends with with a newline now
if &b != b"\n" {
//self.file.write_all(&b)?;
self.file.write_all(b"\n")?;
}
// write the new line.
self.file.write_all(&appendee.into_bytes()).map_or_else(
|e| Err(("Failed to append to file".to_owned(), e).into()),
Ok,
)
}
/// This function tries to lock a file in the way other passwd locking mechanisms work. /// This function tries to lock a file in the way other passwd locking mechanisms work.
/// ///
/// * get the pid /// * get the pid
@@ -113,22 +158,6 @@ impl LockedFileGuard {
/// * try to lock again now that the old logfile has been safely removed. /// * try to lock again now that the old logfile has been safely removed.
/// * remove the original file and only keep the lock hardlink /// * remove the original file and only keep the lock hardlink
fn try_to_lock_file(path: &PathBuf) -> Result<(PathBuf, File), crate::UserLibError> { fn try_to_lock_file(path: &PathBuf) -> Result<(PathBuf, File), crate::UserLibError> {
struct TempLockFile {
tlf: PathBuf,
}
impl Drop for TempLockFile {
fn drop(&mut self) {
info!("removing temporary lockfile {}", self.tlf.to_str().unwrap());
std::fs::remove_file(&self.tlf).unwrap();
}
}
impl Deref for TempLockFile {
type Target = PathBuf;
fn deref(&self) -> &PathBuf {
&self.tlf
}
}
info!("locking file {}", path.to_string_lossy()); info!("locking file {}", path.to_string_lossy());
let mut tempfilepath_const = path.clone(); let mut tempfilepath_const = path.clone();
// get the pid // get the pid
@@ -151,12 +180,19 @@ impl LockedFileGuard {
); );
// write the pid into the tempfile // write the pid into the tempfile
{ {
let mut tempfile = File::create(&*tempfilepath) let mut tempfile = File::create(&*tempfilepath).unwrap_or_else(|e| {
.expect(&format!("Failed to open {}", filename.to_str().unwrap())); panic!("Failed to open {} error: {}", filename.to_str().unwrap(), e)
match write!(tempfile, "{}", pid) { });
Ok(_) => {} write!(tempfile, "{}", pid).or_else(|e| {
Err(_) => error!("could not write to {}", filename.to_string_lossy()), let error_msg = format!(
}; "could not write to {} error {}",
filename.to_string_lossy(),
e
);
error!("{}", error_msg);
let err: crate::UserLibError = error_msg.into();
Err(err)
})?;
} }
// try to make a hardlink from the lockfile to the tempfile // try to make a hardlink from the lockfile to the tempfile
@@ -166,7 +202,7 @@ impl LockedFileGuard {
debug!("successfully locked"); debug!("successfully locked");
// open the file // open the file
let resfile = File::open(&path); let resfile = OpenOptions::new().read(true).write(true).open(&path);
return match resfile { return match resfile {
Ok(file) => Ok((lockfilepath, file)), Ok(file) => Ok((lockfilepath, file)),
Err(e) => { Err(e) => {
@@ -194,12 +230,9 @@ impl LockedFileGuard {
} }
}; };
let mut content = String::new(); let mut content = String::new();
match lf.read_to_string(&mut content) { lf.read_to_string(&mut content)
Ok(_) => {} .unwrap_or_else(|e| panic!("failed to read the lockfile{}", e));
Err(_) => {
panic!("failed to read the lockfile{}", e);
}
}
let content = content.trim().trim_matches(char::from(0)); let content = content.trim().trim_matches(char::from(0));
let lock_pid = content.parse::<u32>(); let lock_pid = content.parse::<u32>();
match lock_pid { match lock_pid {
+3
View File
@@ -5,11 +5,13 @@ pub struct SourceHash {
} }
impl SourceHash { impl SourceHash {
#[must_use]
pub fn new(src: &str) -> Self { pub fn new(src: &str) -> Self {
Self { Self {
hashvalue: src.to_owned(), hashvalue: src.to_owned(),
} }
} }
#[must_use]
pub fn has_changed(&self, new: &str) -> bool { pub fn has_changed(&self, new: &str) -> bool {
trace!( trace!(
"Old and new lengths: {}, {}", "Old and new lengths: {}, {}",
@@ -27,6 +29,7 @@ pub struct Hashes {
} }
impl Hashes { impl Hashes {
#[must_use]
pub fn new(passwd: &str, shadow: &str, group: &str) -> Self { pub fn new(passwd: &str, shadow: &str, group: &str) -> Self {
Self { Self {
passwd: SourceHash::new(passwd), passwd: SourceHash::new(passwd),
+330 -138
View File
@@ -1,27 +1,27 @@
#![warn(
clippy::all,
//clippy::restriction,
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
#![allow(clippy::non_ascii_literal)] #![allow(clippy::non_ascii_literal)]
pub mod files; pub mod files;
pub mod hashes; pub mod hashes;
use crate::api::GroupRead; use crate::{
use crate::api::UserRead; api::{
CreateUserArgs, DeleteHome, DeleteUserArgs, GroupRead, UserDBRead, UserDBWrite, UserRead,
},
group::MembershipKind,
UserLibError,
};
#[allow(unused_imports)] #[allow(unused_imports)]
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use std::collections::HashMap; use std::collections::HashMap;
use std::fs::File; use std::fs::File;
use std::io::{BufReader, Read}; use std::io::{BufReader, Read};
pub type UserList = HashMap<String, crate::User>;
pub struct UserDBLocal { pub struct UserDBLocal {
source_files: files::Files, source_files: files::Files,
source_hashes: hashes::Hashes, // to detect changes source_hashes: hashes::Hashes, // to detect changes
pub users: HashMap<String, crate::User>, pub users: UserList,
pub groups: Vec<crate::Group>, pub groups: Vec<crate::Group>,
} }
@@ -33,11 +33,12 @@ impl UserDBLocal {
shadow_content: &str, shadow_content: &str,
group_content: &str, group_content: &str,
) -> Self { ) -> Self {
let shadow_entries: Vec<crate::Shadow> = string_to(&shadow_content); let shadow_entries: Vec<crate::Shadow> = string_to(shadow_content);
let mut users = user_vec_to_hashmap(string_to(&passwd_content)); let mut users = user_vec_to_hashmap(string_to(passwd_content));
let groups = string_to(&group_content); let mut groups = string_to(group_content);
shadow_to_users(&mut users, shadow_entries); shadow_to_users(&mut users, shadow_entries);
let res = Self { groups_to_users(&mut users, &mut groups);
Self {
source_files: files::Files { source_files: files::Files {
passwd: None, passwd: None,
group: None, group: None,
@@ -45,13 +46,11 @@ impl UserDBLocal {
}, },
users, users,
groups, groups,
source_hashes: hashes::Hashes::new(&passwd_content, &shadow_content, &group_content), source_hashes: hashes::Hashes::new(passwd_content, shadow_content, group_content),
}; }
res
} }
/// Import the database from a [`Files`] struct /// Import the database from a [`Files`] struct
#[must_use]
pub fn load_files(files: files::Files) -> Result<Self, crate::UserLibError> { pub fn load_files(files: files::Files) -> Result<Self, crate::UserLibError> {
// Get the Strings for the files use an inner block to drop references after read. // Get the Strings for the files use an inner block to drop references after read.
let (my_passwd_lines, my_shadow_lines, my_group_lines) = { let (my_passwd_lines, my_shadow_lines, my_group_lines) = {
@@ -67,136 +66,248 @@ impl UserDBLocal {
let mut users = user_vec_to_hashmap(string_to(&my_passwd_lines)); let mut users = user_vec_to_hashmap(string_to(&my_passwd_lines));
let passwds: Vec<crate::Shadow> = string_to(&my_shadow_lines); let passwds: Vec<crate::Shadow> = string_to(&my_shadow_lines);
let mut groups: Vec<crate::Group> = string_to(&my_group_lines);
shadow_to_users(&mut users, passwds); shadow_to_users(&mut users, passwds);
groups_to_users(&mut users, &mut groups);
Ok(Self { Ok(Self {
source_files: files, source_files: files,
users, users,
groups: string_to(&my_group_lines), groups,
source_hashes: hashes::Hashes::new(&my_passwd_lines, &my_shadow_lines, &my_group_lines), source_hashes: hashes::Hashes::new(&my_passwd_lines, &my_shadow_lines, &my_group_lines),
}) })
} }
fn delete_from_passwd(
user: &crate::User,
passwd_file_content: &str,
locked_p: &mut files::LockedFileGuard,
) -> Result<(), UserLibError> {
let modified_p = user.remove_in(passwd_file_content);
// write the new content to the file.
let ncont = locked_p.replace_contents(modified_p);
match ncont {
Ok(_) => Ok(()),
Err(e) => Err(format!("Failed to write the passwd database: {}", e).into()),
}
}
fn delete_from_shadow(
user: &crate::User,
shadow_file_content: &str,
locked_s: &mut files::LockedFileGuard,
) -> Result<(), UserLibError> {
let shad = user.get_shadow();
match shad {
Some(shadow) => {
let modified_s = shadow.remove_in(shadow_file_content);
let ncont = locked_s.replace_contents(modified_s);
match ncont {
Ok(_) => Ok(()),
Err(e) => Err(format!(
"Error during write to the database. \
Please doublecheck as the shadowdatabase could be corrupted: {}",
e,
)
.into()),
}
}
None => Ok(()),
}
}
fn delete_from_group(
group: &crate::Group,
group_file_content: &str,
locked_g: &mut files::LockedFileGuard,
) -> Result<(), UserLibError> {
let modified_g = group.borrow().remove_in(group_file_content);
let replace_result = locked_g.replace_contents(modified_g);
match replace_result {
Ok(_) => Ok(()),
Err(e) => Err(format!(
"Error during write to the database. \
Please doublecheck as the groupdatabase could be corrupted: {}",
e,
)
.into()),
}
}
fn write_groups(&self, locked_g: &mut files::LockedFileGuard) -> Result<(), UserLibError> {
let content = self
.groups
.iter()
.map(|g| (g.borrow().to_string()))
.collect::<Vec<String>>()
.join("\n");
let replace_result = locked_g.replace_contents(content);
match replace_result {
Ok(_) => Ok(()),
Err(e) => Err(format!(
"Error during write to the database. \
Please doublecheck as the groupdatabase could be corrupted: {}",
e,
)
.into()),
}
}
fn delete_home(user: &crate::User) -> std::io::Result<()> {
if let Some(dir) = user.get_home_dir() {
std::fs::remove_dir_all(dir)
} else {
let error_msg = "Failed to remove the home directory! As the user did not have one.";
error!("{}", error_msg);
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
error_msg,
))
}
}
fn delete_group_by_id(&mut self, gid: u32) {
self.groups
.retain(|g| g.borrow().get_gid().expect("groups have to have a gid") != gid);
}
} }
use crate::api::UserDBWrite;
impl UserDBWrite for UserDBLocal { impl UserDBWrite for UserDBLocal {
fn delete_user(&mut self, username: &str) -> Result<crate::User, crate::UserLibError> { fn delete_user(&mut self, args: DeleteUserArgs) -> Result<crate::User, UserLibError> {
// try to get the user from the database // try to get the user from the database
let user_opt = self.users.get(username); let user_opt = self.get_user_by_name(args.username);
let user = match user_opt { let user = match user_opt {
Some(user) => user, Some(user) => user,
None => { None => {
return Err(crate::UserLibError::NotFound); return Err(UserLibError::NotFound);
} }
}; };
if self.source_files.is_virtual() { if self.source_files.is_virtual() {
warn!("There are no associated files working in dummy mode!"); warn!("There are no associated files working in dummy mode!");
let res = self.users.remove(username); let res = self.users.remove(args.username);
match res { match res {
Some(u) => Ok(u), Some(u) => Ok(u),
None => Err(crate::UserLibError::NotFound), None => Err(UserLibError::NotFound), // should not happen anymore as existence is checked.
} }
} else { } else {
let opened = self.source_files.lock_all_get(); let opened = self.source_files.lock_all_get();
let (mut locked_p, mut locked_s, locked_g) = opened.expect("failed to lock files!"); let (mut locked_p, mut locked_s, mut locked_g) = opened.expect("failed to lock files!");
// read the files to strings // read the files to strings
let p = file_to_string(&locked_p.file)?; let passwd_file_content = file_to_string(&locked_p.file)?;
let s = file_to_string(&locked_s.file)?; let shadow_file_content = file_to_string(&locked_s.file)?;
let _g = file_to_string(&locked_g.file)?; let group_file_content = file_to_string(&locked_g.file)?;
{
let src = &self.source_hashes;
if src.passwd.has_changed(&p) | src.shadow.has_changed(&s) {
error!("The source files have changed. Deleting the user could corrupt the userdatabase. Aborting!");
} else {
// create the new content of passwd
let modified_p = user.remove_in(&p);
// write the new content to the file. let src = &self.source_hashes;
let ncont = locked_p.replace_contents(modified_p); if src.passwd.has_changed(&passwd_file_content)
match ncont { | src.shadow.has_changed(&shadow_file_content)
Ok(_) => { {
let shad = user.get_shadow(); error!("The source files have changed. Deleting the user could corrupt the userdatabase. Aborting!");
match shad { Err(format!("The userdatabase has been changed {}", args.username).into())
Some(shadow) => { } else {
let modified_s = shadow.remove_in(&s); Self::delete_from_passwd(user, &passwd_file_content, &mut locked_p)?;
let ncont = locked_s.replace_contents(modified_s); Self::delete_from_shadow(user, &shadow_file_content, &mut locked_s)?;
match ncont { if args.delete_home == DeleteHome::Delete {
Ok(_) => (), Self::delete_home(user)?;
Err(e) => { }
return Err(format!( trace!("The users groups: {:#?}", user.get_groups());
"Error during write to the database. \ // Iterate over the GIDs to avoid borrowing issues
Please doublecheck as the shadowdatabase could be corrupted: {}", let users_groups: Vec<(MembershipKind, u32)> = user
e, .get_groups()
) .iter()
.into()); .map(|(k, g)| (*k, g.borrow().get_gid().unwrap()))
} .collect();
} for (kind, group) in users_groups {
} trace!("Woring on group: {:?} - {}", kind, group);
None => (), match kind {
crate::group::MembershipKind::Primary => {
if self
.get_group_by_id(group)
.expect("The group does not exist")
.borrow()
.get_member_names()
.expect("this group allways has a member")
.len()
== 1
{
trace!(
"Deleting group as the user to be deleted is the only member {}", self
.get_group_by_id(group)
.expect("The group does not exist")
.borrow()
.get_groupname().expect("a group has to have a name")
);
Self::delete_from_group(
self.get_group_by_id(group)
.expect("The group does not exist"),
&group_file_content,
&mut locked_g,
)?;
self.delete_group_by_id(group);
} else {
// remove the from the group instead of deleting the group if he was not the only user in its primary group.
if let Some(group) = self.get_group_by_id(group) {
group
.borrow_mut()
.remove_member(MembershipKind::Primary, args.username)
};
self.write_groups(&mut locked_g)?;
warn!(
"The primary group (GID: {}) was not empty and is thus not removed. Only the membership has been removed",
group
);
} }
// Remove the user from the memory database(HashMap)
let res = self.users.remove(username);
return Ok(
res.expect("Failed to remove the user from the internal HashMap")
);
} }
Err(e) => { crate::group::MembershipKind::Member => {
return Err(format!( trace!("delete the membership in the group");
"Error during write to the database. \ if let Some(group) = self.get_group_by_id(group) {
Please doublecheck as the userdatabase could be corrupted: {}", group
e, .borrow_mut()
) .remove_member(MembershipKind::Member, args.username)
.into()); };
self.write_groups(&mut locked_g)?;
} }
} }
} }
Err(format!("The userdatabase has been changed {}", username).into()) // Remove the user from the memory database(HashMap)
let res = self.users.remove(args.username);
match res {
Some(u) => Ok(u),
None => Err("Failed to remove the user from the internal HashMap".into()),
}
} }
} }
} }
fn new_user( fn new_user(&mut self, args: CreateUserArgs) -> Result<&crate::User, crate::UserLibError> {
&mut self, /* if self.users.contains_key(args.username) {
username: String, Err(format!("The username {} already exists! Aborting!", args.username).into())
enc_password: String,
uid: u32,
gid: u32,
full_name: String,
room: String,
phone_work: String,
phone_home: String,
other: Option<Vec<String>>,
home_dir: String,
shell_path: String,*/
) -> Result<&crate::User, crate::UserLibError> {
/*if self.users.contains_key(&username) {
Err(format!(
"The username {} already exists! Aborting!",
username
)
.into())
} else { } else {
let pwd = if self.source_files.shadow.is_none(){ let mut new_user = crate::User::default();
crate::Password::Encrypted(crate::EncryptedPassword{}); new_user.username(args.username.to_owned());
if self.users.contains_key(args.username) {
Err("Failed to create the user. A user with the same Name already exists".into())
} else {
let opened = self.source_files.lock_all_get();
let (mut locked_p, mut locked_s, mut _locked_g) =
opened.expect("failed to lock files!");
//dbg!(&locked_p);
locked_p.append(format!("{}", new_user))?;
if let Some(shadow) = new_user.get_shadow() {
info!("Adding shadow entry {}", shadow);
locked_s.append(format!("{}", shadow))?;
} else {
warn!("Omitting shadow entry!")
}
assert!(self
.users
.insert(args.username.to_owned(), new_user)
.is_none());
self.users
.get(args.username)
.map_or_else(|| Err("User was not successfully added!".into()), Ok)
} }
else{ }
crate::Password::Shadow(crate::Shadow{})
}
self.users.insert(
username,
crate::User {
username: crate::Username { username },
password:,
uid: crate::Uid{uid},
gid:crate::Gid{gid},
gecos: crate::Gecos{},
home_dir:crate::HomeDir{dir: home_dir},
shell_path: crate::ShellPath{shell: shell_path},
},
)
}*/
todo!()
} }
fn delete_group(&mut self, _group: &crate::Group) -> Result<(), crate::UserLibError> { fn delete_group(&mut self, _group: &crate::Group) -> Result<(), crate::UserLibError> {
@@ -208,7 +319,6 @@ impl UserDBWrite for UserDBLocal {
} }
} }
use crate::api::UserDBRead;
impl UserDBRead for UserDBLocal { impl UserDBRead for UserDBLocal {
fn get_all_users(&self) -> Vec<&crate::User> { fn get_all_users(&self) -> Vec<&crate::User> {
let mut res: Vec<&crate::User> = self.users.iter().map(|(_, x)| x).collect(); let mut res: Vec<&crate::User> = self.users.iter().map(|(_, x)| x).collect();
@@ -222,21 +332,21 @@ impl UserDBRead for UserDBLocal {
fn get_user_by_id(&self, uid: u32) -> Option<&crate::User> { fn get_user_by_id(&self, uid: u32) -> Option<&crate::User> {
// could probably be more efficient - on the other hand its no problem to loop a thousand users. // could probably be more efficient - on the other hand its no problem to loop a thousand users.
for (_, user) in self.users.iter() { for user in self.users.values() {
if user.get_uid() == uid { if user.get_uid() == uid {
return Some(&user); return Some(user);
} }
} }
None None
} }
fn get_all_groups(&self) -> Vec<&crate::Group> { fn get_all_groups(&self) -> Vec<crate::Group> {
self.groups.iter().collect() self.groups.iter().map(std::clone::Clone::clone).collect()
} }
fn get_group_by_name(&self, name: &str) -> Option<&crate::Group> { fn get_group_by_name(&self, name: &str) -> Option<&crate::Group> {
for group in self.groups.iter() { for group in &self.groups {
if group.get_groupname()? == name { if group.borrow().get_groupname()? == name {
return Some(group); return Some(group);
} }
} }
@@ -244,8 +354,8 @@ impl UserDBRead for UserDBLocal {
} }
fn get_group_by_id(&self, id: u32) -> Option<&crate::Group> { fn get_group_by_id(&self, id: u32) -> Option<&crate::Group> {
for group in self.groups.iter() { for group in &self.groups {
if group.get_gid()? == id { if group.borrow().get_gid()? == id {
return Some(group); return Some(group);
} }
} }
@@ -269,7 +379,9 @@ impl UserDBValidation for UserDBLocal {
fn is_gid_valid_and_free(&self, gid: u32) -> bool { fn is_gid_valid_and_free(&self, gid: u32) -> bool {
warn!("No valid check, only free check"); warn!("No valid check, only free check");
self.groups.iter().all(|x| x.get_gid().unwrap() != gid) self.groups
.iter()
.all(|x| x.borrow().get_gid().unwrap() != gid)
} }
fn is_groupname_valid_and_free(&self, name: &str) -> bool { fn is_groupname_valid_and_free(&self, name: &str) -> bool {
@@ -277,7 +389,7 @@ impl UserDBValidation for UserDBLocal {
let free = self let free = self
.groups .groups
.iter() .iter()
.all(|x| x.get_groupname().unwrap() != name); .all(|x| x.borrow().get_groupname().unwrap() != name);
valid && free valid && free
} }
} }
@@ -293,22 +405,63 @@ fn file_to_string(file: &File) -> Result<String, crate::UserLibError> {
} }
} }
fn groups_to_users<'a>(
users: &'a mut UserList,
groups: &'a mut [crate::Group],
) -> &'a mut UserList {
// Populate the regular groups
for group in groups.iter() {
match group.borrow().get_member_names() {
Some(usernames) => {
for username in usernames {
if let Some(user) = users.get_mut(username) {
user.add_group(crate::group::MembershipKind::Member, group.clone());
}
}
}
None => continue,
}
}
// Populate the primary membership
for user in users.values_mut() {
let gid = user.get_gid();
let grouplist: Vec<&crate::Group> = groups
.iter()
.filter(|g| g.borrow().get_gid().unwrap() == gid)
.collect();
if grouplist.len() == 1 {
let group = *grouplist.first().unwrap();
group.borrow_mut().append_user(
user.get_username()
.expect("Users without username are not supported"),
);
user.add_group(crate::group::MembershipKind::Primary, group.clone());
} else {
error!(
"Somehow the group with gid {} was found {} times",
gid,
grouplist.len()
);
}
}
users
}
/// Merge the Shadow passwords into the users /// Merge the Shadow passwords into the users
fn shadow_to_users( fn shadow_to_users(users: &mut UserList, shadow: Vec<crate::Shadow>) -> &mut UserList {
users: &mut HashMap<String, crate::User>,
shadow: Vec<crate::Shadow>,
) -> &mut HashMap<String, crate::User> {
for pass in shadow { for pass in shadow {
let user = users let user = users
.get_mut(pass.get_username()) .get_mut(pass.get_username())
.expect(&format!("the user {} does not exist", pass.get_username())); .unwrap_or_else(|| panic!("the user {} does not exist", pass.get_username()));
user.password = crate::Password::Shadow(pass); user.password = crate::Password::Shadow(pass);
} }
users users
} }
/// Convert a `Vec<crate::User>` to a `HashMap<String, crate::User>` where the username is used as key /// Convert a `Vec<crate::User>` to a `UserList` (`HashMap<String, crate::User>`) where the username is used as key
fn user_vec_to_hashmap(users: Vec<crate::User>) -> HashMap<String, crate::User> { fn user_vec_to_hashmap(users: Vec<crate::User>) -> UserList {
users users
.into_iter() .into_iter()
.map(|x| { .map(|x| {
@@ -322,7 +475,7 @@ fn user_vec_to_hashmap(users: Vec<crate::User>) -> HashMap<String, crate::User>
.collect() .collect()
} }
/// Try to parse a String into some Object /// Try to parse a String into some Object.
/// ///
/// # Errors /// # Errors
/// if the parsing failed a [`UserLibError::Message`](crate::userlib_error::UserLibError::Message) is returned containing a more detailed error message. /// if the parsing failed a [`UserLibError::Message`](crate::userlib_error::UserLibError::Message) is returned containing a more detailed error message.
@@ -337,12 +490,20 @@ fn string_to<T>(source: &str) -> Vec<T>
where where
T: NewFromString, T: NewFromString,
{ {
use std::convert::TryInto;
source source
.lines() .lines()
.enumerate() .enumerate()
.filter_map(|(n, line)| { .filter_map(|(n, line)| {
if line.len() > 5 { if line.len() > 5 {
Some(T::new_from_string(line.to_owned(), n as u32).expect("failed to read lines")) Some(
T::new_from_string(
line.to_owned(),
n.try_into()
.unwrap_or_else(|e| panic!("Failed to convert usize to u32 {}", e)),
)
.expect("failed to read lines"),
)
} else { } else {
None None
} }
@@ -352,11 +513,21 @@ where
#[test] #[test]
fn test_creator_user_db_local() { fn test_creator_user_db_local() {
let data = UserDBLocal::import_from_strings("test:x:1001:1001:full Name,004,000342,001-2312,myemail@test.com:/home/test:/bin/test", "test:!!$6$/RotIe4VZzzAun4W$7YUONvru1rDnllN5TvrnOMsWUD5wSDUPAD6t6/Xwsr/0QOuWF3HcfAhypRkGa8G1B9qqWV5kZSnCb8GKMN9N61:18260:0:99999:7:::", "teste:x:1002:test,test"); let data = UserDBLocal::import_from_strings("test:x:1002:1002:full Name,004,000342,001-2312,myemail@test.com:/home/test:/bin/test", "test:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18260:0:99999:7:::", "teste:x:1002:\nanother:x:1003:test");
assert_eq!( assert_eq!(
data.users.get("test").unwrap().get_username().unwrap(), data.users.get("test").unwrap().get_username().unwrap(),
"test" "test"
) );
for user in data.users.values() {
dbg!(user.get_groups());
let (member_group1, group1) = user.get_groups().first().unwrap();
let (member_group2, group2) = user.get_groups().get(1).unwrap();
assert_eq!(*member_group1, crate::group::MembershipKind::Member);
assert_eq!(group1.borrow().get_groupname(), Some("another"));
assert_eq!(*member_group2, crate::group::MembershipKind::Primary);
assert_eq!(group2.borrow().get_groupname(), Some("teste"));
}
} }
#[test] #[test]
@@ -368,7 +539,15 @@ fn test_parsing_local_database() {
let my_passwd_lines = file_to_string(&pwdfile).unwrap(); let my_passwd_lines = file_to_string(&pwdfile).unwrap();
let my_group_lines = file_to_string(&grpfile).unwrap(); let my_group_lines = file_to_string(&grpfile).unwrap();
let data = UserDBLocal::import_from_strings(&my_passwd_lines, "", &my_group_lines); let data = UserDBLocal::import_from_strings(&my_passwd_lines, "", &my_group_lines);
assert_eq!(data.groups.get(0).unwrap().get_groupname().unwrap(), "root"); assert_eq!(
data.groups
.get(0)
.unwrap()
.borrow()
.get_groupname()
.unwrap(),
"root"
);
} }
#[test] #[test]
@@ -390,11 +569,19 @@ fn test_user_db_read_implementation() {
assert!(data.get_all_groups().len() > 10); assert!(data.get_all_groups().len() > 10);
assert!(data.get_group_by_name("root").is_some()); assert!(data.get_group_by_name("root").is_some());
assert_eq!( assert_eq!(
data.get_group_by_name("root").unwrap().get_gid().unwrap(), data.get_group_by_name("root")
.unwrap()
.borrow()
.get_gid()
.unwrap(),
0 0
); );
assert_eq!( assert_eq!(
data.get_group_by_id(0).unwrap().get_groupname().unwrap(), data.get_group_by_id(0)
.unwrap()
.borrow()
.get_groupname()
.unwrap(),
"root" "root"
); );
assert!(data.get_user_by_name("norealnameforsure").is_none()); assert!(data.get_user_by_name("norealnameforsure").is_none());
@@ -403,11 +590,16 @@ fn test_user_db_read_implementation() {
#[test] #[test]
fn test_user_db_write_implementation() { fn test_user_db_write_implementation() {
let mut data = UserDBLocal::import_from_strings("test:x:1001:1001:full Name,004,000342,001-2312,myemail@test.com:/home/test:/bin/test", "test:!!$6$/RotIe4VZzzAun4W$7YUONvru1rDnllN5TvrnOMsWUD5wSDUPAD6t6/Xwsr/0QOuWF3HcfAhypRkGa8G1B9qqWV5kZSnCb8GKMN9N61:18260:0:99999:7:::", "teste:x:1002:test,test"); use crate::api::DeleteUserArgs;
let mut data = UserDBLocal::import_from_strings("test:x:1001:1001:full Name,004,000342,001-2312,myemail@test.com:/home/test:/bin/test", "test:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18260:0:99999:7:::", "teste:x:1002:test,test");
let user = "test"; let user = "test";
assert_eq!(data.get_all_users().len(), 1); assert_eq!(data.get_all_users().len(), 1);
assert!(data.delete_user(&user).is_ok()); assert!(data
assert!(data.delete_user(&user).is_err()); .delete_user(DeleteUserArgs::builder().username(user).build().unwrap())
.is_ok());
assert!(data
.delete_user(DeleteUserArgs::builder().username(user).build().unwrap())
.is_err());
assert_eq!(data.get_all_users().len(), 0); assert_eq!(data.get_all_users().len(), 0);
} }
+123
View File
@@ -0,0 +1,123 @@
extern crate test_bin;
extern crate umanux;
mod testfiles;
#[test]
fn test_create_user_function() {
use testfiles::Fixture;
use std::fs;
use umanux::api::UserDBWrite;
use umanux::api::UserRead;
let p = Fixture::copy("passwd");
let s = Fixture::copy("shadow");
let g = Fixture::copy("group");
let pf = fs::read_to_string(&p.path).unwrap();
let mf = umanux::Files {
passwd: Some(p.path.clone()),
shadow: Some(s.path),
group: Some(g.path),
};
let mut db = umanux::UserDBLocal::load_files(mf).unwrap();
let user_res: Result<&umanux::User, umanux::UserLibError> = db.new_user(
umanux::api::CreateUserArgs::builder()
.username("test2")
// .delete_home(umanux::api::DeleteHome::Delete)
.build()
.unwrap(),
);
let password_file_string = fs::read_to_string(&p.path).unwrap();
let shadow_file_string = fs::read_to_string(&p.path).unwrap();
assert_eq!(user_res.unwrap().get_username().unwrap(), "test2");
let pflines = pf.lines();
let pflines2 = password_file_string.lines();
for (l1, l2) in pflines.zip(pflines2) {
dbg!(l1, l2);
assert!(l1 == l2);
}
assert!(password_file_string
.lines()
.last()
.unwrap()
.starts_with("test2"));
assert!(shadow_file_string
.lines()
.last()
.unwrap()
.starts_with("test2"));
}
#[test]
fn test_create_user_binary() {
use testfiles::Fixture;
use std::fs;
let p = Fixture::copy("passwd");
let s = Fixture::copy("shadow");
let g = Fixture::copy("group");
//dbg!(&p, &s, &g);
let passwd_string = fs::read_to_string(&p.path).unwrap();
let passwd_lines = passwd_string.lines();
let shadow_string = fs::read_to_string(&s.path).unwrap();
let shadow_lines = shadow_string.lines();
let out = test_bin::get_test_bin("create_user")
.args(&[
"testuser3",
"-p",
p.path.to_str().unwrap(),
"-s",
s.path.to_str().unwrap(),
"-g",
g.path.to_str().unwrap(),
])
.output()
.expect("Failed to run the command");
println!(
"The output after running: {}",
String::from_utf8_lossy(&out.stdout)
);
println!(
"The error after running: {}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(String::from_utf8_lossy(&out.stdout), "");
assert_eq!(String::from_utf8_lossy(&out.stderr), "");
let passwd_string_after = fs::read_to_string(&p.path).unwrap();
let passwd_lines_after = passwd_string_after.lines();
let shadow_string_after = fs::read_to_string(&s.path).unwrap();
let shadow_lines_after = shadow_string_after.lines();
for (l1, l2) in passwd_lines.zip(passwd_lines_after) {
//dbg!(l1, l2);
assert!(l1 == l2);
}
assert_eq!(
passwd_string_after
.lines()
.last()
.unwrap()
.starts_with("testuser3"),
true
);
//dbg!(&shadow_string_after);
for (l1, l2) in shadow_lines.zip(shadow_lines_after) {
//dbg!(l1, l2);
assert!(l1 == l2);
}
assert_eq!(
shadow_string_after
.lines()
.last()
.unwrap()
.starts_with("testuser3"),
true
);
}
+53
View File
@@ -0,0 +1,53 @@
extern crate umanux;
mod testfiles;
#[test]
fn test_delete_user_function() {
use testfiles::Fixture;
use std::fs;
use umanux::api::UserDBWrite;
use umanux::api::UserRead;
let p = Fixture::copy("passwd");
let s = Fixture::copy("shadow");
let g = Fixture::copy("group");
let pf = fs::read_to_string(&p.path).unwrap();
let mf = umanux::Files {
passwd: Some(p.path.clone()),
shadow: Some(s.path),
group: Some(g.path.clone()),
};
let mut db = umanux::UserDBLocal::load_files(mf).unwrap();
let user_res: Result<umanux::User, umanux::UserLibError> = db.delete_user(
umanux::api::DeleteUserArgs::builder()
.username("teste")
// .delete_home(umanux::api::DeleteHome::Delete)
.build()
.unwrap(),
);
let pf2 = fs::read_to_string(&p.path).unwrap();
assert_eq!(user_res.unwrap().get_username().unwrap(), "teste");
let pflines = pf.lines();
let pflines2 = pf2.lines();
for (l1, l2) in pflines.zip(pflines2.clone()) {
if l1 != l2 {
assert!(l1.starts_with("teste"));
assert!(l2.starts_with("bergfried"));
break;
}
}
for line in pflines2 {
assert!(!line.starts_with("teste"))
}
let groupfile2 = fs::read_to_string(&g.path).unwrap();
let groupfilelines2 = groupfile2.lines();
for line in groupfilelines2 {
println!("{}", &line);
assert!(!line.ends_with("teste"))
}
}
+93
View File
@@ -0,0 +1,93 @@
root:x:0:
bin:x:1:
daemon:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
lp:x:7:
mem:x:8:
kmem:x:9:
wheel:x:10:dietrich
cdrom:x:11:
mail:x:12:
man:x:15:
dialout:x:18:dietrich
floppy:x:19:
games:x:20:
tape:x:33:
video:x:39:
ftp:x:50:
lock:x:54:dietrich
audio:x:63:
users:x:100:
nobody:x:65534:
utmp:x:22:
utempter:x:35:
input:x:999:
kvm:x:36:qemu
render:x:998:
systemd-journal:x:190:
systemd-coredump:x:997:
systemd-network:x:192:
systemd-resolve:x:193:
dbus:x:81:
systemd-timesync:x:996:
tss:x:59:clevis
dip:x:40:
printadmin:x:995:
gluster:x:994:
qemu:x:107:
nm-openconnect:x:993:
usbmuxd:x:113:
geoclue:x:992:
polkitd:x:991:
rtkit:x:172:
pulse-access:x:990:
pulse-rt:x:989:
pulse:x:171:
chrony:x:988:
avahi:x:70:
pipewire:x:987:
dnsmasq:x:986:
saslauth:x:76:
radvd:x:75:
rpc:x:32:
ssh_keys:x:985:
openvpn:x:984:
nm-openvpn:x:983:
libvirt:x:982:dietrich
unbound:x:981:
brlapi:x:980:
apache:x:48:
colord:x:979:
rpcuser:x:29:
abrt:x:173:
flatpak:x:978:
gdm:x:42:
gnome-initial-setup:x:977:
sshd:x:74:
slocate:x:21:
vboxsf:x:976:
tcpdump:x:72:
wbpriv:x:88:
clevis:x:975:
cockpit-ws:x:974:
libvirtdbus:x:973:
setroubleshoot:x:972:
mysql:x:27:
firebird:x:971:
cockpit-wsinstance:x:970:
pbuilder:x:969:
teste:x:1002:test,teste
testnewgroup:x:1015:teste
hausle:x:1018:dietrich
bergfried:x:1009:
t1:x:1019:
t2:x:1020:
docker:x:968:
jackuser:x:967:
akmods:x:966:
mock:x:135:
rtlsdr:x:965:
Debian-exim:x:128:
+60
View File
@@ -0,0 +1,60 @@
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin
systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
systemd-timesync:x:998:996:systemd Time Synchronization:/:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
gluster:x:997:994:GlusterFS daemons:/run/gluster:/sbin/nologin
qemu:x:107:107:qemu user:/:/sbin/nologin
nm-openconnect:x:996:993:NetworkManager user for OpenConnect:/:/sbin/nologin
usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin
geoclue:x:995:992:User for geoclue:/var/lib/geoclue:/sbin/nologin
polkitd:x:994:991:User for polkitd:/:/sbin/nologin
rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin
pulse:x:171:171:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin
chrony:x:993:988::/var/lib/chrony:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
pipewire:x:992:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin
dnsmasq:x:986:986:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin
saslauth:x:985:76:Saslauthd user:/run/saslauthd:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
openvpn:x:984:984:OpenVPN:/etc/openvpn:/sbin/nologin
nm-openvpn:x:983:983:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin
unbound:x:982:981:Unbound DNS resolver:/etc/unbound:/sbin/nologin
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
colord:x:981:979:User for colord:/var/lib/colord:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
flatpak:x:980:978:User for flatpak system helper:/:/sbin/nologin
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
gnome-initial-setup:x:979:977::/run/gnome-initial-setup/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
vboxadd:x:978:1::/var/run/vboxadd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
clevis:x:977:975:Clevis Decryption Framework unprivileged user:/var/cache/clevis:/sbin/nologin
cockpit-ws:x:976:974:User for cockpit-ws:/nonexisting:/sbin/nologin
libvirtdbus:x:975:973:Libvirt D-Bus bridge:/:/sbin/nologin
setroubleshoot:x:974:972::/var/lib/setroubleshoot:/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/sbin/nologin
firebird:x:973:971::/:/bin/nologin
cockpit-wsinstance:x:972:970:User for cockpit-ws instances:/nonexisting:/sbin/nologin
pbuilder:x:971:969:pbuilder:/var/run/pbuilder:/sbin/nologin
test:x:1001:1015:Long,007,1499990,1999201,AKK:/home/test:/bin/bash
teste:x:1002:1002::/home/teste:/bin/bash
bergfried:x:1009:1009:Bergfried Freiberg,,,,:/home/bergfried:/bin/bash
akmods:x:970:966:User is used by akmods to build akmod packages:/var/cache/akmods/:/sbin/nologin
Debian-exim:x:123:128::/var/spool/exim4:/usr/sbin/nologin
+60
View File
@@ -0,0 +1,60 @@
root:$6$I4MRB1rzlIft7qiw$2i0OBungWyGBxXbcxbHNKfeaXKRQBEksxK8o3Zvb8VQKuDOSCaLjh1p6C1yfY.z/BCX0dzozj6l3F67QW1X8b.:18260:0:99999:7:::
bin:*:17995:0:99999:7:::
daemon:*:17995:0:99999:7:::
adm:*:17995:0:99999:7:::
lp:*:17995:0:99999:7:::
sync:*:17995:0:99999:7:::
shutdown:*:17995:0:99999:7:::
halt:*:17995:0:99999:7:::
mail:*:17995:0:99999:7:::
operator:*:17995:0:99999:7:::
games:*:17995:0:99999:7:::
ftp:*:17995:0:99999:7:::
nobody:*:17995:0:99999:7:::
systemd-coredump:!!:18107::::::
systemd-network:!!:18107::::::
systemd-resolve:!!:18107::::::
dbus:!!:18107::::::
systemd-timesync:!!:18107::::::
tss:!!:18107::::::
gluster:!!:18107::::::
qemu:!!:18107::::::
nm-openconnect:!!:18107::::::
usbmuxd:!!:18107::::::
geoclue:!!:18107::::::
polkitd:!!:18107::::::
rtkit:!!:18107::::::
pulse:!!:18107::::::
chrony:!!:18107::::::
avahi:!!:18107::::::
pipewire:!!:18107::::::
dnsmasq:!!:18107::::::
saslauth:!!:18107::::::
radvd:!!:18107::::::
rpc:!!:18107:0:99999:7:::
openvpn:!!:18107::::::
nm-openvpn:!!:18107::::::
unbound:!!:18107::::::
apache:!!:18107::::::
colord:!!:18107::::::
rpcuser:!!:18107::::::
abrt:!!:18107::::::
flatpak:!!:18107::::::
gdm:!!:18107::::::
gnome-initial-setup:!!:18107::::::
sshd:!!:18107::::::
vboxadd:!!:18107::::::
tcpdump:!!:18107::::::
clevis:!!:18113::::::
cockpit-ws:!!:18113::::::
libvirtdbus:!!:18113::::::
setroubleshoot:!!:18113::::::
mysql:!!:18137::::::
firebird:!!:18140::::::
cockpit-wsinstance:!!:18196::::::
pbuilder:!!:18198::::::
test:$6$K3iBIIJwfJjolbIV$AaDjW1kvaeYl8KAqAkvXMTWloQV2VsB8a33PHYItRPdETtYGKP2T2n6HjUUuXUZFPxLdnJyB8cWlpPCl1x/VP0:18574:0:99999:7:::
teste:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18574:0:99999:7:::
bergfried:$6$dzc1lAZo7XaWwFx9$MpUJtzD9WFJhgt.5zVtgP6mGjFldNCZ02Pp9S9Y4XTV16fMUuN/0vi5Xs4BH2T0G6EL2gS/gAHRnsyvY4aVi31:18574:0:99999:7:::
akmods:!!:18395::::::
Debian-exim:!:18574:0:99999:7:::
+49
View File
@@ -0,0 +1,49 @@
use std::{env, path::Path};
use std::{fs, path::PathBuf};
use tempfile::TempDir;
use std::ops::Deref;
#[derive(Debug)]
pub struct Fixture {
pub path: PathBuf,
pub source: PathBuf,
_tempdir: TempDir,
}
impl Fixture {
#[must_use]
pub fn blank(fixture_filename: &str) -> Self {
// First, figure out the right file in `tests/fixtures/`:
let root_dir = &env::var("CARGO_MANIFEST_DIR").expect("$CARGO_MANIFEST_DIR");
let mut source = PathBuf::from(root_dir);
source.push("tests/fixtures");
source.push(&fixture_filename);
// The "real" path of the file is going to be under a temporary directory:
let tempdir = tempfile::tempdir().unwrap();
let mut path = PathBuf::from(&tempdir.path());
path.push(&fixture_filename);
Self {
_tempdir: tempdir,
source,
path,
}
}
#[must_use]
pub fn copy(fixture_filename: &str) -> Self {
let fixture = Self::blank(fixture_filename);
fs::copy(&fixture.source, &fixture.path).unwrap();
fixture
}
}
impl Deref for Fixture {
type Target = Path;
fn deref(&self) -> &Self::Target {
&self.path
}
}