libmount-0.1.15/.gitignore010066400037200003720000000000401356324602500136400ustar0000000000000000/target Cargo.lock /.vagga /tmp libmount-0.1.15/.travis.yml010066400037200003720000000036411356324602500137730ustar0000000000000000language: rust rust: stable os: linux dist: trusty sudo: false addons: apt: packages: - fakeroot - musl-tools cache: - apt - cargo before_cache: - rm -r $TRAVIS_BUILD_DIR/target/debug script: - cargo build $CARGO_ARGS - cargo test $CARGO_ARGS jobs: include: - rust: stable - rust: beta - rust: nightly # deploy - stage: publish docs env: # GH_TOKEN - secure: "g8UoQdG0w09xquGMDmnvkCO3b4/jb00OrFvXgCrN9g8m7RrX+ZQ98Ztjjp9Dr4Sni1U3V9LrTFrEFv9+vrNJJX6TQ2rLOZOF+IvlYLFOsz6LcNHTqcnAYJoTy+VqsXTwkNs3TP9LwUnxX0X0N8GxyKAJJ0wSHZvNooDDi8x2jeGuT5AwyRd3S9zoBi4nlQdwU20NErH0i50ayEKE1SLQJcG3Xtl6OtHGqxHWgOPXNQwqY/042NOnMFiL40lvh3iS2xtM2sDwRdfWj+pmvji2FRMHlkC+g5JwC50KkeCL+VBrT8MZbUW8UWjDC9J1tV7zfA8HY0nURgYl6g2NWe0/7vTgx0oQM+9Kf0OcNWVBA2j7g8MVJA9/1JW6B11a7oFgRDmJLGGrqaIAndrviho/V1OQtB4l0h1ZF6iUVZwuRHdCd6wxY4ahCQHjnsGUxnzYAgU2e/7IL/gKXjYhUdly99Ah018XXZ2MqAXISoh3fpKJg52pKcfjnJr3bDs6mpBHVdHH/zfk3jWtmvcozPubRSXsjnLFeBnAGdLz8pWHq9tzRTIQoV1RDNo4a73ck9diti52HhKfWFGojmrAXABWwkJ7wor0F3/uxHhbTpuHf+AFO8tgPyEamLFWL7WCbxFLXI7SSuewdCgEEV0Kz2Xrj0/prywHmaREUgblwyk8wpc=" # CARGO_TOKEN - secure: "AatVkDxYdzu8K1Qa6xlwVbfXu1YfuxfKd+jZoCFzKq1tP3OLtAbWsoZsiyGcgfDk3gq3oXHFbgjXObM/N6wA4U94mvZMralHkWc7eoECrfGjPz0ei8EOXzgFlWtE3keKBMvrCzIOUNt6+y20NsFgxfv9tSLWN7gRRWl8T+RQ6aO5p5kuI7mmN+e5y7QdtIEODeqRnpBl4wbG/BltJG0YrBoxt/R42inIHw0gUYZzAk8Xypjczb9aGdSwZmXxMw78n9Km4e+Z5/enUxam+qr/Rf4vBoBDpq3l7GIgl6ZHBHWAcKb9r8Vj1OJdwN0Bf4q13LRJNYISLCya0XYUZl0A4/2TOGBkO+RpPON8OoYTZcGSJ8O/5z9tuViSKoogmJipm8KTPh/u3yi4qdkt2hSdkn8OEpvDV53CCm9lQVTglE14uQCnrUYefXtrp3JPSIYb+TTqJW13p5LV/vr/lHDXk2oqU1eSL3b+se1kOogsVQOS+WDo5lvhDN6PbkU7+iLeYkFe7wVcDfZV/nf4QV4ZfMpgtXHPdy+PbhITnOZKuGA52ZTqi+tDn3RxHY0sGZFXLRpVZB2o73jJAc6t/uWlrEUQw1T2CJA3ohxfFlrF8WTItCAYT/pIR7Rr4qxloLkvVcWB5L3WsudZyJpUNrl3ch67yydpzSzr4xiv2X6u0Bo=" install: true deploy: - provider: script script: 'cargo publish --verbose --token=$CARGO_TOKEN' on: tags: true libmount-0.1.15/Cargo.toml.orig010066400037200003720000000010441356324602500145440ustar0000000000000000[package] name = "libmount" description = """ The type-safe wrapper around mount system call """ license = "MIT/Apache-2.0" readme = "README.md" keywords = ["linux", "container", "mount", "volume", "filesystem"] homepage = "http://github.com/tailhook/libmount" documentation = "http://docs.rs/libmount" version = "0.1.15" authors = ["paul@colomiets.name"] [dependencies] libc = "0.2.28" nix = "0.14" quick-error = "1.2.0" [dev-dependencies] argparse = "0.2.1" env_logger = "0.5.10" log = "0.4.1" [lib] name = "libmount" path = "src/lib.rs" libmount-0.1.15/Cargo.toml0000644000000022420000000000000110060ustar00# 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 = "libmount" version = "0.1.15" authors = ["paul@colomiets.name"] description = " The type-safe wrapper around mount system call\n" homepage = "http://github.com/tailhook/libmount" documentation = "http://docs.rs/libmount" readme = "README.md" keywords = ["linux", "container", "mount", "volume", "filesystem"] license = "MIT/Apache-2.0" [lib] name = "libmount" path = "src/lib.rs" [dependencies.libc] version = "0.2.28" [dependencies.nix] version = "0.14" [dependencies.quick-error] version = "1.2.0" [dev-dependencies.argparse] version = "0.2.1" [dev-dependencies.env_logger] version = "0.5.10" [dev-dependencies.log] version = "0.4.1" libmount-0.1.15/LICENSE-APACHE010066400037200003720000000261361356324602500136120ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. libmount-0.1.15/LICENSE-MIT010066400037200003720000000020531356324602500133120ustar0000000000000000Copyright (c) 2016 The libmount Developers 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. libmount-0.1.15/README.md010066400037200003720000000022661356324602500131430ustar0000000000000000libmount ======== [Documentation](https://docs.rs/libmount) | [Github](https://github.com/tailhook/libmount) | [Crate](https://crates.io/crates/libmount) This is a higher-level wrapper around ``mount()`` system call for linux. Goals: 1. Type-safe wrapper, including mount options 2. Support of new features such as overlayfs 3. Good support of unprivileges user namespaces 4. Very detailed error messages, which are helpful for end users Features: * [x] Bind Mounts * [x] OverlayFS * [x] Tmpfs * [ ] Pseudo file systems: `proc`, `sys` * [ ] `umount` and `umount2` * [x] Parser of `/proc/PID/mountinfo` * [x] Read-only mounts (remount) * [ ] Ext2/3/4 * [ ] Btrfs * [ ] Support of mount flags throught trait * [ ] Fuse License ======= Licensed under either of * Apache License, Version 2.0, (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) * MIT license (./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, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. libmount-0.1.15/bulk.yaml010066400037200003720000000002051356324602500134740ustar0000000000000000minimum-bulk: v0.4.5 versions: - file: Cargo.toml block-start: ^\[package\] block-end: ^\[.*\] regex: ^version\s*=\s*"(\S+)" libmount-0.1.15/examples/bind_mount.rs010066400037200003720000000024121356324602500161770ustar0000000000000000extern crate libmount; extern crate argparse; extern crate env_logger; #[macro_use] extern crate log; use std::path::PathBuf; use std::process::exit; use argparse::{ArgumentParser, Parse, StoreFalse, StoreTrue}; fn main() { env_logger::init(); let mut source = PathBuf::new(); let mut target = PathBuf::new(); let mut recursive = true; let mut readonly = false; { let mut ap = ArgumentParser::new(); ap.set_description("Bind mounting utility. Similar to `mount --bind`"); ap.refer(&mut source).add_argument("source", Parse, "Source directory for bind mount").required(); ap.refer(&mut target).add_argument("target", Parse, "Target directory for bind mount").required(); ap.refer(&mut recursive).add_option(&["--non-recursive"], StoreFalse, "Disable recursive mount (only a real superuser can do this)"); ap.refer(&mut readonly).add_option(&["--readonly"], StoreTrue, "Readonly mount"); ap.parse_args_or_exit(); } match libmount::BindMount::new(source, target) .recursive(recursive) .readonly(readonly) .mount() { Ok(()) => {} Err(e) => { error!("{}", e); exit(1); } } } libmount-0.1.15/examples/move.rs010066400037200003720000000016251356324602500150140ustar0000000000000000extern crate libmount; extern crate argparse; extern crate env_logger; #[macro_use] extern crate log; use std::path::PathBuf; use std::process::exit; use argparse::{ArgumentParser, Parse}; fn main() { env_logger::init(); let mut source = PathBuf::new(); let mut target = PathBuf::new(); { let mut ap = ArgumentParser::new(); ap.set_description("Move mountpoint utility. \ Similar to `mount --move`"); ap.refer(&mut source).add_argument("source", Parse, "Source directory for bind mount").required(); ap.refer(&mut target).add_argument("target", Parse, "Target directory for bind mount").required(); ap.parse_args_or_exit(); } match libmount::Move::new(source, target).move_mountpoint() { Ok(()) => {} Err(e) => { error!("{}", e); exit(1); } } } libmount-0.1.15/examples/overlay_readonly.rs010066400037200003720000000020211356324602500174130ustar0000000000000000extern crate libmount; extern crate argparse; extern crate env_logger; #[macro_use] extern crate log; use std::path::PathBuf; use std::process::exit; use argparse::{ArgumentParser, Parse, Collect}; fn main() { env_logger::init(); let mut lowerdirs = Vec::::new(); let mut target = PathBuf::new(); { let mut ap = ArgumentParser::new(); ap.set_description("Overlayfs mount utility. Similar to `mount -t overlay`"); ap.refer(&mut target) .add_argument("target", Parse, "The destination directory for mount").required(); ap.refer(&mut lowerdirs).add_argument("lowerdir", Collect, "The source layers of the overlay").required(); ap.parse_args_or_exit(); } match libmount::Overlay::readonly(lowerdirs.iter().map(|x| x.as_ref()), target) .mount() { Ok(()) => {} Err(e) => { error!("{}", e); exit(1); } } } libmount-0.1.15/examples/overlay_writable.rs010066400037200003720000000025671356324602500174260ustar0000000000000000extern crate libmount; extern crate argparse; extern crate env_logger; #[macro_use] extern crate log; use std::path::PathBuf; use std::process::exit; use argparse::{ArgumentParser, Parse, ParseOption, Collect}; fn main() { env_logger::init(); let mut lowerdirs = Vec::::new(); let mut target = PathBuf::new(); let mut upper = PathBuf::new(); let mut work = None::; { let mut ap = ArgumentParser::new(); ap.set_description("Overlayfs mount utility. Similar to `mount -t overlay`"); ap.refer(&mut target).add_argument("target", Parse, "The destination directory for mount").required(); ap.refer(&mut upper).add_argument("upperdir", Parse, "The upper (writable) directory").required(); ap.refer(&mut work).add_argument("workdir", ParseOption, "The workdir, must be on the same filesystem as upperdir"); ap.refer(&mut lowerdirs).add_argument("lowerdir", Collect, "The source layers of the overlay").required(); ap.parse_args_or_exit(); } match libmount::Overlay::writable( lowerdirs.iter().map(|x| x.as_ref()), &upper, work.unwrap_or(upper.join("tmp")), target) .mount() { Ok(()) => {} Err(e) => { error!("{}", e); exit(1); } } } libmount-0.1.15/examples/remount.rs010066400037200003720000000030541356324602500155350ustar0000000000000000extern crate libmount; extern crate argparse; extern crate env_logger; #[macro_use] extern crate log; use std::path::PathBuf; use std::process::exit; use argparse::{ArgumentParser, Parse, StoreTrue}; fn main() { env_logger::init(); let mut path = PathBuf::new(); let mut bind = false; let mut readonly = false; let mut nodev = false; let mut noexec = false; let mut nosuid = false; { let mut ap = ArgumentParser::new(); ap.set_description("Remount utility. Similar to `mount -o remount` \ but keeps current mount point options"); ap.refer(&mut path).add_argument("path", Parse, "Directory for remounting").required(); ap.refer(&mut bind).add_option(&["--bind"], StoreTrue, "Set bind mount option"); ap.refer(&mut readonly).add_option(&["--readonly"], StoreTrue, "Set readonly mount option"); ap.refer(&mut nodev).add_option(&["--nodev"], StoreTrue, "Set nodev mount option"); ap.refer(&mut noexec).add_option(&["--noexec"], StoreTrue, "Set noexec mount option"); ap.refer(&mut nosuid).add_option(&["--nosuid"], StoreTrue, "Set nosuid mount option"); ap.parse_args_or_exit(); } match libmount::Remount::new(path) .bind(bind) .readonly(readonly) .nodev(nodev) .noexec(noexec) .nosuid(nosuid) .remount() { Ok(()) => {} Err(e) => { error!("{}", e); exit(1); } } } libmount-0.1.15/examples/tmpfs.rs010066400037200003720000000030471356324602500151770ustar0000000000000000extern crate libmount; extern crate argparse; extern crate env_logger; #[macro_use] extern crate log; use std::path::PathBuf; use std::process::exit; use argparse::{ArgumentParser, Parse, StoreOption}; fn main() { env_logger::init(); let mut target = PathBuf::new(); let mut size = None::; let mut mode = None::; let mut uid = None::; let mut gid = None::; { let mut ap = ArgumentParser::new(); ap.set_description("Tmpfs mount utility. Similar to `mount --tmpfs`"); ap.refer(&mut target).add_argument("target", Parse, "Target directory to mount tmpfs to").required(); ap.refer(&mut size).add_option(&["--size"], StoreOption, "Set size of the filesystem"); ap.refer(&mut mode).add_option(&["--mode"], StoreOption, "Set mode of the root directory"); ap.refer(&mut uid).add_option(&["--uid"], StoreOption, "Set uid of the directory"); ap.refer(&mut gid).add_option(&["--gid"], StoreOption, "Set gid of the directory"); ap.parse_args_or_exit(); } let mut mnt = libmount::Tmpfs::new(target); if let Some(x) = size { mnt = mnt.size_bytes(x); }; if let Some(ref x) = mode { mnt = mnt.mode(u32::from_str_radix(x, 8).expect("valid octal mode")); } if let Some(x) = uid { mnt = mnt.uid(x); } if let Some(x) = gid { mnt = mnt.gid(x); } match mnt.mount() { Ok(()) => {} Err(e) => { error!("{}", e); exit(1); } } } libmount-0.1.15/src/bind.rs010066400037200003720000000056641356324602500137420ustar0000000000000000use std::fmt; use std::ffi::{CStr, CString, OsStr}; use std::os::unix::ffi::OsStrExt; use std::path::Path; use nix::mount::{MsFlags, mount}; use {OSError, Error}; use util::{path_to_cstring, as_path}; use explain::{Explainable, exists, user}; use remount::Remount; /// A mount bind definition /// /// By default bind mount is recursive (it's what you want most of the time). /// /// Also recursive mounts can be used in user namespaces. #[derive(Debug, Clone)] pub struct BindMount { source: CString, target: CString, recursive: bool, readonly: bool, } impl BindMount { /// Create a new, recursive bind mount /// /// You can disable recursion with a `non_recursive()` method pub fn new, B: AsRef>(source: A, target: B) -> BindMount { BindMount { source: path_to_cstring(source.as_ref()), target: path_to_cstring(target.as_ref()), recursive: true, readonly: false, } } /// Toggle recursion pub fn recursive(mut self, flag: bool) -> BindMount { self.recursive = flag; self } /// If set to `true` makes bind-mount readonly /// /// Few notes: /// /// 1. This makes additional `mount` call (`Remount().readonly()`) /// 2. If remount fails mount bind is left on the filesystem, no cleanup /// is done /// 3. If set to `false` is option is no-op (does **not** remount `rw`) pub fn readonly(mut self, flag: bool) -> BindMount { self.readonly = flag; self } /// Execute a bind mount pub fn bare_mount(self) -> Result<(), OSError> { let mut flags = MsFlags::MS_BIND; if self.recursive { flags = flags | MsFlags::MS_REC; } if let Err(err) = mount( Some(&*self.source), &*self.target, None::<&CStr>, flags, None::<&CStr>, ) { return Err(OSError::from_nix(err, Box::new(self))); } if self.readonly { try!(Remount::new(OsStr::from_bytes(self.target.as_bytes())) .bind(true) .readonly(true) .bare_remount()); } Ok(()) } /// Execute a bind mount and explain the error immediately pub fn mount(self) -> Result<(), Error> { self.bare_mount().map_err(OSError::explain) } } impl fmt::Display for BindMount { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.recursive { try!(write!(fmt, "recursive ")); } write!(fmt, "bind mount {:?} -> {:?}", as_path(&self.source), as_path(&self.target)) } } impl Explainable for BindMount { fn explain(&self) -> String { [ format!("source: {}", exists(as_path(&self.source))), format!("target: {}", exists(as_path(&self.target))), format!("{}", user()), ].join(", ") } } libmount-0.1.15/src/error.rs010066400037200003720000000026711356324602500141520ustar0000000000000000use std::io; use std::fmt; use std::error::Error as StdError; use {OSError, Error, MountError}; use remount::RemountError; impl OSError { /// Convert error to the one providing extra useful information pub fn explain(self) -> Error { let text = self.1.explain(); match self.0 { MountError::Io(e) => Error(self.1, e, text), MountError::Remount(RemountError::Io(msg, io_err)) => { Error(self.1, io_err, format!("{}, {}", msg, text)) }, MountError::Remount(err) => { let text = format!("{}, {}", &err, text); let err = Box::new(err); Error(self.1, io::Error::new(io::ErrorKind::InvalidData, err), text) }, } } } impl fmt::Display for OSError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}: {}", self.1, self.0) } } impl StdError for OSError { fn cause(&self) -> Option<&StdError> { Some(&self.0) } fn description(&self) -> &str { self.0.description() } } impl fmt::Display for Error { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}: {} ({})", self.0, self.1, self.2) } } impl StdError for Error { fn cause(&self) -> Option<&StdError> { Some(&self.1) } fn description(&self) -> &str { self.1.description() } } libmount-0.1.15/src/escape.rs010066400037200003720000000000001356324602500142410ustar0000000000000000libmount-0.1.15/src/explain.rs010066400037200003720000000016111356324602500144520ustar0000000000000000use std::io::Read; use std::fs::File; use std::fmt::{Display, Debug}; use std::path::Path; use nix::unistd::getuid; pub trait Explainable: Display + Debug { fn explain(&self) -> String; } pub fn exists(path: &Path) -> &'static str { if path.exists() { "exists" } else { "missing" } } pub fn user() -> &'static str { let uid = getuid(); if u32::from(uid) == 0 { let mut buf = String::with_capacity(100); match File::open("/proc/self/uid_map") .and_then(|mut f| f.read_to_string(&mut buf)) { Ok(_) => { if buf == " 0 0 4294967295\n" { "superuser" } else { "mapped-root" } } Err(_) => { "privileged" } } } else { "regular-user" } } libmount-0.1.15/src/lib.rs010066400037200003720000000054621356324602500135700ustar0000000000000000//! # libmount //! //! [Documentation](https://docs.rs/libmount) | //! [Github](https://github.com/tailhook/libmount) | //! [Crate](https://crates.io/crates/libmount) //! //! This library has two major goals: //! //! 1. Add type-safe interface for mount() system call //! 2. Add very good explanation of what's wrong when the call fails //! //! So we have two error types: //! //! 1. `OSError` holds mount info and errno //! 2. `Error` is returned by `OSError::explain()` //! //! The first one is returned by `bare_mount()` the second by `mount()`, and //! using latter is preffered for most situations. Unless performance is //! too critical (i.e. you are doing thousands of *failing* mounts per second). //! On the success path there is no overhead. //! #![warn(missing_debug_implementations)] #![warn(missing_docs)] extern crate libc; extern crate nix; #[macro_use] extern crate quick_error; mod util; mod error; mod explain; mod bind; mod overlay; mod tmpfs; mod modify; mod remount; pub mod mountinfo; use std::io; use explain::Explainable; use remount::RemountError; pub use bind::BindMount; pub use overlay::Overlay; pub use tmpfs::Tmpfs; pub use modify::Move; pub use remount::Remount; quick_error! { #[derive(Debug)] enum MountError { Io(err: io::Error) { cause(err) from() } Remount(err: RemountError) { cause(err) from() } } } /// The raw os error /// /// This is a wrapper around `io::Error` providing `explain()` method /// /// Note: you need to explain as fast as possible, because during explain /// library makes some probes for different things in filesystem, and if /// anything changes it may give incorrect results. /// /// You should always `explain()` the errors, unless you are trying lots of /// mounts for bruteforcing or other similar thing and you are concerned of /// performance. Usually library does `stat()` and similar things which are /// much faster than mount anyway. Also explaining is zero-cost in the success /// path. /// #[derive(Debug)] pub struct OSError(MountError, Box); impl OSError { fn from_remount(err: RemountError, explain: Box) -> OSError { OSError(MountError::Remount(err), explain) } fn from_nix(err: nix::Error, explain: Box) -> OSError { OSError( MountError::Io( err.as_errno().map_or_else(|| io::Error::new(io::ErrorKind::Other, err), io::Error::from), ), explain, ) } } /// The error holder which contains as much information about why failure /// happens as the library implementors could gain /// /// This type only provides `Display` for now, but some programmatic interface /// is expected in future. #[derive(Debug)] pub struct Error(Box, io::Error, String); libmount-0.1.15/src/modify.rs010066400037200003720000000031351356324602500143040ustar0000000000000000use std::fmt; use std::ffi::{CStr, CString}; use std::path::Path; use nix::mount::{MsFlags, mount}; use {OSError, Error}; use util::{path_to_cstring, as_path}; use explain::{Explainable, exists}; /// A move operation definition /// /// This is a similar to `mount --move` and allows to atomically move mount /// point from one place to another #[derive(Debug, Clone)] pub struct Move { source: CString, target: CString, } impl Move { /// Create a new Move operation pub fn new, B: AsRef>(source: A, target: B) -> Move { Move { source: path_to_cstring(source.as_ref()), target: path_to_cstring(target.as_ref()), } } /// Execute a move-mountpoint operation pub fn bare_move_mountpoint(self) -> Result<(), OSError> { mount(Some(&*self.source), &*self.target, None::<&CStr>, MsFlags::MS_MOVE, None::<&CStr>) .map_err(|err| OSError::from_nix(err, Box::new(self))) } /// Execute a move mountpoint operation and explain the error immediately pub fn move_mountpoint(self) -> Result<(), Error> { self.bare_move_mountpoint().map_err(OSError::explain) } } impl fmt::Display for Move { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "move {:?} -> {:?}", as_path(&self.source), as_path(&self.target)) } } impl Explainable for Move { fn explain(&self) -> String { [ format!("source: {}", exists(as_path(&self.source))), format!("target: {}", exists(as_path(&self.target))), ].join(", ") } } libmount-0.1.15/src/mountinfo.rs010066400037200003720000000507571356324602500150470ustar0000000000000000//! This module contains parser for /proc/PID/mountinfo //! use std; use std::fmt; use std::ffi::{OsStr, OsString}; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::borrow::Cow; use std::error::Error; use nix::mount::MsFlags; use libc::c_ulong; /// Error parsing a single entry of mountinfo file #[derive(Debug)] pub(crate) struct ParseRowError(pub(crate) String); impl fmt::Display for ParseRowError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Parse error: {}", self.0) } } impl Error for ParseRowError { fn description(&self) -> &str { return &self.0; } } /// Mountinfo file parsing error #[derive(Debug)] pub struct ParseError { msg: String, row_num: usize, row: String, } impl ParseError { fn new(msg: String, row_num: usize, row: String) -> ParseError { ParseError { msg: msg, row_num: row_num, row: row, } } } impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Parse error at line {}: {}\n{}", self.row_num, self.description(), self.row) } } impl Error for ParseError { fn description(&self) -> &str { return &self.msg; } } /// A parser class for mountinfo file #[derive(Debug)] pub struct Parser<'a> { data: &'a [u8], row_num: usize, exhausted: bool, } #[allow(dead_code)] impl<'a> Parser<'a> { /// Create a new parser /// /// `data` should contain whole contents of `mountinfo` file of any process pub fn new(data: &'a [u8]) -> Parser<'a> { Parser { data: data, row_num: 0, exhausted: false, } } } /// A single entry returned by mountpoint parser #[allow(missing_docs)] // self-descriptive / described by man page #[derive(Debug)] pub struct MountPoint<'a> { pub mount_id: c_ulong, pub parent_id: c_ulong, pub major: c_ulong, pub minor: c_ulong, pub root: Cow<'a, OsStr>, pub mount_point: Cow<'a, OsStr>, pub mount_options: Cow<'a, OsStr>, // TODO: we might need some enum which will have three states: // empty, single Cow value or a vector Vec> pub optional_fields: Cow<'a, OsStr>, pub fstype: Cow<'a, OsStr>, pub mount_source: Cow<'a, OsStr>, pub super_options: Cow<'a, OsStr>, } impl<'a> MountPoint<'a> { /// Returns flags of the mountpoint as a numeric value /// /// This value matches linux `MsFlags::MS_*` flags as passed into mount syscall pub fn get_flags(&self) -> c_ulong { self.get_mount_flags().bits() as c_ulong } pub(crate) fn get_mount_flags(&self) -> MsFlags { let mut flags = MsFlags::empty(); for opt in self.mount_options.as_bytes().split(|c| *c == b',') { let opt = OsStr::from_bytes(opt); if opt == OsStr::new("ro") { flags |= MsFlags::MS_RDONLY } else if opt == OsStr::new("nosuid") { flags |= MsFlags::MS_NOSUID } else if opt == OsStr::new("nodev") { flags |= MsFlags::MS_NODEV } else if opt == OsStr::new("noexec") { flags |= MsFlags::MS_NOEXEC } else if opt == OsStr::new("mand") { flags |= MsFlags::MS_MANDLOCK } else if opt == OsStr::new("sync") { flags |= MsFlags::MS_SYNCHRONOUS } else if opt == OsStr::new("dirsync") { flags |= MsFlags::MS_DIRSYNC } else if opt == OsStr::new("noatime") { flags |= MsFlags::MS_NOATIME } else if opt == OsStr::new("nodiratime") { flags |= MsFlags::MS_NODIRATIME } else if opt == OsStr::new("relatime") { flags |= MsFlags::MS_RELATIME } else if opt == OsStr::new("strictatime") { flags |= MsFlags::MS_STRICTATIME } } flags } } impl<'a> Iterator for Parser<'a> { type Item = Result, ParseError>; fn next(&mut self) -> Option { if self.exhausted { return None; } loop { match self.data.iter().position(|c| *c == b'\n') { Some(ix) => { self.row_num += 1; let row = &self.data[..ix]; self.data = &self.data[ix + 1..]; let res = match parse_mount_point(row) { Ok(None) => continue, Ok(Some(v)) => Ok(v), Err(e) => Err(ParseError::new(e.0, self.row_num, String::from_utf8_lossy(row).into_owned())), }; return Some(res); }, None => { self.exhausted = true; let res = match parse_mount_point(self.data) { Ok(None) => return None, Ok(Some(v)) => Ok(v), Err(e) => Err(ParseError::new(e.0, self.row_num, String::from_utf8_lossy(self.data).into_owned())), }; return Some(res); }, } } } } pub(crate) fn parse_mount_point<'a>(row: &'a [u8]) -> Result>, ParseRowError> { let row = rstrip_cr(&row); if is_comment_line(row) { return Ok(None); } let (mount_id, row) = try!(parse_int(row)); let (parent_id, row) = try!(parse_int(row)); let (major, minor, row) = try!(parse_major_minor(row)); let (root, row) = try!(parse_os_str(row)); let (mount_point, row) = try!(parse_os_str(row)); let (mount_options, row) = try!(parse_os_str(row)); let (optional_fields, row) = try!(parse_optional(row)); let (fstype, row) = try!(parse_os_str(row)); let (mount_source, row) = try!(parse_os_str(row)); let (super_options, _) = try!(parse_os_str(row)); // TODO: should we ignore extra fields? Ok(Some(MountPoint { mount_id: mount_id, parent_id: parent_id, major: major, minor: minor, root: root, mount_point: mount_point, mount_options: mount_options, optional_fields: optional_fields, fstype: fstype, mount_source: mount_source, super_options: super_options, })) } fn is_comment_line(row: &[u8]) -> bool { if row.is_empty() { return true; } for c in row { if *c == b' ' || *c == b'\t' { continue; } if *c == b'#' { return true; } return false; } return false; } fn rstrip_cr(row: &[u8]) -> &[u8] { if let Some((&b'\r', tail)) = row.split_last() { tail } else { row } } fn parse_field<'a>(data: &'a [u8], delimit: &'a [u8]) -> Result<(&'a [u8], &'a [u8]), ParseRowError> { if data.is_empty() { return Err(ParseRowError(format!("Expected more fields"))); } let data = lstrip_whitespaces(data); Ok(split_by(data, delimit)) } fn parse_os_str<'a>(data: &'a [u8]) -> Result<(Cow<'a, OsStr>, &'a [u8]), ParseRowError> { let (field, tail) = try!(parse_field(data, b" ")); Ok((unescape_octals(OsStr::from_bytes(field)), tail)) } fn parse_int(data: &[u8]) -> Result<(c_ulong, &[u8]), ParseRowError> { let (field, tail) = try!(parse_field(data, b" ")); let v = try!(std::str::from_utf8(field).map_err(|e| { ParseRowError(format!("Cannot parse integer {:?}: {}", String::from_utf8_lossy(field).into_owned(), e))})); let v = try!(c_ulong::from_str_radix(v, 10).map_err(|e| { ParseRowError(format!("Cannot parse integer {:?}: {}", String::from_utf8_lossy(field).into_owned(), e))})); Ok((v, tail)) } fn parse_major_minor(data: &[u8]) -> Result<(c_ulong, c_ulong, &[u8]), ParseRowError> { let (major_field, data) = try!(parse_field(data, b":")); let (minor_field, tail) = try!(parse_field(data, b" ")); let (major, _) = try!(parse_int(major_field)); let (minor, _) = try!(parse_int(minor_field)); Ok((major, minor, tail)) } fn parse_optional<'a>(data: &'a [u8]) -> Result<(Cow<'a, OsStr>, &'a [u8]), ParseRowError> { let (field, tail) = try!(parse_field(data, b"- ")); let field = rstrip_whitespaces(field); Ok((unescape_octals(OsStr::from_bytes(field)), tail)) } fn lstrip_whitespaces(v: &[u8]) -> &[u8] { for (i, c) in v.iter().enumerate() { if *c != b' ' { return &v[i..]; } } return &v[0..0]; } fn rstrip_whitespaces(v: &[u8]) -> &[u8] { for (i, c) in v.iter().enumerate().rev() { if *c != b' ' { return &v[..i + 1]; } } return &v[0..0]; } fn split_by<'a, 'b>(v: &'a [u8], needle: &'b [u8]) -> (&'a [u8], &'a [u8]) { if needle.len() > v.len() { return (&v[0..], &v[0..0]); } let mut i = 0; while i <= v.len() - needle.len() { let (head, tail) = v.split_at(i); if tail.starts_with(needle) { return (head, &tail[needle.len()..]); } i += 1; } return (&v[0..], &v[0..0]); } fn unescape_octals(s: &OsStr) -> Cow { let (mut i, has_escapes) = { let bytes = s.as_bytes(); let mut i = 0; while i < bytes.len() { if is_octal_encoding(&bytes[i..]) { break; } i += 1; } (i, i < bytes.len()) }; if !has_escapes { return Cow::Borrowed(s); } let mut v: Vec = vec!(); let bytes = s.as_bytes(); v.extend_from_slice(&bytes[..i]); while i < bytes.len() { if is_octal_encoding(&bytes[i..]) { let c = parse_octal(&bytes[i + 1..]); v.push(c); i += 4; } else { v.push(bytes[i]); i += 1; } } Cow::Owned(OsString::from_vec(v)) } fn is_octal_encoding(v: &[u8]) -> bool { v.len() >= 4 && v[0] == b'\\' && is_oct(v[1]) && is_oct(v[2]) && is_oct(v[3]) } fn is_oct(c: u8) -> bool { c >= b'0' && c <= b'7' } fn parse_octal(v: &[u8]) -> u8 { ((v[0] & 7) << 6) + ((v[1] & 7) << 3) + (v[2] & 7) } #[cfg(test)] mod test { use std::path::Path; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; use nix::mount::MsFlags; use super::{Parser, ParseError}; use super::{is_octal_encoding, parse_octal, unescape_octals}; #[test] fn test_is_octal_encoding() { assert!(is_octal_encoding(b"\\000")); assert!(is_octal_encoding(b"\\123")); assert!(is_octal_encoding(b"\\777")); assert!(!is_octal_encoding(b"")); assert!(!is_octal_encoding(b"\\")); assert!(!is_octal_encoding(b"000")); assert!(!is_octal_encoding(b"\\00")); assert!(!is_octal_encoding(b"\\800")); } #[test] fn test_parse_octal() { assert_eq!(parse_octal(b"000"), 0); assert_eq!(parse_octal(b"123"), 83); assert_eq!(parse_octal(b"377"), 255); // mount utility just ignores overflowing assert_eq!(parse_octal(b"777"), 255); } #[test] fn test_unescape_octals() { assert_eq!(unescape_octals(OsStr::new("\\000")), OsStr::from_bytes(b"\x00")); assert_eq!(unescape_octals(OsStr::new("\\00")), OsStr::new("\\00")); assert_eq!(unescape_octals(OsStr::new("test\\040data")), OsStr::new("test data")); } #[test] fn test_mount_info_parser_proc() { let content = b"19 24 0:4 / /proc rw,nosuid,nodev,noexec,relatime shared:12 - proc proc rw"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_id, 19); assert_eq!(mount_point.parent_id, 24); assert_eq!(mount_point.major, 0); assert_eq!(mount_point.minor, 4); assert_eq!(mount_point.root, Path::new("/")); assert_eq!(mount_point.mount_point, Path::new("/proc")); assert_eq!(mount_point.mount_options, OsStr::new("rw,nosuid,nodev,noexec,relatime")); assert_eq!(mount_point.optional_fields, OsStr::new("shared:12")); assert_eq!(mount_point.fstype, OsStr::new("proc")); assert_eq!(mount_point.mount_source, OsStr::new("proc")); assert_eq!(mount_point.super_options, OsStr::new("rw")); assert_eq!(mount_point.get_mount_flags(), MsFlags::MS_NOSUID | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC | MsFlags::MS_RELATIME); assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_comment() { let content = b"# Test comment\n\ \t # Another shifted comment\n\ 19 24 0:4 / /#proc rw,nosuid,nodev,noexec,relatime shared:12 - proc proc rw"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_id, 19); assert_eq!(mount_point.parent_id, 24); assert_eq!(mount_point.major, 0); assert_eq!(mount_point.minor, 4); assert_eq!(mount_point.root, Path::new("/")); assert_eq!(mount_point.mount_point, Path::new("/#proc")); assert_eq!(mount_point.mount_options, OsStr::new("rw,nosuid,nodev,noexec,relatime")); assert_eq!(mount_point.optional_fields, OsStr::new("shared:12")); assert_eq!(mount_point.fstype, OsStr::new("proc")); assert_eq!(mount_point.mount_source, OsStr::new("proc")); assert_eq!(mount_point.super_options, OsStr::new("rw")); assert_eq!(mount_point.get_mount_flags(), MsFlags::MS_NOSUID | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC | MsFlags::MS_RELATIME); assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_missing_optional_fields() { let content = b"335 294 0:56 / /proc rw,relatime - proc proc rw"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_id, 335); assert_eq!(mount_point.parent_id, 294); assert_eq!(mount_point.major, 0); assert_eq!(mount_point.minor, 56); assert_eq!(mount_point.root, Path::new("/")); assert_eq!(mount_point.mount_point, Path::new("/proc")); assert_eq!(mount_point.mount_options, OsStr::new("rw,relatime")); assert_eq!(mount_point.optional_fields, OsStr::new("")); assert_eq!(mount_point.fstype, OsStr::new("proc")); assert_eq!(mount_point.mount_source, OsStr::new("proc")); assert_eq!(mount_point.super_options, OsStr::new("rw")); assert_eq!(mount_point.get_mount_flags(), MsFlags::MS_RELATIME); assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_more_optional_fields() { let content = b"335 294 0:56 / /proc rw,relatime shared:12 master:1 - proc proc rw"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_id, 335); assert_eq!(mount_point.parent_id, 294); assert_eq!(mount_point.major, 0); assert_eq!(mount_point.minor, 56); assert_eq!(mount_point.root, Path::new("/")); assert_eq!(mount_point.mount_point, Path::new("/proc")); assert_eq!(mount_point.mount_options, OsStr::new("rw,relatime")); assert_eq!(mount_point.optional_fields, OsStr::new("shared:12 master:1")); assert_eq!(mount_point.fstype, OsStr::new("proc")); assert_eq!(mount_point.mount_source, OsStr::new("proc")); assert_eq!(mount_point.super_options, OsStr::new("rw")); assert_eq!(mount_point.get_mount_flags(), MsFlags::MS_RELATIME); assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_escaping() { let content = br"76 24 8:6 / /home/my\040super\011name\012\134 rw,relatime shared:29 - ext4 /dev/sda1 rw,data=ordered"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_id, 76); assert_eq!(mount_point.parent_id, 24); assert_eq!(mount_point.major, 8); assert_eq!(mount_point.minor, 6); assert_eq!(mount_point.root, Path::new("/")); assert_eq!(mount_point.mount_point, Path::new("/home/my super\tname\n\\")); assert_eq!(mount_point.mount_options, OsStr::new("rw,relatime")); assert_eq!(mount_point.optional_fields, OsStr::new("shared:29")); assert_eq!(mount_point.fstype, OsStr::new("ext4")); assert_eq!(mount_point.mount_source, OsStr::new("/dev/sda1")); assert_eq!(mount_point.super_options, OsStr::new("rw,data=ordered")); assert_eq!(mount_point.get_mount_flags(), MsFlags::MS_RELATIME); assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_non_utf8() { let content = b"22 24 0:19 / /\xff rw shared:5 - tmpfs tmpfs rw,mode=755"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_point, Path::new(OsStr::from_bytes(b"/\xff"))); assert_eq!(mount_point.mount_options, OsStr::new("rw")); assert_eq!(mount_point.fstype, OsStr::new("tmpfs")); assert_eq!(mount_point.mount_source, OsStr::new("tmpfs")); assert_eq!(mount_point.get_mount_flags(), MsFlags::empty()); assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_crlf() { let content = b"26 20 0:21 / /tmp rw shared:4 - tmpfs tmpfs rw\r\n\ \n\ \r\n\ 27 22 0:22 / /tmp rw,nosuid,nodev shared:6 - tmpfs tmpfs rw\r"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_point, Path::new("/tmp")); assert_eq!(mount_point.mount_options, OsStr::new("rw")); assert_eq!(mount_point.super_options, OsStr::new("rw")); assert_eq!(mount_point.get_mount_flags(), MsFlags::empty()); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_point, Path::new("/tmp")); assert_eq!(mount_point.mount_options, OsStr::new("rw,nosuid,nodev")); assert_eq!(mount_point.super_options, OsStr::new("rw")); assert_eq!(mount_point.get_mount_flags(), MsFlags::MS_NOSUID | MsFlags::MS_NODEV); assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_incomplete_row() { let content = b"19 24 0:4 / /proc rw,relatime shared:12 - proc proc"; let mut parser = Parser::new(&content[..]); let mount_info_res = parser.next().unwrap(); assert!(mount_info_res.is_err()); match mount_info_res { Err(ParseError {ref msg, ..}) => { assert_eq!(msg, "Expected more fields"); }, _ => panic!("Expected incomplete row error") } assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_invalid_int() { let content = b"19 24b 0:4 / /proc rw,relatime - proc proc rw"; let mut parser = Parser::new(&content[..]); let mount_info_res = parser.next().unwrap(); assert!(mount_info_res.is_err()); match mount_info_res { Err(ParseError {ref msg, ..}) => { assert!(msg.starts_with("Cannot parse integer \"24b\":")); }, _ => panic!("Expected invalid row error") } assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_overflowed_int() { let content = b"111111111111111111111"; let mut parser = Parser::new(&content[..]); let mount_info_res = parser.next().unwrap(); assert!(mount_info_res.is_err()); match mount_info_res { Err(ParseError {ref msg, ..}) => { assert!(msg.starts_with("Cannot parse integer \"111111111111111111111\"")); }, _ => panic!("Expected invalid row error") } assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_invalid_escape() { let content = b"19 24 0:4 / /proc\\1 rw,relatime - proc proc rw"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_point, Path::new("/proc\\1")); assert!(parser.next().is_none()); } #[test] fn test_mount_info_parser_overflowed_escape() { let content = b"19 24 0:4 / /proc\\400 rw,nosuid,nodev,noexec,relatime - proc proc rw"; let mut parser = Parser::new(&content[..]); let mount_point = parser.next().unwrap().unwrap(); assert_eq!(mount_point.mount_point, Path::new(OsStr::from_bytes(b"/proc\x00"))); assert!(parser.next().is_none()); } } libmount-0.1.15/src/overlay.rs010066400037200003720000000134671356324602500145070ustar0000000000000000use std::fmt; use std::path::{Path, PathBuf}; use std::fs::metadata; use std::ffi::{CStr, CString}; use std::os::unix::fs::MetadataExt; use std::os::unix::ffi::OsStrExt; use nix::mount::{MsFlags, mount}; use util::{path_to_cstring, as_path}; use {OSError, Error}; use explain::{Explainable, exists, user}; /// An overlay mount point /// /// This requires linux kernel of at least 3.18. /// /// To use overlayfs in user namespace you need a kernel patch (which is /// enabled by default in ubuntu). At least this is still true for mainline /// kernel 4.5.0. #[derive(Debug, Clone)] pub struct Overlay { lowerdirs: Vec, upperdir: Option, workdir: Option, target: CString, } impl Overlay { /// A constructor for read-only overlayfs mount /// /// You must have at least two directories in the list (for single /// dir it might be equal to bind mount, but kernel return EINVAL for /// such options). /// /// The top-most directory will be first in the list. pub fn readonly<'x, I, T>(dirs: I, target: T) -> Overlay where I: Iterator, T: AsRef { Overlay { lowerdirs: dirs.map(|x| x.to_path_buf()).collect(), upperdir: None, workdir: None, target: path_to_cstring(target.as_ref()), } } /// A constructor for writable overlayfs mount /// /// The upperdir and workdir must be on the same filesystem. /// /// The top-most directory will be first in the list of lowerdirs. pub fn writable<'x, I, B, C, D>(lowerdirs: I, upperdir: B, workdir: C, target: D) -> Overlay where I: Iterator, B: AsRef, C: AsRef, D: AsRef, { Overlay { lowerdirs: lowerdirs.map(|x| x.to_path_buf()).collect(), upperdir: Some(upperdir.as_ref().to_path_buf()), workdir: Some(workdir.as_ref().to_path_buf()), target: path_to_cstring(target.as_ref()), } } /// Execute an overlay mount pub fn bare_mount(self) -> Result<(), OSError> { let mut options = Vec::new(); options.extend(b"lowerdir="); for (i, p) in self.lowerdirs.iter().enumerate() { if i != 0 { options.push(b':') } append_escape(&mut options, p); } if let (Some(u), Some(w)) = (self.upperdir.as_ref(), self.workdir.as_ref()) { options.extend(b",upperdir="); append_escape(&mut options, u); options.extend(b",workdir="); append_escape(&mut options, w); } mount( Some(CStr::from_bytes_with_nul(b"overlay\0").unwrap()), &*self.target, Some(CStr::from_bytes_with_nul(b"overlay\0").unwrap()), MsFlags::empty(), Some(&*options), ).map_err(|err| OSError::from_nix(err, Box::new(self))) } /// Execute an overlay mount and explain the error immediately pub fn mount(self) -> Result<(), Error> { self.bare_mount().map_err(OSError::explain) } } /// Escape the path to put it into options string for overlayfs /// /// The rules here are not documented anywhere as far as I know and was /// derived experimentally. fn append_escape(dest: &mut Vec, path: &Path) { for &byte in path.as_os_str().as_bytes().iter() { match byte { // This is escape char b'\\' => { dest.push(b'\\'); dest.push(b'\\'); } // This is used as a path separator in lowerdir b':' => { dest.push(b'\\'); dest.push(b':'); } // This is used as a argument separator b',' => { dest.push(b'\\'); dest.push(b','); } x => dest.push(x), } } } impl fmt::Display for Overlay { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if let (Some(udir), Some(wdir)) = (self.upperdir.as_ref(), self.workdir.as_ref()) { write!(fmt, "overlayfs \ {},upperdir={:?},workdir={:?} -> {:?}", self.lowerdirs.iter().map(|x| format!("{:?}", x)) .collect::>().join(":"), udir, wdir, as_path(&self.target)) } else { write!(fmt, "overlayfs \ {} -> {:?}", self.lowerdirs.iter().map(|x| format!("{:?}", x)) .collect::>().join(":"), as_path(&self.target)) } } } impl Explainable for Overlay { fn explain(&self) -> String { let mut info = self.lowerdirs.iter() .map(|x| format!("{:?}: {}", x, exists(x))) .collect::>(); if let (Some(udir), Some(wdir)) = (self.upperdir.as_ref(), self.workdir.as_ref()) { let umeta = metadata(&udir).ok(); let wmeta = metadata(&wdir).ok(); info.push(format!("upperdir: {}", exists(&udir))); info.push(format!("workdir: {}", exists(&wdir))); if let (Some(u), Some(w)) = (umeta, wmeta) { info.push(format!("{}", if u.dev() == w.dev() { "same-fs" } else { "different-fs" })); } if udir.starts_with(wdir) { info.push("upperdir-prefix-of-workdir".to_string()); } else if wdir.starts_with(udir) { info.push("workdir-prefix-of-upperdir".to_string()); } info.push(format!("target: {}", exists(as_path(&self.target)))); } if self.lowerdirs.len() < 1 { info.push("no-lowerdirs".to_string()); } else if self.upperdir.is_none() && self.lowerdirs.len() < 2 { info.push("single-lowerdir".to_string()); } info.push(user().to_string()); info.join(", ") } } libmount-0.1.15/src/remount.rs010066400037200003720000000316531356324602500145140ustar0000000000000000use std::io; use std::fmt; use std::ffi::CStr; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use std::env::current_dir; use std::default::Default; use nix::mount::{MsFlags, mount}; use {OSError, Error}; use util::path_to_cstring; use explain::{Explainable, exists, user}; use mountinfo::{parse_mount_point}; /// A remount definition /// /// Usually it is used to change mount flags for a mounted filesystem. /// Especially to make a readonly filesystem writable or vice versa. #[derive(Debug, Clone)] pub struct Remount { path: PathBuf, flags: MountFlags, } #[derive(Debug, Clone, Default)] struct MountFlags { pub bind: Option, pub readonly: Option, pub nodev: Option, pub noexec: Option, pub nosuid: Option, pub noatime: Option, pub nodiratime: Option, pub relatime: Option, pub strictatime: Option, pub dirsync: Option, pub synchronous: Option, pub mandlock: Option, } impl MountFlags { fn apply_to_flags(&self, flags: MsFlags) -> MsFlags { let mut flags = flags; flags = apply_flag(flags, MsFlags::MS_BIND, self.bind); flags = apply_flag(flags, MsFlags::MS_RDONLY, self.readonly); flags = apply_flag(flags, MsFlags::MS_NODEV, self.nodev); flags = apply_flag(flags, MsFlags::MS_NOEXEC, self.noexec); flags = apply_flag(flags, MsFlags::MS_NOSUID, self.nosuid); flags = apply_flag(flags, MsFlags::MS_NOATIME, self.noatime); flags = apply_flag(flags, MsFlags::MS_NODIRATIME, self.nodiratime); flags = apply_flag(flags, MsFlags::MS_RELATIME, self.relatime); flags = apply_flag(flags, MsFlags::MS_STRICTATIME, self.strictatime); flags = apply_flag(flags, MsFlags::MS_DIRSYNC, self.dirsync); flags = apply_flag(flags, MsFlags::MS_SYNCHRONOUS, self.synchronous); flags = apply_flag(flags, MsFlags::MS_MANDLOCK, self.mandlock); flags } } fn apply_flag(flags: MsFlags, flag: MsFlags, set: Option) -> MsFlags { match set { Some(true) => flags | flag, Some(false) => flags & !flag, None => flags, } } quick_error! { #[derive(Debug)] pub enum RemountError { Io(msg: String, err: io::Error) { cause(err) display("{}: {}", msg, err) description(err.description()) from(err: io::Error) -> (String::new(), err) } ParseMountInfo(err: String) { display("{}", err) from() } UnknownMountPoint(path: PathBuf) { display("Cannot find mount point: {:?}", path) } } } impl Remount { /// Create a new Remount operation /// /// By default it doesn't modify any flags. So is basically useless, you /// should set some flags to make it effective. pub fn new>(path: A) -> Remount { Remount { path: path.as_ref().to_path_buf(), flags: Default::default(), } } /// Set bind flag /// Note: remount readonly doesn't work without MS_BIND flag /// inside unpriviledged user namespaces pub fn bind(mut self, flag: bool) -> Remount { self.flags.bind = Some(flag); self } /// Set readonly flag pub fn readonly(mut self, flag: bool) -> Remount { self.flags.readonly = Some(flag); self } /// Set nodev flag pub fn nodev(mut self, flag: bool) -> Remount { self.flags.nodev = Some(flag); self } /// Set noexec flag pub fn noexec(mut self, flag: bool) -> Remount { self.flags.noexec = Some(flag); self } /// Set nosuid flag pub fn nosuid(mut self, flag: bool) -> Remount { self.flags.nosuid = Some(flag); self } /// Set noatime flag pub fn noatime(mut self, flag: bool) -> Remount { self.flags.noatime = Some(flag); self } /// Set nodiratime flag pub fn nodiratime(mut self, flag: bool) -> Remount { self.flags.nodiratime = Some(flag); self } /// Set relatime flag pub fn relatime(mut self, flag: bool) -> Remount { self.flags.relatime = Some(flag); self } /// Set strictatime flag pub fn strictatime(mut self, flag: bool) -> Remount { self.flags.strictatime = Some(flag); self } /// Set dirsync flag pub fn dirsync(mut self, flag: bool) -> Remount { self.flags.dirsync = Some(flag); self } /// Set synchronous flag pub fn synchronous(mut self, flag: bool) -> Remount { self.flags.synchronous = Some(flag); self } /// Set mandlock flag pub fn mandlock(mut self, flag: bool) -> Remount { self.flags.mandlock = Some(flag); self } /// Execute a remount pub fn bare_remount(self) -> Result<(), OSError> { let mut flags = match get_mountpoint_flags(&self.path) { Ok(flags) => flags, Err(e) => { return Err(OSError::from_remount(e, Box::new(self))); }, }; flags = self.flags.apply_to_flags(flags) | MsFlags::MS_REMOUNT; mount( None::<&CStr>, &*path_to_cstring(&self.path), None::<&CStr>, flags, None::<&CStr>, ).map_err(|err| OSError::from_nix(err, Box::new(self))) } /// Execute a remount and explain the error immediately pub fn remount(self) -> Result<(), Error> { self.bare_remount().map_err(OSError::explain) } } impl fmt::Display for MountFlags { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let mut prefix = ""; if let Some(true) = self.bind { try!(write!(fmt, "{}bind", prefix)); prefix = ","; } if let Some(true) = self.readonly { try!(write!(fmt, "{}ro", prefix)); prefix = ","; } if let Some(true) = self.nodev { try!(write!(fmt, "{}nodev", prefix)); prefix = ","; } if let Some(true) = self.noexec { try!(write!(fmt, "{}noexec", prefix)); prefix = ","; } if let Some(true) = self.nosuid { try!(write!(fmt, "{}nosuid", prefix)); prefix = ","; } if let Some(true) = self.noatime { try!(write!(fmt, "{}noatime", prefix)); prefix = ","; } if let Some(true) = self.nodiratime { try!(write!(fmt, "{}nodiratime", prefix)); prefix = ","; } if let Some(true) = self.relatime { try!(write!(fmt, "{}relatime", prefix)); prefix = ","; } if let Some(true) = self.strictatime { try!(write!(fmt, "{}strictatime", prefix)); prefix = ","; } if let Some(true) = self.dirsync { try!(write!(fmt, "{}dirsync", prefix)); prefix = ","; } if let Some(true) = self.synchronous { try!(write!(fmt, "{}sync", prefix)); prefix = ","; } if let Some(true) = self.mandlock { try!(write!(fmt, "{}mand", prefix)); } Ok(()) } } impl fmt::Display for Remount { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if !self.flags.apply_to_flags(MsFlags::empty()).is_empty() { try!(write!(fmt, "{} ", self.flags)); } write!(fmt, "remount {:?}", &self.path) } } impl Explainable for Remount { fn explain(&self) -> String { [ format!("path: {}", exists(&self.path)), format!("{}", user()), ].join(", ") } } fn get_mountpoint_flags(path: &Path) -> Result { let mount_path = if path.is_absolute() { path.to_path_buf() } else { let mut mpath = try!(current_dir()); mpath.push(path); mpath }; let mut mountinfo_content = Vec::with_capacity(4 * 1024); let mountinfo_path = Path::new("/proc/self/mountinfo"); let mut mountinfo_file = try!(File::open(mountinfo_path) .map_err(|e| RemountError::Io( format!("Cannot open file: {:?}", mountinfo_path), e))); try!(mountinfo_file.read_to_end(&mut mountinfo_content) .map_err(|e| RemountError::Io( format!("Cannot read file: {:?}", mountinfo_path), e))); match get_mountpoint_flags_from(&mountinfo_content, &mount_path) { Ok(Some(flags)) => Ok(flags), Ok(None) => Err(RemountError::UnknownMountPoint(mount_path)), Err(e) => Err(e), } } fn get_mountpoint_flags_from(content: &[u8], path: &Path) -> Result, RemountError> { // iterate from the end of the mountinfo file for line in content.split(|c| *c == b'\n').rev() { let entry = parse_mount_point(line) .map_err(|e| RemountError::ParseMountInfo(e.0))?; if let Some(mount_point) = entry { if mount_point.mount_point == path { return Ok(Some(mount_point.get_mount_flags())); } } } Ok(None) } #[cfg(test)] mod test { use std::path::Path; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; use nix::mount::MsFlags; use Error; use super::{Remount, RemountError, MountFlags}; use super::{get_mountpoint_flags, get_mountpoint_flags_from}; #[test] fn test_mount_flags() { let flags = MountFlags { bind: Some(true), readonly: Some(true), nodev: Some(true), noexec: Some(true), nosuid: Some(true), noatime: Some(true), nodiratime: Some(true), relatime: Some(true), strictatime: Some(true), dirsync: Some(true), synchronous: Some(true), mandlock: Some(true), }; let bits = (MsFlags::MS_BIND | MsFlags::MS_RDONLY | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC | MsFlags::MS_NOSUID | MsFlags::MS_NOATIME | MsFlags::MS_NODIRATIME | MsFlags::MS_RELATIME | MsFlags::MS_STRICTATIME | MsFlags::MS_DIRSYNC | MsFlags::MS_SYNCHRONOUS | MsFlags::MS_MANDLOCK).bits(); assert_eq!(flags.apply_to_flags(MsFlags::empty()).bits(), bits); let flags = MountFlags { bind: Some(false), readonly: Some(false), nodev: Some(false), noexec: Some(false), nosuid: Some(false), noatime: Some(false), nodiratime: Some(false), relatime: Some(false), strictatime: Some(false), dirsync: Some(false), synchronous: Some(false), mandlock: Some(false), }; assert_eq!(flags.apply_to_flags(MsFlags::from_bits_truncate(bits)).bits(), 0); let flags = MountFlags::default(); assert_eq!(flags.apply_to_flags(MsFlags::from_bits_truncate(0)).bits(), 0); assert_eq!(flags.apply_to_flags(MsFlags::from_bits_truncate(bits)).bits(), bits); } #[test] fn test_remount() { let remount = Remount::new("/"); assert_eq!(format!("{}", remount), "remount \"/\""); let remount = Remount::new("/").readonly(true).nodev(true); assert_eq!(format!("{}", remount), "ro,nodev remount \"/\""); } #[test] fn test_get_mountpoint_flags_from() { let content = b"19 24 0:4 / /proc rw,nosuid,nodev,noexec,relatime shared:12 - proc proc rw"; let flags = get_mountpoint_flags_from(&content[..], Path::new("/proc")).unwrap().unwrap(); assert_eq!(flags, MsFlags::MS_NODEV | MsFlags::MS_NOEXEC | MsFlags::MS_NOSUID | MsFlags::MS_RELATIME); } #[test] fn test_get_mountpoint_flags_from_dups() { let content = b"11 18 0:4 / /tmp rw shared:28 - tmpfs tmpfs rw\n\ 12 18 0:6 / /tmp rw,nosuid,nodev shared:29 - tmpfs tmpfs rw\n"; let flags = get_mountpoint_flags_from(&content[..], Path::new("/tmp")).unwrap().unwrap(); assert_eq!(flags, MsFlags::MS_NOSUID | MsFlags::MS_NODEV); } #[test] fn test_get_mountpoint_flags() { assert!(get_mountpoint_flags(Path::new("/")).is_ok()); } #[test] fn test_get_mountpoint_flags_unknown() { let mount_point = Path::new(OsStr::from_bytes(b"/\xff")); let error = get_mountpoint_flags(mount_point).unwrap_err(); match error { RemountError::UnknownMountPoint(p) => assert_eq!(p, mount_point), _ => panic!(), } } #[test] fn test_remount_unknown_mountpoint() { let remount = Remount::new("/non-existent"); let error = remount.remount().unwrap_err(); let Error(_, e, msg) = error; match e.get_ref() { Some(e) => { assert_eq!( e.to_string(), "Cannot find mount point: \"/non-existent\""); }, _ => panic!(), } assert!(msg.starts_with( "Cannot find mount point: \"/non-existent\", path: missing, ")); } } libmount-0.1.15/src/tmpfs.rs010066400037200003720000000106451356324602500141520ustar0000000000000000use std::io::{Write, Cursor}; use std::fmt; use std::str::from_utf8; use std::ffi::{CString, CStr}; use std::path::Path; use libc::{uid_t, gid_t, mode_t}; use nix::mount::{MsFlags, mount}; use {OSError, Error}; use util::{path_to_cstring, as_path}; use explain::{Explainable, exists, user}; #[derive(Debug, Clone, Copy)] enum Size { Auto, Bytes(usize), Blocks(usize), } /// A tmpfs mount definition /// /// By default tmpfs is mounted with nosuid,nodev #[derive(Debug, Clone)] pub struct Tmpfs { target: CString, size: Size, nr_inodes: Option, mode: Option, uid: Option, gid: Option, flags: MsFlags, } impl Tmpfs { /// New tmpfs mount point with target path and default settngs pub fn new>(path: P) -> Tmpfs { Tmpfs { target: path_to_cstring(path.as_ref()), size: Size::Auto, nr_inodes: None, mode: None, uid: None, gid: None, flags: MsFlags::MS_NOSUID|MsFlags::MS_NODEV, } } /// Set size in bytes pub fn size_bytes(mut self, size: usize) -> Tmpfs { self.size = Size::Bytes(size); self } /// Set size in blocks of PAGE_CACHE_SIZE pub fn size_blocks(mut self, size: usize) -> Tmpfs { self.size = Size::Blocks(size); self } /// Maximum number of inodes pub fn nr_inodes(mut self, num: usize) -> Tmpfs { self.nr_inodes = Some(num); self } /// Set initial permissions of the root directory pub fn mode(mut self, mode: mode_t) -> Tmpfs { self.mode = Some(mode); self } /// Set initial owner of the root directory pub fn uid(mut self, uid: uid_t) -> Tmpfs { self.uid = Some(uid); self } /// Set initial group of the root directory pub fn gid(mut self, gid: gid_t) -> Tmpfs { self.gid = Some(gid); self } fn format_options(&self) -> Vec { let mut cur = Cursor::new(Vec::new()); match self.size { Size::Auto => {} Size::Bytes(x) => write!(cur, "size={}", x).unwrap(), Size::Blocks(x) => write!(cur, "nr_blocks={}", x).unwrap(), } if let Some(inodes) = self.nr_inodes { if cur.position() != 0 { cur.write(b",").unwrap(); } write!(cur, "nr_inodes={}", inodes).unwrap(); } if let Some(mode) = self.mode { if cur.position() != 0 { cur.write(b",").unwrap(); } write!(cur, "mode=0{:04o}", mode).unwrap(); } if let Some(uid) = self.uid { if cur.position() != 0 { cur.write(b",").unwrap(); } write!(cur, "uid={}", uid).unwrap(); } if let Some(gid) = self.gid { if cur.position() != 0 { cur.write(b",").unwrap(); } write!(cur, "gid={}", gid).unwrap(); } return cur.into_inner(); } /// Mount the tmpfs pub fn bare_mount(self) -> Result<(), OSError> { let mut options = self.format_options(); mount( Some(CStr::from_bytes_with_nul(b"tmpfs\0").unwrap()), &*self.target, Some(CStr::from_bytes_with_nul(b"tmpfs\0").unwrap()), self.flags, Some(&*options) ).map_err(|err| OSError::from_nix(err, Box::new(self))) } /// Mount the tmpfs and explain error immediately pub fn mount(self) -> Result<(), Error> { self.bare_mount().map_err(OSError::explain) } } impl fmt::Display for Tmpfs { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let opts = self.format_options(); write!(fmt, "tmpfs {} -> {:?}", from_utf8(&opts).unwrap(), as_path(&self.target)) } } impl Explainable for Tmpfs { fn explain(&self) -> String { [ format!("target: {}", exists(as_path(&self.target))), format!("{}", user()), ].join(", ") } } mod test { #[cfg(test)] use super::Tmpfs; #[test] fn test_tmpfs_options() { let fs = Tmpfs::new("/tmp") .size_bytes(1 << 20) .nr_inodes(1024) .mode(0o1777) .uid(1000) .gid(1000); assert_eq!(fs.format_options(), "size=1048576,nr_inodes=1024,mode=01777,uid=1000,gid=1000".as_bytes()) } } libmount-0.1.15/src/util.rs010066400037200003720000000004601356324602500137700ustar0000000000000000use std::path::Path; use std::ffi::{CStr, CString, OsStr}; use std::os::unix::ffi::OsStrExt; pub fn path_to_cstring(path: &Path) -> CString { return CString::new(path.as_os_str().as_bytes()).unwrap() } pub fn as_path(cstring: &CStr) -> &Path { OsStr::from_bytes(cstring.to_bytes()).as_ref() } libmount-0.1.15/vagga.yaml010066400037200003720000000016311356324602500136300ustar0000000000000000commands: cargo: !Command description: Run any cargo command container: ubuntu run: [cargo] make: !Command description: Build the library container: ubuntu run: [cargo, build] _bulk: !Command description: Run `bulk` command (for version bookkeeping) container: ubuntu run: [bulk] containers: ubuntu: setup: - !Ubuntu bionic - !Install [ca-certificates, build-essential, vim] - !TarInstall url: "https://static.rust-lang.org/dist/rust-1.26.0-x86_64-unknown-linux-gnu.tar.gz" script: "./install.sh --prefix=/usr \ --components=rustc,rust-std-x86_64-unknown-linux-gnu,cargo" - &bulk !Tar url: "https://github.com/tailhook/bulk/releases/download/v0.4.11/bulk-v0.4.11.tar.gz" sha256: b718bb8448e726690c94d98d004bf7575f7a429106ec26ad3faf11e0fd9a7978 path: / environ: HOME: /work/target USER: pc libmount-0.1.15/.cargo_vcs_info.json0000644000000001120000000000000130020ustar00{ "git": { "sha1": "0c824aa4a6be0f254606262c87d3ca0608bedc26" } } libmount-0.1.15/Cargo.lock0000644000000220330000000000000107630ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "aho-corasick" version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "argparse" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "atty" version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "bitflags" version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "cc" version = "1.0.47" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "cfg-if" version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "env_logger" version = "0.5.13" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)", "humantime 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "termcolor 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "humantime" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "lazy_static" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libc" version = "0.2.65" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libmount" version = "0.1.15" dependencies = [ "argparse 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)", "quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "log" version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "memchr" version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "nix" version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "cc 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)", "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "quick-error" version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "regex" version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)", "memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "regex-syntax 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)", "thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "regex-syntax" version = "0.6.12" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "termcolor" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "wincolor 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "thread_local" version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "void" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi" version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi-util" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "wincolor" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [metadata] "checksum aho-corasick 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "58fb5e95d83b38284460a5fda7d6470aa0b8844d283a0b614b8535e880800d2d" "checksum argparse 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "3f8ebf5827e4ac4fd5946560e6a99776ea73b596d80898f357007317a7141e47" "checksum atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)" = "1803c647a3ec87095e7ae7acfca019e98de5ec9a7d01343f611cf3152ed71a90" "checksum bitflags 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" "checksum cc 1.0.47 (registry+https://github.com/rust-lang/crates.io-index)" = "aa87058dce70a3ff5621797f1506cb837edd02ac4c0ae642b4542dce802908b8" "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" "checksum env_logger 0.5.13 (registry+https://github.com/rust-lang/crates.io-index)" = "15b0a4d2e39f8420210be8b27eeda28029729e2fd4291019455016c348240c38" "checksum humantime 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" "checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" "checksum libc 0.2.65 (registry+https://github.com/rust-lang/crates.io-index)" = "1a31a0627fdf1f6a39ec0dd577e101440b7db22672c0901fe00a9a6fbb5c24e8" "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" "checksum memchr 2.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "88579771288728879b57485cc7d6b07d648c9f0141eb955f8ab7f9d45394468e" "checksum nix 0.14.1 (registry+https://github.com/rust-lang/crates.io-index)" = "6c722bee1037d430d0f8e687bbdbf222f27cc6e4e68d5caf630857bb2b6dbdce" "checksum quick-error 1.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9274b940887ce9addde99c4eee6b5c44cc494b182b97e73dc8ffdcb3397fd3f0" "checksum regex 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dc220bd33bdce8f093101afe22a037b8eb0e5af33592e6a9caafff0d4cb81cbd" "checksum regex-syntax 0.6.12 (registry+https://github.com/rust-lang/crates.io-index)" = "11a7e20d1cce64ef2fed88b66d347f88bd9babb82845b2b858f3edbf59a4f716" "checksum termcolor 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "96d6098003bde162e4277c70665bd87c326f5a0c3f3fbfb285787fa482d54e6e" "checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b" "checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" "checksum winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8093091eeb260906a183e6ae1abdba2ef5ef2257a21801128899c3fc699229c6" "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "checksum winapi-util 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7168bab6e1daee33b4557efd0e95d5ca70a03706d39fa5f3fe7a236f584b03c9" "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" "checksum wincolor 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "96f5016b18804d24db43cebf3c77269e7569b8954a8464501c216cc5e070eaa9"