command-fds-0.3.3/.cargo_vcs_info.json0000644000000001361046102023000132510ustar { "git": { "sha1": "750b7be437f3063ed9e080bffd9050e293031e82" }, "path_in_vcs": "" }command-fds-0.3.3/.github/dependabot.yml000064400000000000000000000003171046102023000162100ustar 00000000000000version: 2 updates: - package-ecosystem: "cargo" directory: "/" schedule: interval: "weekly" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" command-fds-0.3.3/.github/workflows/rust.yml000064400000000000000000000024161046102023000171370ustar 00000000000000name: Rust on: push: branches: [main] pull_request: env: CARGO_TERM_COLOR: always jobs: build: permissions: checks: write runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - uses: taiki-e/install-action@nextest - name: Build run: cargo build - name: Run tests run: cargo nextest run - name: Run doctests run: cargo test --doc - name: Run clippy uses: actions-rs/clippy-check@v1 with: token: ${{ secrets.GITHUB_TOKEN }} args: --all-features format: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - name: Format Rust code run: cargo fmt --all -- --check coverage: runs-on: ubuntu-latest env: RUSTC_BOOTSTRAP: 1 steps: - uses: actions/checkout@v6 - uses: taiki-e/install-action@nextest - uses: taiki-e/install-action@cargo-llvm-cov - name: Run tests with coverage run: cargo llvm-cov nextest --all-features --codecov --output-path codecov-report.json - name: Upload coverage to codecov.io uses: codecov/codecov-action@v6 with: fail_ci_if_error: true files: codecov-report.json token: ${{ secrets.CODECOV_TOKEN }} command-fds-0.3.3/.gitignore000064400000000000000000000000211046102023000140000ustar 00000000000000/target .vscode/ command-fds-0.3.3/CHANGELOG.md000064400000000000000000000001701046102023000136260ustar 00000000000000# Changelog ## 0.3.3 ### New features - Added `inherited` module for taking ownership of inherited file descriptors. command-fds-0.3.3/CONTRIBUTING.md000064400000000000000000000021171046102023000142510ustar 00000000000000# How to Contribute We'd love to accept your patches and contributions to this project. There are just a few small guidelines you need to follow. ## Contributor License Agreement Contributions to this project must be accompanied by a Contributor License Agreement (CLA). You (or your employer) retain the copyright to your contribution; this simply gives us permission to use and redistribute your contributions as part of the project. Head over to to see your current agreements on file or to sign a new one. You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again. ## Code reviews All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using pull requests. ## Community Guidelines This project follows [Google's Open Source Community Guidelines](https://opensource.google/conduct/). command-fds-0.3.3/Cargo.lock0000644000000324631046102023000112340ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "anyhow" version = "1.0.102" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" [[package]] name = "bitflags" version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" [[package]] name = "bytes" version = "1.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cfg_aliases" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "command-fds" version = "0.3.3" dependencies = [ "nix", "tempfile", "thiserror", "tokio", ] [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", "windows-sys", ] [[package]] name = "fastrand" version = "2.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" [[package]] name = "foldhash" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" [[package]] name = "getrandom" version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" dependencies = [ "cfg-if", "libc", "r-efi", "wasip2", "wasip3", ] [[package]] name = "hashbrown" version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" dependencies = [ "foldhash", ] [[package]] name = "hashbrown" version = "0.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "id-arena" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" [[package]] name = "indexmap" version = "2.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", "hashbrown 0.17.0", "serde", "serde_core", ] [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "leb128fmt" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" [[package]] name = "libc" version = "0.2.184" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" [[package]] name = "linux-raw-sys" version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "log" version = "0.4.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897" [[package]] name = "memchr" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" [[package]] name = "mio" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1" dependencies = [ "libc", "wasi", "windows-sys", ] [[package]] name = "nix" version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d6d0705320c1e6ba1d912b5e37cf18071b6c2e9b7fa8215a1e8a7651966f5d3" dependencies = [ "bitflags", "cfg-if", "cfg_aliases", "libc", ] [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" [[package]] name = "pin-project-lite" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" [[package]] name = "prettyplease" version = "0.2.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6837b9e10d61f45f987d50808f83d1ee3d206c66acf650c3e4ae2e1f6ddedf55" dependencies = [ "proc-macro2", "syn", ] [[package]] name = "proc-macro2" version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "r-efi" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rustix" version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys", ] [[package]] name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" [[package]] name = "serde" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", ] [[package]] name = "serde_core" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.149" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86" dependencies = [ "itoa", "memchr", "serde", "serde_core", "zmij", ] [[package]] name = "signal-hook-registry" version = "1.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410" dependencies = [ "libc", ] [[package]] name = "syn" version = "2.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tempfile" version = "3.27.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", "getrandom", "once_cell", "rustix", "windows-sys", ] [[package]] name = "thiserror" version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" version = "2.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "tokio" version = "1.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bd1c4c0fc4a7ab90fc15ef6daaa3ec3b893f004f915f2392557ed23237820cd" dependencies = [ "bytes", "libc", "mio", "pin-project-lite", "signal-hook-registry", "windows-sys", ] [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "unicode-xid" version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasip2" version = "1.0.2+wasi-0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" dependencies = [ "wit-bindgen", ] [[package]] name = "wasip3" version = "0.4.0+wasi-0.3.0-rc-2026-01-06" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" dependencies = [ "wit-bindgen", ] [[package]] name = "wasm-encoder" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" dependencies = [ "leb128fmt", "wasmparser", ] [[package]] name = "wasm-metadata" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", "indexmap", "wasm-encoder", "wasmparser", ] [[package]] name = "wasmparser" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags", "hashbrown 0.15.5", "indexmap", "semver", ] [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" version = "0.61.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" dependencies = [ "windows-link", ] [[package]] name = "wit-bindgen" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" dependencies = [ "wit-bindgen-rust-macro", ] [[package]] name = "wit-bindgen-core" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" dependencies = [ "anyhow", "heck", "wit-parser", ] [[package]] name = "wit-bindgen-rust" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck", "indexmap", "prettyplease", "syn", "wasm-metadata", "wit-bindgen-core", "wit-component", ] [[package]] name = "wit-bindgen-rust-macro" version = "0.51.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" dependencies = [ "anyhow", "prettyplease", "proc-macro2", "quote", "syn", "wit-bindgen-core", "wit-bindgen-rust", ] [[package]] name = "wit-component" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags", "indexmap", "log", "serde", "serde_derive", "serde_json", "wasm-encoder", "wasm-metadata", "wasmparser", "wit-parser", ] [[package]] name = "wit-parser" version = "0.244.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", "indexmap", "log", "semver", "serde", "serde_derive", "serde_json", "unicode-xid", "wasmparser", ] [[package]] name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" command-fds-0.3.3/Cargo.toml0000644000000025751046102023000112600ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2024" name = "command-fds" version = "0.3.3" authors = ["Andrew Walbran "] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A library for passing arbitrary file descriptors when spawning child processes." readme = "README.md" keywords = [ "command", "process", "child", "subprocess", "fd", ] categories = ["os::unix-apis"] license = "Apache-2.0" repository = "https://github.com/google/command-fds/" [features] default = [] tokio = ["dep:tokio"] [lib] name = "command_fds" path = "src/lib.rs" [[example]] name = "spawn" path = "examples/spawn.rs" [dependencies.nix] version = "0.31.2" features = ["fs"] [dependencies.thiserror] version = "2.0.18" [dependencies.tokio] version = "1.51.0" features = ["process"] optional = true default-features = false [dev-dependencies.tempfile] version = "3.27.0" command-fds-0.3.3/Cargo.toml.orig000064400000000000000000000012221046102023000147030ustar 00000000000000[package] name = "command-fds" version = "0.3.3" edition = "2024" authors = ["Andrew Walbran "] license = "Apache-2.0" description = "A library for passing arbitrary file descriptors when spawning child processes." repository = "https://github.com/google/command-fds/" keywords = ["command", "process", "child", "subprocess", "fd"] categories = ["os::unix-apis"] [dependencies] nix = { version = "0.31.2", features = ["fs"] } thiserror = "2.0.18" tokio = { version = "1.51.0", optional = true, default-features = false, features = [ "process", ] } [dev-dependencies] tempfile = "3.27.0" [features] default = [] tokio = ["dep:tokio"] command-fds-0.3.3/LICENSE000064400000000000000000000261351046102023000130330ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. command-fds-0.3.3/README.md000064400000000000000000000042101046102023000132730ustar 00000000000000# command-fds [![crates.io page](https://img.shields.io/crates/v/command-fds.svg)](https://crates.io/crates/command-fds) [![docs.rs page](https://docs.rs/command-fds/badge.svg)](https://docs.rs/command-fds) A library for passing arbitrary file descriptors when spawning child processes, and safely taking ownership of passed file descriptors within such a child process. ## Example In the parent process: ```rust use command_fds::{CommandFdExt, FdMapping}; use std::fs::File; use std::io::stdin; use std::os::fd::AsFd; use std::os::unix::io::AsRawFd; use std::process::Command; // Open a file. let file = File::open("Cargo.toml").unwrap(); // Prepare to run `ls -l /proc/self/fd` with some FDs mapped. let mut command = Command::new("ls"); command.arg("-l").arg("/proc/self/fd"); command .fd_mappings(vec![ // Map `file` as FD 3 in the child process. FdMapping { parent_fd: file.into(), child_fd: 3, }, // Map this process's stdin as FD 5 in the child process. FdMapping { parent_fd: stdin().as_fd().try_clone_to_owned().unwrap(), child_fd: 5, }, ]) .unwrap(); // Spawn the child process. let mut child = command.spawn().unwrap(); child.wait().unwrap(); ``` In the child process: ```rust use command_fds::inherited::{init_inherited_fds, take_fd_ownership}; fn main() { // SAFETY: This is called before anything else in the program. unsafe { init_inherited_fds(); } // Get an OwnedFd for the file that was passed as FD 3 by the parent. let inherited_file = take_fd_ownership(3).unwrap(); // Trying to take the same file descriptor again will return an error. take_fd_ownership(3).expect_err("Can't take the same FD twice"); // Trying to take a file descriptor which wasn't passed will also return an error. take_fd_ownership(4).expect_err("Can't take an FD which wasn't inherited"); } ``` ## License Licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). ## Contributing If you want to contribute to the project, see details of [how we accept contributions](CONTRIBUTING.md). command-fds-0.3.3/examples/spawn.rs000064400000000000000000000044561046102023000153440ustar 00000000000000// Copyright 2021, The Android Open Source Project // // 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. use command_fds::{CommandFdExt, FdMapping}; use std::fs::{File, read_dir, read_link}; use std::io::stdin; use std::os::fd::AsFd; use std::os::unix::process::CommandExt; use std::process::Command; use std::thread::sleep; use std::time::Duration; /// Prints out a list of all open file descriptors. fn list_fds() { let dir = read_dir("/proc/self/fd").unwrap(); for entry in dir { let entry = entry.unwrap(); let target = read_link(entry.path()).unwrap(); println!("{:?} -> {:?}", entry.file_name(), target); } } fn main() { list_fds(); // Open a file. let file = File::open("Cargo.toml").unwrap(); println!("File: {:?}", file); list_fds(); // Prepare to run `ls -l /proc/self/fd` with some FDs mapped. let mut command = Command::new("ls"); command.arg("-l").arg("/proc/self/fd"); let stdin_fd = stdin().as_fd().try_clone_to_owned().unwrap(); command .fd_mappings(vec![ // Map `file` as FD 3 in the child process. FdMapping { parent_fd: file.into(), child_fd: 3, }, // Map this process's stdin as FD 5 in the child process. FdMapping { parent_fd: stdin_fd, child_fd: 5, }, ]) .unwrap(); unsafe { command.pre_exec(|| { println!("pre_exec"); list_fds(); Ok(()) }); } // Spawn the child process. println!("Spawning command"); let mut child = command.spawn().unwrap(); sleep(Duration::from_millis(100)); println!("Spawned"); list_fds(); println!("Waiting for command"); println!("{:?}", child.wait().unwrap()); } command-fds-0.3.3/src/inherited.rs000064400000000000000000000211341046102023000151300ustar 00000000000000// Copyright 2024, The Android Open Source Project // // 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. //! Utilities for safely obtaining `OwnedFd`s for inherited file descriptors. use nix::{ fcntl::{F_SETFD, FdFlag, fcntl}, libc, }; use std::{ collections::HashMap, fs::{canonicalize, read_dir}, os::fd::{FromRawFd, OwnedFd, RawFd}, sync::{Mutex, OnceLock}, }; use thiserror::Error; static INHERITED_FDS: OnceLock>>> = OnceLock::new(); /// Errors that can occur while taking an ownership of `RawFd` #[derive(Debug, PartialEq, Error)] pub enum InheritedFdError { /// init_inherited_fds() not called #[error("init_inherited_fds() not called")] NotInitialized, /// Ownership already taken #[error("Ownership of FD {0} is already taken")] OwnershipTaken(RawFd), /// Not an inherited file descriptor #[error("FD {0} is either invalid file descriptor or not an inherited one")] FileDescriptorNotInherited(RawFd), } /// Takes ownership of all open file descriptors in this process other than standard /// input/output/error, so that they can later be obtained by calling [`take_fd_ownership`]. /// /// Sets the `FD_CLOEXEC` flag on all of these file descriptors. /// /// # Safety /// /// This must be called very early in the program, before the ownership of any file descriptors /// (except stdin/out/err) is taken. pub unsafe fn init_inherited_fds() -> Result<(), std::io::Error> { let mut fds = HashMap::new(); let fd_path = canonicalize("/proc/self/fd")?; for entry in read_dir(&fd_path)? { let entry = entry?; // Files in /prod/self/fd are guaranteed to be numbers. So parsing is always successful. let file_name = entry.file_name(); let raw_fd = file_name.to_str().unwrap().parse::().unwrap(); // We don't take ownership of the stdio FDs as the Rust runtime owns them. if [libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO].contains(&raw_fd) { continue; } // Exceptional case: /proc/self/fd/* may be a dir fd created by read_dir just above. Since // the file descriptor is owned by read_dir (and thus closed by it), we shouldn't take // ownership to it. if entry.path().read_link()? == fd_path { continue; } // SAFETY: /proc/self/fd/* are file descriptors that are open. If `init_inherited_fds()` was // called at the very beginning of the program execution (as requested by the safety // requirement of this function), this is the first time to claim the ownership of these // file descriptors. let owned_fd = unsafe { OwnedFd::from_raw_fd(raw_fd) }; fcntl(&owned_fd, F_SETFD(FdFlag::FD_CLOEXEC))?; fds.insert(raw_fd, Some(owned_fd)); } INHERITED_FDS .set(Mutex::new(fds)) .or(Err(std::io::Error::other( "Inherited fds were already initialized", ))) } /// Takes the ownership of the given `RawFd` and returns an `OwnedFd` for it. /// /// The returned FD will have the `FD_CLOEXEC` flag set. /// /// An error is returned when the ownership was already taken (by a prior call to this /// function with the same `RawFd`) or `RawFd` is not an inherited file descriptor. pub fn take_fd_ownership(raw_fd: RawFd) -> Result { let mut fds = INHERITED_FDS .get() .ok_or(InheritedFdError::NotInitialized)? .lock() .unwrap(); if let Some(value) = fds.get_mut(&raw_fd) { if let Some(owned_fd) = value.take() { Ok(owned_fd) } else { Err(InheritedFdError::OwnershipTaken(raw_fd)) } } else { Err(InheritedFdError::FileDescriptorNotInherited(raw_fd)) } } #[cfg(test)] mod test { use super::*; use nix::unistd::close; use std::{ io, os::fd::{AsRawFd, IntoRawFd}, }; use tempfile::tempfile; struct Fixture { fds: Vec, } impl Fixture { fn setup(num_fds: usize) -> Result { let mut fds = Vec::new(); for _ in 0..num_fds { fds.push(tempfile()?.into_raw_fd()); } Ok(Fixture { fds }) } fn open_new_file(&mut self) -> Result { let raw_fd = tempfile()?.into_raw_fd(); self.fds.push(raw_fd); Ok(raw_fd) } } impl Drop for Fixture { fn drop(&mut self) { self.fds.iter().for_each(|fd| { let _ = close(*fd); }); } } fn is_fd_opened(raw_fd: RawFd) -> bool { unsafe { libc::fcntl(raw_fd, libc::F_GETFD) != -1 } } #[test] fn happy_case() { let fixture = Fixture::setup(2).unwrap(); let f0 = fixture.fds[0]; let f1 = fixture.fds[1]; // SAFETY: assume files opened by Fixture are inherited ones unsafe { init_inherited_fds().unwrap(); } let f0_owned = take_fd_ownership(f0).unwrap(); let f1_owned = take_fd_ownership(f1).unwrap(); assert_eq!(f0, f0_owned.as_raw_fd()); assert_eq!(f1, f1_owned.as_raw_fd()); drop(f0_owned); drop(f1_owned); assert!(!is_fd_opened(f0)); assert!(!is_fd_opened(f1)); } #[test] fn access_non_inherited_fd() { let mut fixture = Fixture::setup(2).unwrap(); // SAFETY: assume files opened by Fixture are inherited ones unsafe { init_inherited_fds().unwrap(); } let f = fixture.open_new_file().unwrap(); assert_eq!( take_fd_ownership(f).err(), Some(InheritedFdError::FileDescriptorNotInherited(f)) ); } #[test] fn call_init_inherited_fds_multiple_times() { let _ = Fixture::setup(2).unwrap(); // SAFETY: assume files opened by Fixture are inherited ones unsafe { init_inherited_fds().unwrap(); } // SAFETY: for testing let res = unsafe { init_inherited_fds() }; assert!(res.is_err()); } #[test] fn access_without_init_inherited_fds() { let fixture = Fixture::setup(2).unwrap(); let f = fixture.fds[0]; assert_eq!( take_fd_ownership(f).err(), Some(InheritedFdError::NotInitialized) ); } #[test] fn double_ownership() { let fixture = Fixture::setup(2).unwrap(); let f = fixture.fds[0]; // SAFETY: assume files opened by Fixture are inherited ones unsafe { init_inherited_fds().unwrap(); } let f_owned = take_fd_ownership(f).unwrap(); let f_double_owned = take_fd_ownership(f); assert_eq!( f_double_owned.err(), Some(InheritedFdError::OwnershipTaken(f)), ); // just to highlight that f_owned is kept alive when the second call to take_fd_ownership // is made. drop(f_owned); } #[test] fn take_drop_retake() { let fixture = Fixture::setup(2).unwrap(); let f = fixture.fds[0]; // SAFETY: assume files opened by Fixture are inherited ones unsafe { init_inherited_fds().unwrap(); } let f_owned = take_fd_ownership(f).unwrap(); drop(f_owned); let f_double_owned = take_fd_ownership(f); assert_eq!( f_double_owned.err(), Some(InheritedFdError::OwnershipTaken(f)), ); } #[test] fn cloexec() { let fixture = Fixture::setup(2).unwrap(); let f = fixture.fds[0]; let res = unsafe { libc::fcntl(f.as_raw_fd(), libc::F_SETFD, 0) }; assert_ne!(res, -1); // SAFETY: assume files opened by Fixture are inherited ones unsafe { init_inherited_fds().unwrap(); } // SAFETY: F_GETFD doesn't need any extra parameters. let flags = unsafe { libc::fcntl(f.as_raw_fd(), libc::F_GETFD) }; assert_ne!(flags, -1); // FD_CLOEXEC should be set by init_inherited_fds assert_eq!(flags, FdFlag::FD_CLOEXEC.bits()); } } command-fds-0.3.3/src/lib.rs000064400000000000000000000363541046102023000137350ustar 00000000000000// Copyright 2021, The Android Open Source Project // // 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. //! A library for passing arbitrary file descriptors when spawning child processes, and safely //! taking ownership of passed file descriptors within such a child process. //! //! # Example //! //! In the parent process: //! //! ``` //! use command_fds::{CommandFdExt, FdMapping}; //! use std::fs::File; //! use std::io::stdin; //! use std::os::fd::AsFd; //! use std::os::unix::io::AsRawFd; //! use std::process::Command; //! //! // Open a file. //! let file = File::open("Cargo.toml").unwrap(); //! //! // Prepare to run `ls -l /proc/self/fd` with some FDs mapped. //! let mut command = Command::new("ls"); //! command.arg("-l").arg("/proc/self/fd"); //! command //! .fd_mappings(vec![ //! // Map `file` as FD 3 in the child process. //! FdMapping { //! parent_fd: file.into(), //! child_fd: 3, //! }, //! // Map this process's stdin as FD 5 in the child process. //! FdMapping { //! parent_fd: stdin().as_fd().try_clone_to_owned().unwrap(), //! child_fd: 5, //! }, //! ]) //! .unwrap(); //! //! // Spawn the child process. //! let mut child = command.spawn().unwrap(); //! child.wait().unwrap(); //! ``` //! //! In the child process: //! //! ```no_run //! use command_fds::inherited::{init_inherited_fds, take_fd_ownership}; //! //! fn main() { //! // SAFETY: This is called before anything else in the program. //! unsafe { //! init_inherited_fds(); //! } //! //! // Get an OwnedFd for the file that was passed as FD 3 by the parent. //! let inherited_file = take_fd_ownership(3).unwrap(); //! //! // Trying to take the same file descriptor again will return an error. //! take_fd_ownership(3).expect_err("Can't take the same FD twice"); //! //! // Trying to take a file descriptor which wasn't passed will also return an error. //! take_fd_ownership(4).expect_err("Can't take an FD which wasn't inherited"); //! } //! ``` pub mod inherited; #[cfg(feature = "tokio")] pub mod tokio; use nix::fcntl::{FcntlArg, FdFlag, fcntl}; use nix::unistd::dup2_raw; use std::cmp::max; use std::io; use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd}; use std::os::unix::io::RawFd; use std::os::unix::process::CommandExt; use std::process::Command; use thiserror::Error; /// A mapping from a file descriptor in the parent to a file descriptor in the child, to be applied /// when spawning a child process. /// /// This takes ownership of the `parent_fd` to ensure that it is kept open until after the child is /// spawned. #[derive(Debug)] pub struct FdMapping { pub parent_fd: OwnedFd, pub child_fd: RawFd, } /// Error setting up FD mappings, because there were two or more mappings for the same child FD. #[derive(Copy, Clone, Debug, Eq, Error, PartialEq)] #[error("Two or more mappings for the same child FD")] pub struct FdMappingCollision; /// Extension to add file descriptor mappings to a [`Command`]. pub trait CommandFdExt { /// Adds the given set of file descriptors to the command. /// /// Warning: Calling this more than once on the same command may result in unexpected behaviour. /// In particular, it is not possible to check that two mappings applied separately don't use /// the same `child_fd`. If there is such a collision then one will apply and the other will be /// lost. /// /// Note that the `Command` takes ownership of the file descriptors, which means that they won't /// be closed in the parent process until the `Command` is dropped. fn fd_mappings(&mut self, mappings: Vec) -> Result<&mut Self, FdMappingCollision>; /// Adds the given set of file descriptors to be passed on to the child process when the command /// is run. /// /// Note that the `Command` takes ownership of the file descriptors, which means that they won't /// be closed in the parent process until the `Command` is dropped. fn preserved_fds(&mut self, fds: Vec) -> &mut Self; } impl CommandFdExt for Command { fn fd_mappings( &mut self, mut mappings: Vec, ) -> Result<&mut Self, FdMappingCollision> { let child_fds = validate_child_fds(&mappings)?; // Register the callback to apply the mappings after forking but before execing. // Safety: `map_fds` will not allocate, so it is safe to call from this hook. unsafe { // If the command is run more than once, the closure will be called multiple times but // in different forked processes, which will have different copies of `mappings`. So // their changes to it shouldn't be visible to each other. self.pre_exec(move || map_fds(&mut mappings, &child_fds)); } Ok(self) } fn preserved_fds(&mut self, fds: Vec) -> &mut Self { unsafe { self.pre_exec(move || preserve_fds(&fds)); } self } } /// Validates that there are no conflicting mappings to the same child FD. fn validate_child_fds(mappings: &[FdMapping]) -> Result, FdMappingCollision> { let mut child_fds: Vec = mappings.iter().map(|mapping| mapping.child_fd).collect(); child_fds.sort_unstable(); child_fds.dedup(); if child_fds.len() != mappings.len() { return Err(FdMappingCollision); } Ok(child_fds) } // This function must not do any allocation, as it is called from the pre_exec hook. fn map_fds(mappings: &mut [FdMapping], child_fds: &[RawFd]) -> io::Result<()> { if mappings.is_empty() { // No need to do anything, and finding first_unused_fd would fail. return Ok(()); } // Find the first FD which is higher than any parent or child FD in the mapping, so we can // safely use it and higher FDs as temporary FDs. There may be other files open with these FDs, // so we still need to ensure we don't conflict with them. let first_safe_fd = mappings .iter() .map(|mapping| max(mapping.parent_fd.as_raw_fd(), mapping.child_fd)) .max() .unwrap() + 1; // If any parent FDs conflict with child FDs, then first duplicate them to a temporary FD which // is clear of either range. Mappings to the same FD are fine though, we can handle them by just // removing the FD_CLOEXEC flag from the existing (parent) FD. for mapping in mappings.iter_mut() { if child_fds.contains(&mapping.parent_fd.as_raw_fd()) && mapping.parent_fd.as_raw_fd() != mapping.child_fd { let parent_fd = fcntl(&mapping.parent_fd, FcntlArg::F_DUPFD_CLOEXEC(first_safe_fd))?; // SAFETY: We just created `parent_fd` so we can take ownership of it. unsafe { mapping.parent_fd = OwnedFd::from_raw_fd(parent_fd); } } } // Now we can actually duplicate FDs to the desired child FDs. for mapping in mappings { if mapping.child_fd == mapping.parent_fd.as_raw_fd() { // Remove the FD_CLOEXEC flag, so the FD will be kept open when exec is called for the // child. fcntl(&mapping.parent_fd, FcntlArg::F_SETFD(FdFlag::empty()))?; } else { // This closes child_fd if it is already open as something else, and clears the // FD_CLOEXEC flag on child_fd. // SAFETY: `dup2_raw` returns an `OwnedFd` which takes ownership of the child FD and // would close it when it is dropped. We avoid this by calling `into_raw_fd` to give up // ownership again. unsafe { let _ = dup2_raw(&mapping.parent_fd, mapping.child_fd)?.into_raw_fd(); } } } Ok(()) } fn preserve_fds(fds: &[OwnedFd]) -> io::Result<()> { for fd in fds { // Remove the FD_CLOEXEC flag, so the FD will be kept open when exec is called for the // child. fcntl(fd, FcntlArg::F_SETFD(FdFlag::empty()))?; } Ok(()) } #[cfg(test)] mod tests { use super::*; use nix::unistd::close; use std::collections::HashSet; use std::fs::{File, read_dir}; use std::os::unix::io::AsRawFd; use std::process::Output; use std::str; use std::sync::Once; static SETUP: Once = Once::new(); #[test] fn conflicting_mappings() { setup(); let mut command = Command::new("ls"); let file1 = File::open("testdata/file1.txt").unwrap(); let file2 = File::open("testdata/file2.txt").unwrap(); // Mapping two different FDs to the same FD isn't allowed. assert!( command .fd_mappings(vec![ FdMapping { child_fd: 4, parent_fd: file1.into(), }, FdMapping { child_fd: 4, parent_fd: file2.into(), }, ]) .is_err() ); } #[test] fn no_mappings() { setup(); let mut command = Command::new("ls"); command.arg("/proc/self/fd"); assert!(command.fd_mappings(vec![]).is_ok()); let output = command.output().unwrap(); expect_fds(&output, &[0, 1, 2, 3], 0); } #[test] fn none_preserved() { setup(); let mut command = Command::new("ls"); command.arg("/proc/self/fd"); command.preserved_fds(vec![]); let output = command.output().unwrap(); expect_fds(&output, &[0, 1, 2, 3], 0); } #[test] fn one_mapping() { setup(); let mut command = Command::new("ls"); command.arg("/proc/self/fd"); let file = File::open("testdata/file1.txt").unwrap(); // Map the file an otherwise unused FD. assert!( command .fd_mappings(vec![FdMapping { parent_fd: file.into(), child_fd: 5, },]) .is_ok() ); let output = command.output().unwrap(); expect_fds(&output, &[0, 1, 2, 3, 5], 0); } #[test] #[ignore = "flaky on GitHub"] fn one_preserved() { setup(); let mut command = Command::new("ls"); command.arg("/proc/self/fd"); let file = File::open("testdata/file1.txt").unwrap(); let file_fd: OwnedFd = file.into(); let raw_file_fd = file_fd.as_raw_fd(); assert!(raw_file_fd > 3); command.preserved_fds(vec![file_fd]); let output = command.output().unwrap(); expect_fds(&output, &[0, 1, 2, 3, raw_file_fd], 0); } #[test] fn swap_mappings() { setup(); let mut command = Command::new("ls"); command.arg("/proc/self/fd"); let file1 = File::open("testdata/file1.txt").unwrap(); let file2 = File::open("testdata/file2.txt").unwrap(); let fd1: OwnedFd = file1.into(); let fd2: OwnedFd = file2.into(); let fd1_raw = fd1.as_raw_fd(); let fd2_raw = fd2.as_raw_fd(); // Map files to each other's FDs, to ensure that the temporary FD logic works. assert!( command .fd_mappings(vec![ FdMapping { parent_fd: fd1, child_fd: fd2_raw, }, FdMapping { parent_fd: fd2, child_fd: fd1_raw, }, ]) .is_ok(), ); let output = command.output().unwrap(); // Expect one more Fd for the /proc/self/fd directory. We can't predict what number it will // be assigned, because 3 might or might not be taken already by fd1 or fd2. expect_fds(&output, &[0, 1, 2, fd1_raw, fd2_raw], 1); } #[test] fn one_to_one_mapping() { setup(); let mut command = Command::new("ls"); command.arg("/proc/self/fd"); let file1 = File::open("testdata/file1.txt").unwrap(); let file2 = File::open("testdata/file2.txt").unwrap(); let fd1: OwnedFd = file1.into(); let fd1_raw = fd1.as_raw_fd(); // Map file1 to the same FD it currently has, to ensure the special case for that works. assert!( command .fd_mappings(vec![FdMapping { parent_fd: fd1, child_fd: fd1_raw, }]) .is_ok() ); let output = command.output().unwrap(); // Expect one more Fd for the /proc/self/fd directory. We can't predict what number it will // be assigned, because 3 might or might not be taken already by fd1 or fd2. expect_fds(&output, &[0, 1, 2, fd1_raw], 1); // Keep file2 open until the end, to ensure that it's not passed to the child. drop(file2); } #[test] fn map_stdin() { setup(); let mut command = Command::new("cat"); let file = File::open("testdata/file1.txt").unwrap(); // Map the file to stdin. assert!( command .fd_mappings(vec![FdMapping { parent_fd: file.into(), child_fd: 0, },]) .is_ok() ); let output = command.output().unwrap(); assert!(output.status.success()); assert_eq!(output.stdout, b"test 1"); } /// Parse the output of ls into a set of filenames fn parse_ls_output(output: &[u8]) -> HashSet { str::from_utf8(output) .unwrap() .split_terminator("\n") .map(str::to_owned) .collect() } /// Check that the output of `ls /proc/self/fd` contains the expected set of FDs, plus exactly /// `extra` extra FDs. fn expect_fds(output: &Output, expected_fds: &[RawFd], extra: usize) { assert!(output.status.success()); let expected_fds: HashSet = expected_fds.iter().map(RawFd::to_string).collect(); let fds = parse_ls_output(&output.stdout); if extra == 0 { assert_eq!(fds, expected_fds); } else { assert!(expected_fds.is_subset(&fds)); assert_eq!(fds.len(), expected_fds.len() + extra); } } fn setup() { SETUP.call_once(close_excess_fds); } /// Close all file descriptors apart from stdin, stdout and stderr. /// /// This is necessary because GitHub Actions opens a bunch of others for some reason. fn close_excess_fds() { let dir = read_dir("/proc/self/fd").unwrap(); for entry in dir { let entry = entry.unwrap(); let fd: RawFd = entry.file_name().to_str().unwrap().parse().unwrap(); if fd > 3 { close(fd).unwrap(); } } } } command-fds-0.3.3/src/tokio.rs000064400000000000000000000012401046102023000142760ustar 00000000000000use crate::{ CommandFdExt, FdMapping, FdMappingCollision, map_fds, preserve_fds, validate_child_fds, }; use std::os::fd::OwnedFd; use tokio::process::Command; impl CommandFdExt for Command { fn fd_mappings( &mut self, mut mappings: Vec, ) -> Result<&mut Self, FdMappingCollision> { let child_fds = validate_child_fds(&mappings)?; unsafe { self.pre_exec(move || map_fds(&mut mappings, &child_fds)); } Ok(self) } fn preserved_fds(&mut self, fds: Vec) -> &mut Self { unsafe { self.pre_exec(move || preserve_fds(&fds)); } self } } command-fds-0.3.3/testdata/file1.txt000064400000000000000000000000061046102023000153650ustar 00000000000000test 1command-fds-0.3.3/testdata/file2.txt000064400000000000000000000000061046102023000153660ustar 00000000000000test 2