daemonize-0.4.1/.gitignore010064400007650000024000000000221344636106500137000ustar0000000000000000target Cargo.lock daemonize-0.4.1/.travis.yml010064400007650000024000000033171344636106500140330ustar0000000000000000sudo: required language: rust # necessary for `travis-cargo coveralls --no-sudo` addons: apt: packages: - libcurl4-openssl-dev - libelf-dev - libdw-dev - binutils-dev # optional: only required for the --verify flag of coveralls # run builds for all the trains (and more) rust: - nightly - beta # check it compiles on the latest stable compiler - stable # load travis-cargo before_script: - | sudo pip install 'travis-cargo<0.2' # the main build script: - | travis-cargo build && travis-cargo test && travis-cargo --only stable doc after_success: # upload the documentation from the build with stable (automatically only actually # runs on the master branch, not individual PRs) - travis-cargo --only stable doc-upload - travis-cargo coveralls --no-sudo --verify env: global: - TRAVIS_CARGO_NIGHTLY_FEATURE="" # encrypted github token for doc upload (see `GH_TOKEN` link above) - secure: "KiqojVvSvs6KXQ9PEC2O1X6ExR89Ms+V+W9EzL5bdkfgAREDbzt5fCzS297gLZAWe6SAeRmYMeiCyU2XPp3tVn5udwaBbi2N69VGFTxwhR41j/uIEniu2GJAdPvsdRVCOosdQzpOdxHwE1NV5iTZiBHN2fx+qOHxVitCI4PhkxPJOuF+bHbDJaYP7VsIj/KzmWGyH2R9lX0MIerqCwhlLS1Qd0poxZgDypbFPyZ+y05TZqLkxMWBPsfiIUVA8VY+1BK/0Z19vaJ4Ng3M4/yT1mawlGn2AbfbvACqfZgkb5e8ei+32IGAVMpyaooU4kyqWJ60JoBnCdZ69McJU3Q+Yrszx7tTbCM56FY3eZ4W+/AH6H6E5owbRM05lc9CdfrpF2lJ0fB+rerIpuVVAf+RKvOhll8K38T9AF9D7a+2z8tt2WO3D8Ynyf+S9zmIvLc6iX5Xdx0Ptn9ivD5q50sqLGiMsR7gqMToVdKjBbWqcymCb8zRW4bX6GP3n5BAIAnBbvMAOCDgEzD5aRzDlRIE4KlCAto02Nuy7dvMYv47eRTYr9ljiy+2bpayGVi0hxxUf1zkHZZQYgLQkSNuiZcSptEVRWaZgLY0TNeotbylmA5yxliXwLfDMcb6B6XhYNgp64wYTRVabZuxzBM/L3c+IdqjtqoyuziMonLnqHQmZmk=" notifications: webhooks: - http://heimdallr.thesharp.org/travis daemonize-0.4.1/Cargo.toml.orig010064400007650000024000000007451344670453700146200ustar0000000000000000[package] name = "daemonize" version = "0.4.1" license = "MIT/Apache-2.0" authors = ["Fedor Gogolev "] repository = "https://github.com/knsd/daemonize" documentation = "https://docs.rs/daemonize" readme = "README.md" description = "Library to enable your code run as a daemon process on Unix-like systems." keywords = ["daemon", "daemonize", "unix"] categories = ["os::unix-apis"] [dependencies] boxfnonce = "0.1.1" libc = "0.2.4" [dev-dependencies] tempdir = "0.3.4" daemonize-0.4.1/Cargo.toml0000644000000020270000000000000110470ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "daemonize" version = "0.4.1" authors = ["Fedor Gogolev "] description = "Library to enable your code run as a daemon process on Unix-like systems." documentation = "https://docs.rs/daemonize" readme = "README.md" keywords = ["daemon", "daemonize", "unix"] categories = ["os::unix-apis"] license = "MIT/Apache-2.0" repository = "https://github.com/knsd/daemonize" [dependencies.boxfnonce] version = "0.1.1" [dependencies.libc] version = "0.2.4" [dev-dependencies.tempdir] version = "0.3.4" daemonize-0.4.1/CHANGELOG.md010064400007650000024000000033501344670461300135300ustar0000000000000000daemonize changelog =================== Here you can see the full list of changes between each daemonize release. Version 0.4.1 ------------- Released on March 27, 2019 * Fix armv7 build, #34 Version 0.4.0 ------------- Released on March 26, 2019 * Allow an action by the master process right before exit, #33 * Make privileged action and exit action a FnOnce, #27 Version 0.3.0 ------------- Released on April 07, 2018 * Don't clobber pidfile of already-running daemon, #21 * Add ability to `chroot(2)` as part of the daemon process, #22 * Replace platform-dependent errno with std function, #23 * Redirect standard streams to defined files, #1 Version 0.2.3 ------------- Released on August 29, 2016 * Add support for setting a different umask Version 0.2.2 ------------- Released on March 20, 2016 * Fixed memory unsafety in CStrings routine * Show the actual error on failing to open /dev/null Version 0.2.1 ------------- Released on January 19, 2016 * Remove quick-error dependency Version 0.2.0 ------------- Released on January 17, 2016 * Add __Nonexhaustive DaemonizeError variant Version 0.1.2 ------------- Released on January 10, 2016 * FreeBSD support. Version 0.1.1 ------------- Released on January 10, 2016 * Relicense under dual MIT/Apache-2.0. Version 0.1.0 ------------- Released on December 25, 2015 * Remove `From<&String>` implementation for `User` and `Group`. * Use `umask` from `libc`. Version 0.0.3 ------------- Released on December 21, 2015 * Add `Errno` type. * Derive some standard traits for types. Version 0.0.2 ------------- Released on December 21, 2015 * Add cargo keywords. Version 0.0.1 ------------- Released on December 21, 2015 * Initial release. daemonize-0.4.1/examples/complex.rs010064400007650000024000000016501344647436000155560ustar0000000000000000extern crate daemonize; use std::fs::File; use daemonize::Daemonize; fn main() { let stdout = File::create("/tmp/daemon.out").unwrap(); let stderr = File::create("/tmp/daemon.err").unwrap(); let daemonize = Daemonize::new() .pid_file("/tmp/test.pid") // Every method except `new` and `start` .chown_pid_file(true) // is optional, see `Daemonize` documentation .working_directory("/tmp") // for default behaviour. .user("nobody") .group("daemon") // Group name .group(2) // or group id. .umask(0o777) // Set umask, `0o027` by default. .stdout(stdout) // Redirect stdout to `/tmp/daemon.out`. .stderr(stderr) // Redirect stderr to `/tmp/daemon.err`. .privileged_action(|| "Executed before drop privileges"); match daemonize.start() { Ok(_) => println!("Success, daemonized"), Err(e) => eprintln!("Error, {}", e), } } daemonize-0.4.1/examples/test_chdir.rs010064400007650000024000000007061344647436000162400ustar0000000000000000extern crate daemonize; use std::io::prelude::*; use daemonize::Daemonize; fn main() { let args = std::env::args().collect::>(); let chdir = &args[1]; let file = &args[2]; let umask = args[3].parse().unwrap(); Daemonize::new() .working_directory(chdir) .umask(umask) .start() .unwrap(); std::fs::File::create(file) .unwrap() .write_all(b"test") .unwrap(); } daemonize-0.4.1/examples/test_chown_pid.rs010064400007650000024000000005131344647436000171150ustar0000000000000000extern crate daemonize; use daemonize::Daemonize; fn main() { let args = std::env::args().collect::>(); let user = &(*args[1]); let group = &(*args[2]); let pid = &(*args[3]); Daemonize::new() .pid_file(pid) .user(user) .group(group) .start() .unwrap(); } daemonize-0.4.1/examples/test_chroot.rs010064400007650000024000000007571344647370700164570ustar0000000000000000extern crate daemonize; use std::io::prelude::*; use daemonize::Daemonize; fn main() { let args = std::env::args().collect::>(); let chroot = &args[1]; let file = &args[2]; let umask = args[3].parse().unwrap(); Daemonize::new() .chroot(chroot) .umask(umask) .user("daemon") .group("daemon") .start() .unwrap(); std::fs::File::create(file) .unwrap() .write_all(b"test") .unwrap(); } daemonize-0.4.1/examples/test_double_run.rs010064400007650000024000000010131344647436000172750ustar0000000000000000extern crate daemonize; use daemonize::Daemonize; use std::io::prelude::*; fn main() { let args = std::env::args().collect::>(); let pid = &args[1]; let result_file = &args[2]; let mut file = std::fs::File::create(result_file).unwrap(); match Daemonize::new().pid_file(pid).start() { Ok(()) => { file.write_all(b"ok").unwrap(); std::thread::sleep(std::time::Duration::from_secs(10)); } Err(_) => file.write_all(b"error").unwrap(), }; } daemonize-0.4.1/examples/test_pid.rs010064400007650000024000000003121344647436000157140ustar0000000000000000extern crate daemonize; use daemonize::Daemonize; fn main() { let args = std::env::args().collect::>(); let pid = &args[1]; Daemonize::new().pid_file(pid).start().unwrap(); } daemonize-0.4.1/examples/test_redirect_streams.rs010064400007650000024000000007641344647436000205120ustar0000000000000000extern crate daemonize; use daemonize::Daemonize; fn main() { let args = std::env::args().collect::>(); let stdout = &args[1]; let stderr = &args[2]; let stdout = std::fs::File::create(stdout).unwrap(); let stderr = std::fs::File::create(stderr).unwrap(); Daemonize::new() .stdout(stdout) .stderr(stderr) .start() .unwrap(); println!("stdout"); println!("newline"); eprintln!("stderr"); eprintln!("newline"); } daemonize-0.4.1/examples/test_uid_gid.rs010064400007650000024000000007621344647436000165550ustar0000000000000000extern crate daemonize; extern crate libc; use std::io::prelude::*; use daemonize::Daemonize; fn main() { let args = std::env::args().collect::>(); let user = &(*args[1]); let group = &(*args[2]); let file = &args[3]; let mut file = std::fs::File::create(file).unwrap(); Daemonize::new().user(user).group(group).start().unwrap(); unsafe { file.write_all(format!("{} {}", libc::getuid(), libc::getgid()).as_bytes()) .unwrap(); } } daemonize-0.4.1/LICENSE-APACHE010064400007650000024000000261201344636106500136430ustar0000000000000000 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 2016 Fedor Gogolev 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. daemonize-0.4.1/LICENSE-MIT010064400007650000024000000020411344636106500133470ustar0000000000000000Copyright (c) 2016 Fedor Gogolev 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. daemonize-0.4.1/README.md010064400007650000024000000035471344636106500132060ustar0000000000000000daemonize [![Build Status](https://travis-ci.org/knsd/daemonize.svg?branch=master)](https://travis-ci.org/knsd/daemonize) [![Latest Version](https://img.shields.io/crates/v/daemonize.svg)](https://crates.io/crates/daemonize/) [![docs](https://docs.rs/daemonize/badge.svg)](https://docs.rs/daemonize) ========= daemonize is a library for writing system daemons. Inspired by the Python library [thesharp/daemonize](https://github.com/thesharp/daemonize). Usage example: ```rust extern crate daemonize; use std::fs::File; use daemonize::Daemonize; fn main() { let stdout = File::create("/tmp/daemon.out").unwrap(); let stderr = File::create("/tmp/daemon.err").unwrap(); let daemonize = Daemonize::new() .pid_file("/tmp/test.pid") // Every method except `new` and `start` .chown_pid_file(true) // is optional, see `Daemonize` documentation .working_directory("/tmp") // for default behaviour. .user("nobody") .group("daemon") // Group name .group(2) // or group id. .umask(0o777) // Set umask, `0o027` by default. .stdout(stdout) // Redirect stdout to `/tmp/daemon.out`. .stderr(stderr) // Redirect stderr to `/tmp/daemon.err`. .privileged_action(|| "Executed before drop privileges"); match daemonize.start() { Ok(_) => println!("Success, daemonized"), Err(e) => eprintln!("Error, {}", e), } } ``` ### License Licensed under either of * Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions. daemonize-0.4.1/src/ffi.rs010064400007650000024000000053561344647436000136330ustar0000000000000000// Copyright (c) 2016 Fedor Gogolev // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate libc; use std::ffi::CString; #[repr(C)] #[allow(dead_code)] struct passwd { pw_name: *const libc::c_char, pw_passwd: *const libc::c_char, pw_uid: libc::uid_t, pw_gid: libc::gid_t, pw_gecos: *const libc::c_char, pw_dir: *const libc::c_char, pw_shell: *const libc::c_char, } #[repr(C)] #[allow(dead_code)] struct group { gr_name: *const libc::c_char, gr_passwd: *const libc::c_char, gr_gid: libc::gid_t, gr_mem: *const *const libc::c_char, } extern "C" { fn getgrnam(name: *const libc::c_char) -> *const group; fn getpwnam(name: *const libc::c_char) -> *const passwd; pub fn flock(fd: libc::c_int, operation: libc::c_int) -> libc::c_int; pub fn chroot(fd: *const libc::c_char) -> libc::c_int; } pub unsafe fn get_gid_by_name(name: &CString) -> Option { let ptr = getgrnam(name.as_ptr() as *const libc::c_char); if ptr.is_null() { None } else { let s = &*ptr; Some(s.gr_gid) } } pub unsafe fn get_uid_by_name(name: &CString) -> Option { let ptr = getpwnam(name.as_ptr() as *const libc::c_char); if ptr.is_null() { None } else { let s = &*ptr; Some(s.pw_uid) } } #[cfg(test)] mod tests { use libc; use super::{get_gid_by_name, get_uid_by_name}; #[cfg(any(target_os = "linux", target_os = "freebsd"))] unsafe fn nobody_uid_gid() -> libc::uid_t { (u16::max_value() - 1) as libc::uid_t } #[cfg(any(target_os = "macos", target_os = "ios"))] unsafe fn nobody_uid_gid() -> libc::uid_t { (u32::max_value() - 1) as libc::uid_t } #[cfg(target_os = "openbsd")] unsafe fn nobody_uid_gid() -> libc::uid_t { (i16::max_value()) as libc::uid_t } #[test] fn test_get_gid_by_name() { let group_name = ::std::ffi::CString::new(match ::std::fs::metadata("/etc/debian_version") { Ok(_) => "nogroup", Err(_) => "nobody", }) .unwrap(); unsafe { let gid = get_gid_by_name(&group_name); assert_eq!(gid, Some(nobody_uid_gid())) } } #[test] fn test_get_uid_by_name() { let user_name = ::std::ffi::CString::new("nobody").unwrap(); unsafe { let uid = get_uid_by_name(&user_name); assert_eq!(uid, Some(nobody_uid_gid())) } } } daemonize-0.4.1/src/lib.rs010064400007650000024000000417301344670422600136260ustar0000000000000000// Copyright (c) 2016 Fedor Gogolev // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! //! daemonize is a library for writing system daemons. Inspired by the Python library [thesharp/daemonize](https://github.com/thesharp/daemonize). //! //! The respository is located at https://github.com/knsd/daemonize/. //! //! Usage example: //! //! ``` //! extern crate daemonize; //! //! use std::fs::File; //! //! use daemonize::Daemonize; //! //! fn main() { //! let stdout = File::create("/tmp/daemon.out").unwrap(); //! let stderr = File::create("/tmp/daemon.err").unwrap(); //! //! let daemonize = Daemonize::new() //! .pid_file("/tmp/test.pid") // Every method except `new` and `start` //! .chown_pid_file(true) // is optional, see `Daemonize` documentation //! .working_directory("/tmp") // for default behaviour. //! .user("nobody") //! .group("daemon") // Group name //! .group(2) // or group id. //! .umask(0o777) // Set umask, `0o027` by default. //! .stdout(stdout) // Redirect stdout to `/tmp/daemon.out`. //! .stderr(stderr) // Redirect stderr to `/tmp/daemon.err`. //! .exit_action(|| println!("Executed before master process exits")) //! .privileged_action(|| "Executed before drop privileges"); //! //! match daemonize.start() { //! Ok(_) => println!("Success, daemonized"), //! Err(e) => eprintln!("Error, {}", e), //! } //! } //! ``` mod ffi; extern crate boxfnonce; extern crate libc; use std::env::set_current_dir; use std::ffi::CString; use std::fmt; use std::fs::File; use std::io; use std::mem::transmute; use std::os::unix::ffi::OsStringExt; use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use std::process::exit; use boxfnonce::BoxFnOnce; use libc::{ c_int, close, dup2, fork, ftruncate, getpid, open, setgid, setsid, setuid, umask, write, LOCK_EX, LOCK_NB, }; pub use libc::{gid_t, mode_t, uid_t}; use self::ffi::{chroot, flock, get_gid_by_name, get_uid_by_name}; macro_rules! tryret { ($expr:expr, $ret:expr, $err:expr) => { if $expr == -1 { return Err($err(errno())); } else { #[allow(clippy::unused_unit)] { $ret } } }; } pub type Errno = c_int; /// This error type for `Daemonize` `start` method. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub enum DaemonizeError { /// Unable to fork Fork, /// Unable to create new session DetachSession(Errno), /// Unable to resolve group name to group id GroupNotFound, /// Group option contains NUL GroupContainsNul, /// Unable to set group SetGroup(Errno), /// Unable to resolve user name to user id UserNotFound, /// User option contains NUL UserContainsNul, /// Unable to set user SetUser(Errno), /// Unable to change directory ChangeDirectory, /// pid_file option contains NUL PathContainsNul, /// Unable to open pid file OpenPidfile, /// Unable to lock pid file LockPidfile(Errno), /// Unable to chown pid file ChownPidfile(Errno), /// Unable to redirect standard streams to /dev/null RedirectStreams(Errno), /// Unable to write self pid to pid file WritePid, /// Unable to chroot Chroot(Errno), // Hints that destructuring should not be exhaustive. // This enum may grow additional variants, so this makes sure clients // don't count on exhaustive matching. Otherwise, adding a new variant // could break existing code. #[doc(hidden)] __Nonexhaustive, } impl DaemonizeError { fn __description(&self) -> &str { match *self { DaemonizeError::Fork => "unable to fork", DaemonizeError::DetachSession(_) => "unable to create new session", DaemonizeError::GroupNotFound => "unable to resolve group name to group id", DaemonizeError::GroupContainsNul => "group option contains NUL", DaemonizeError::SetGroup(_) => "unable to set group", DaemonizeError::UserNotFound => "unable to resolve user name to user id", DaemonizeError::UserContainsNul => "user option contains NUL", DaemonizeError::SetUser(_) => "unable to set user", DaemonizeError::ChangeDirectory => "unable to change directory", DaemonizeError::PathContainsNul => "pid_file option contains NUL", DaemonizeError::OpenPidfile => "unable to open pid file", DaemonizeError::LockPidfile(_) => "unable to lock pid file", DaemonizeError::ChownPidfile(_) => "unable to chown pid file", DaemonizeError::RedirectStreams(_) => { "unable to redirect standard streams to /dev/null" } DaemonizeError::WritePid => "unable to write self pid to pid file", DaemonizeError::Chroot(_) => "unable to chroot into directory", DaemonizeError::__Nonexhaustive => unreachable!(), } } } impl std::fmt::Display for DaemonizeError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.__description().fmt(f) } } impl std::error::Error for DaemonizeError { fn description(&self) -> &str { self.__description() } } type Result = std::result::Result; /// Expects system user id or name. If name is provided it will be resolved to id later. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub enum User { Name(String), Id(uid_t), } impl<'a> From<&'a str> for User { fn from(t: &'a str) -> User { User::Name(t.to_owned()) } } impl From for User { fn from(t: uid_t) -> User { User::Id(t) } } /// Expects system group id or name. If name is provided it will be resolved to id later. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] pub enum Group { Name(String), Id(gid_t), } impl<'a> From<&'a str> for Group { fn from(t: &'a str) -> Group { Group::Name(t.to_owned()) } } impl From for Group { fn from(t: gid_t) -> Group { Group::Id(t) } } #[derive(Debug)] enum StdioImp { Devnull, RedirectToFile(File), } /// Describes what to do with a standard I/O stream for a child process. #[derive(Debug)] pub struct Stdio { inner: StdioImp, } impl Stdio { fn devnull() -> Self { Self { inner: StdioImp::Devnull, } } } impl From for Stdio { fn from(file: File) -> Self { Self { inner: StdioImp::RedirectToFile(file), } } } /// Daemonization options. /// /// Fork the process in the background, disassociate from its process group and the control terminal. /// Change umask value to `0o027`, redirect all standard streams to `/dev/null`. Change working /// directory to `/` or provided value. /// /// Optionally: /// /// * maintain and lock the pid-file; /// * drop user privileges; /// * drop group privileges; /// * change root directory; /// * change the pid-file ownership to provided user (and/or) group; /// * execute any provided action just before dropping privileges. /// pub struct Daemonize { directory: PathBuf, pid_file: Option, chown_pid_file: bool, user: Option, group: Option, umask: mode_t, root: Option, privileged_action: BoxFnOnce<'static, (), T>, exit_action: BoxFnOnce<'static, (), ()>, stdin: Stdio, stdout: Stdio, stderr: Stdio, } impl fmt::Debug for Daemonize { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("Daemonize") .field("directory", &self.directory) .field("pid_file", &self.pid_file) .field("chown_pid_file", &self.chown_pid_file) .field("user", &self.user) .field("group", &self.group) .field("umask", &self.umask) .field("root", &self.root) .field("stdin", &self.stdin) .field("stdout", &self.stdout) .field("stderr", &self.stderr) .finish() } } impl Daemonize<()> { #[allow(clippy::new_without_default)] pub fn new() -> Self { Daemonize { directory: Path::new("/").to_owned(), pid_file: None, chown_pid_file: false, user: None, group: None, umask: 0o027, privileged_action: BoxFnOnce::new(|| ()), exit_action: BoxFnOnce::new(|| ()), root: None, stdin: Stdio::devnull(), stdout: Stdio::devnull(), stderr: Stdio::devnull(), } } } impl Daemonize { /// Create pid-file at `path`, lock it exclusive and write daemon pid. pub fn pid_file>(mut self, path: F) -> Self { self.pid_file = Some(path.as_ref().to_owned()); self } /// If `chown` is true, daemonize will change the pid-file ownership, if user or group are provided pub fn chown_pid_file(mut self, chown: bool) -> Self { self.chown_pid_file = chown; self } /// Change working directory to `path` or `/` by default. pub fn working_directory>(mut self, path: F) -> Self { self.directory = path.as_ref().to_owned(); self } /// Drop privileges to `user`. pub fn user>(mut self, user: U) -> Self { self.user = Some(user.into()); self } /// Drop privileges to `group`. pub fn group>(mut self, group: G) -> Self { self.group = Some(group.into()); self } /// Change umask to `mask` or `0o027` by default. pub fn umask(mut self, mask: mode_t) -> Self { self.umask = mask; self } /// Change root to `path` pub fn chroot>(mut self, path: F) -> Self { self.root = Some(path.as_ref().to_owned()); self } /// Execute `action` just before dropping privileges. Most common usecase is to open listening socket. /// Result of `action` execution will be returned by `start` method. pub fn privileged_action N + 'static>(self, action: F) -> Daemonize { let mut new: Daemonize = unsafe { transmute(self) }; new.privileged_action = BoxFnOnce::new(action); new } /// Execute `action` just before exiting the parent process. Most common usecase is to synchronize with /// forked processes. pub fn exit_action(mut self, action: F) -> Daemonize { self.exit_action = BoxFnOnce::new(action); self } /// Configuration for the child process's standard output stream. pub fn stdout>(mut self, stdio: S) -> Self { self.stdout = stdio.into(); self } /// Configuration for the child process's standard error stream. pub fn stderr>(mut self, stdio: S) -> Self { self.stderr = stdio.into(); self } /// Start daemonization process. pub fn start(self) -> std::result::Result { // Maps an Option to Option by applying a function Fn(T) -> Result // to a contained value and try! it's result macro_rules! maptry { ($expr:expr, $f: expr) => { match $expr { None => None, Some(x) => Some(try!($f(x))), }; }; } unsafe { let pid_file_fd = maptry!(self.pid_file.clone(), create_pid_file); perform_fork(Some(self.exit_action))?; set_current_dir(&self.directory).map_err(|_| DaemonizeError::ChangeDirectory)?; set_sid()?; umask(self.umask); perform_fork(None)?; redirect_standard_streams(self.stdin, self.stdout, self.stderr)?; let uid = maptry!(self.user, get_user); let gid = maptry!(self.group, get_group); if self.chown_pid_file { let args: Option<(PathBuf, uid_t, gid_t)> = match (self.pid_file, uid, gid) { (Some(pid), Some(uid), Some(gid)) => Some((pid, uid, gid)), (Some(pid), None, Some(gid)) => Some((pid, uid_t::max_value() - 1, gid)), (Some(pid), Some(uid), None) => Some((pid, uid, gid_t::max_value() - 1)), // Or pid file is not provided, or both user and group _ => None, }; maptry!(args, |(pid, uid, gid)| chown_pid_file(pid, uid, gid)); } let privileged_action_result = self.privileged_action.call(); maptry!(self.root, change_root); maptry!(gid, set_group); maptry!(uid, set_user); maptry!(pid_file_fd, write_pid_file); Ok(privileged_action_result) } } } unsafe fn perform_fork(exit_action: Option>) -> Result<()> { let pid = fork(); if pid < 0 { Err(DaemonizeError::Fork) } else if pid == 0 { Ok(()) } else { if let Some(exit_action) = exit_action { exit_action.call() } exit(0) } } unsafe fn set_sid() -> Result<()> { tryret!(setsid(), Ok(()), DaemonizeError::DetachSession) } unsafe fn redirect_standard_streams(stdin: Stdio, stdout: Stdio, stderr: Stdio) -> Result<()> { let devnull_fd = open(b"/dev/null\0" as *const [u8; 10] as _, libc::O_RDWR); if -1 == devnull_fd { return Err(DaemonizeError::RedirectStreams(errno())); } let process_stdio = |fd, stdio: Stdio| { tryret!(close(fd), (), DaemonizeError::RedirectStreams); match stdio.inner { StdioImp::Devnull => { tryret!(dup2(devnull_fd, fd), (), DaemonizeError::RedirectStreams); } StdioImp::RedirectToFile(file) => { let raw_fd = file.as_raw_fd(); tryret!(dup2(raw_fd, fd), (), DaemonizeError::RedirectStreams); } }; Ok(()) }; process_stdio(libc::STDIN_FILENO, stdin)?; process_stdio(libc::STDOUT_FILENO, stdout)?; process_stdio(libc::STDERR_FILENO, stderr)?; tryret!(close(devnull_fd), (), DaemonizeError::RedirectStreams); Ok(()) } unsafe fn get_group(group: Group) -> Result { match group { Group::Id(id) => Ok(id), Group::Name(name) => { let s = CString::new(name).map_err(|_| DaemonizeError::GroupContainsNul)?; match get_gid_by_name(&s) { Some(id) => get_group(Group::Id(id)), None => Err(DaemonizeError::GroupNotFound), } } } } unsafe fn set_group(group: gid_t) -> Result<()> { tryret!(setgid(group), Ok(()), DaemonizeError::SetGroup) } unsafe fn get_user(user: User) -> Result { match user { User::Id(id) => Ok(id), User::Name(name) => { let s = CString::new(name).map_err(|_| DaemonizeError::UserContainsNul)?; match get_uid_by_name(&s) { Some(id) => get_user(User::Id(id)), None => Err(DaemonizeError::UserNotFound), } } } } unsafe fn set_user(user: uid_t) -> Result<()> { tryret!(setuid(user), Ok(()), DaemonizeError::SetUser) } unsafe fn create_pid_file(path: PathBuf) -> Result { let path_c = pathbuf_into_cstring(path)?; let fd = open(path_c.as_ptr(), libc::O_WRONLY | libc::O_CREAT, 0o666); if -1 == fd { return Err(DaemonizeError::OpenPidfile); } tryret!( flock(fd, LOCK_EX | LOCK_NB), Ok(fd), DaemonizeError::LockPidfile ) } unsafe fn chown_pid_file(path: PathBuf, uid: uid_t, gid: gid_t) -> Result<()> { let path_c = pathbuf_into_cstring(path)?; tryret!( libc::chown(path_c.as_ptr(), uid, gid), Ok(()), DaemonizeError::ChownPidfile ) } unsafe fn write_pid_file(fd: libc::c_int) -> Result<()> { let pid = getpid(); let pid_buf = format!("{}", pid).into_bytes(); let pid_length = pid_buf.len(); let pid_c = CString::new(pid_buf).unwrap(); if -1 == ftruncate(fd, 0) { return Err(DaemonizeError::WritePid); } if write(fd, pid_c.as_ptr() as *const libc::c_void, pid_length) < pid_length as isize { Err(DaemonizeError::WritePid) } else { Ok(()) } } unsafe fn change_root(path: PathBuf) -> Result<()> { let path_c = pathbuf_into_cstring(path)?; if chroot(path_c.as_ptr()) == 0 { Ok(()) } else { Err(DaemonizeError::Chroot(errno())) } } fn pathbuf_into_cstring(path: PathBuf) -> Result { CString::new(path.into_os_string().into_vec()).map_err(|_| DaemonizeError::PathContainsNul) } fn errno() -> Errno { io::Error::last_os_error().raw_os_error().expect("errno") } daemonize-0.4.1/tests/tests.rs010064400007650000024000000073251344647436000146020ustar0000000000000000extern crate libc; extern crate tempdir; use std::ffi::OsStr; use std::io::prelude::*; use tempdir::TempDir; fn run>(cmd: S, args: &[S]) -> u32 { let mut cmd = std::process::Command::new(cmd); for arg in args { cmd.arg(arg); } let mut child = cmd.spawn().unwrap(); let pid = child.id(); child.wait().unwrap(); std::thread::sleep(std::time::Duration::from_millis(100)); pid } #[test] fn test_umask_chdir() { let tmpdir = TempDir::new("chdir").unwrap(); // third argument is the umask: 255 == 0o377 let args = vec![tmpdir.path().to_str().unwrap(), "test", "255"]; run("target/debug/examples/test_chdir", &args); let filename = tmpdir.path().join("test"); let mut data = Vec::new(); std::fs::File::open(&filename) .unwrap() .read_to_end(&mut data) .unwrap(); assert!(data == b"test"); // due to the umask, the file should have been created with -w assert!(filename.metadata().unwrap().permissions().readonly()); } #[test] fn test_pid() { let tmpdir = TempDir::new("chdir").unwrap(); let pid_file = tmpdir.path().join("pid"); let args = vec![pid_file.to_str().unwrap()]; let child_pid = run("target/debug/examples/test_pid", &args); let mut data = String::new(); std::fs::File::open(&pid_file) .unwrap() .read_to_string(&mut data) .unwrap(); let pid: u32 = data.parse().unwrap(); assert!(pid != child_pid) } #[test] fn double_run() { let tmpdir = TempDir::new("double_run").unwrap(); let pid_file = tmpdir.path().join("pid"); let first_result = tmpdir.path().join("first"); let second_result = tmpdir.path().join("second"); for file in &[&first_result, &second_result] { let args = vec![pid_file.to_str().unwrap(), file.to_str().unwrap()]; run("target/debug/examples/test_double_run", &args); } std::thread::sleep(std::time::Duration::from_millis(100)); { let mut data = String::new(); std::fs::File::open(&first_result) .unwrap() .read_to_string(&mut data) .unwrap(); assert!(data == "ok") } { let mut data = String::new(); std::fs::File::open(&second_result) .unwrap() .read_to_string(&mut data) .unwrap(); assert!(data == "error") } } #[test] #[cfg(target_os = "macos")] fn test_uid_gid() { let tmpdir = TempDir::new("uid_gid").unwrap(); let result_file = tmpdir.path().join("result"); let args = vec!["nobody", "daemon", &result_file.to_str().unwrap()]; run("target/debug/examples/test_uid_gid", &args); let own_uid_gid_string = unsafe { format!("{} {}", libc::getuid(), libc::getgid()) }; let mut data = String::new(); std::fs::File::open(&result_file) .unwrap() .read_to_string(&mut data) .unwrap(); assert!(!data.is_empty()); assert!(data != own_uid_gid_string) } #[test] fn test_redirect_streams() { let tmpdir = TempDir::new("redirect").unwrap(); let stdout_file = tmpdir.path().join("stdout"); let stderr_file = tmpdir.path().join("stderr"); let args = vec![stdout_file.to_str().unwrap(), stderr_file.to_str().unwrap()]; run("target/debug/examples/test_redirect_streams", &args); std::thread::sleep(std::time::Duration::from_millis(100)); let mut stdout = String::new(); std::fs::File::open(&stdout_file) .unwrap() .read_to_string(&mut stdout) .unwrap(); let mut stderr = String::new(); std::fs::File::open(&stderr_file) .unwrap() .read_to_string(&mut stderr) .unwrap(); assert_eq!(stdout, "stdout\nnewline\n"); assert_eq!(stderr, "stderr\nnewline\n"); } daemonize-0.4.1/.cargo_vcs_info.json0000644000000001120000000000000130420ustar00{ "git": { "sha1": "b59073bf3e51870a6a8bb44f954faa1b38b20d2d" } }