[
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "\n<!--\nBefore submitting a PR:\n\n1. Link the associated issue (i.e., `closes #<issueNum>` in description)\n2. Ensure that you have met the expected acceptance criteria\n3. Ensure that you have created sufficient tests\n4. Ensure that you have updated all affected documentation\n-->\n\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "---\nversion: 2\nupdates:\n  - package-ecosystem: \"github-actions\"\n    directory: \"/\"\n    schedule:\n      interval: weekly\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Test\n\non:\n  # Allow running this workflow manually from the Actions tab\n  workflow_dispatch:\n  pull_request:\n  push:\n    branches:\n      - main\n    tags:\n      - '*'\n  # Run weekly on the default branch to make sure it always builds with the latest rust release\n  schedule:\n    - cron: '30 5 * * 1'\n\njobs:\n  test-matrix:\n    strategy:\n      fail-fast: false\n      matrix:\n        os:\n          - ubuntu-latest\n          - macos-latest\n    runs-on: ${{ matrix.os }}\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v6\n\n      - name: Install Rust toolchain\n        run: |\n          curl --proto '=https' --tlsv1.2 -sSfL https://sh.rustup.rs \\\n            | sh -s -- -y --default-toolchain stable --profile minimal -c clippy\n          echo \"$HOME/.cargo/bin\" >> \"$GITHUB_PATH\"\n\n      - name: Test Stable\n        run: |\n          # On Ubuntu use busybox to bypass user namespace restrictions.\n          if command -v busybox; then\n            busybox sh -c \"cargo +stable test\"\n          else\n            cargo +stable test\n          fi\n\n      - name: Test Oldstable\n        run: |\n          oldstable=$(cat Cargo.toml | grep rust-version | sed 's/.*\"\\(.*\\)\".*/\\1/')\n          rustup toolchain install --profile minimal $oldstable\n\n          # On Ubuntu use busybox to bypass user namespace restrictions.\n          if command -v busybox; then\n            busybox sh -c \"cargo +$oldstable test\"\n          else\n            cargo \"+$oldstable\" test\n          fi\n\n      - name: Clippy\n        run: cargo +stable clippy\n\n      - name: Rustfmt\n        run: |\n          rustup toolchain install nightly -c rustfmt\n          cargo +nightly fmt -- --check\n\n  # This job reports the results of the test jobs above and is used\n  # to enforce status checks in the repo settings without needing\n  # to update those settings every time the test jobs are updated.\n  test-rollup:\n    name: Test rollup\n    runs-on: ubuntu-latest\n    if: always()\n    needs: test-matrix\n    steps:\n      - name: Check for test jobs failure or cancellation\n        if: contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled')\n        run: exit 1\n"
  },
  {
    "path": ".gitignore",
    "content": "/target\n/Cargo.lock\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nNotable changes to Birdcage are documented in this file.\n\nThe sections should follow the order `Packaging`, `Added`, `Changed`, `Fixed` and `Removed`.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).\n\n## [0.8.1] - 2024-04-19\n\n### Fixed\n\n- Conversion from Birdcage's to STD's `Command` inheriting all STDIO\n\n## [0.8.0] - 2024-04-19\n\n### Changed\n\n- `Sandbox::spawn` now takes a `birdcage::process::Command`\n\n### Fixed\n\n- (Linux) Sandboxed process not killed when parent is terminated with a signal\n\n## [0.7.1] - 2024-02-07\n\n### Changed\n\n- (Linux) Improved error message with unsupported Kernel versions\n\n## [0.7.0] - 2023-11-30\n\n### Added\n\n- (Linux) PID namespace support\n\n### Fixed\n\n- (Linux) Sandbox lockdown failing when deleting file after adding exception\n- (Linux) Environment variables accessible through procfs interface\n\n## [0.6.0] - 2023-11-16\n\n### Fixed\n\n- (Linux) Sandbox exceptions for symbolic links\n- (macOS) Modifying exceptions for paths affected by existing exceptions\n- (Linux) Symlink/Canonical path's exceptions overriding each other\n\n## [v0.5.0] - 2023-10-13\n\n### Changed\n\n- (Linux) Report invalid paths when adding exceptions\n- `Exception::Write` changed to `Exception::WriteAndRead`\n\n### Fixed\n\n- (Linux) Root filesystem exceptions failing sandbox creation\n- (Linux) Sandbox not enforcing readonly/noexec restrictions\n- (Linux) Exceptions for special files (i.e. /dev/null)\n\n## [0.4.0] - 2023-10-09\n\n### Added\n\n- (Linux) Seccomp system call filter\n\n### Changed\n\n- (Linux) Minimum Kernel version reduced to 3.8\n- The sandboxing process now must be single-threaded\n\n### Fixed\n\n- (Linux) Abstract namespace isolation\n- (Linux) Socket and pipe isolation\n\n### Contributors\n\nWe'd like to thank [@bjorn3](https://github.com/bjorn3) for disclosing an issue\nwith socket isolation.\n\n## [0.3.1] - 2023-08-31\n\n### Fixed\n\n- Local sockets denied by network sandbox on Linux\n\n## [0.3.0] - 2023-08-31\n\n### Changed\n\n- Linux seccomp network filtering now uses a whitelist instead of a blacklist\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Covenant Code of Conduct\n\n## Our Pledge\n\nWe as members, contributors, and leaders pledge to make participation in our\ncommunity a harassment-free experience for everyone, regardless of age, body\nsize, visible or invisible disability, ethnicity, sex characteristics, gender\nidentity and expression, level of experience, education, socio-economic status,\nnationality, personal appearance, race, caste, color, religion, or sexual\nidentity and orientation.\n\nWe pledge to act and interact in ways that contribute to an open, welcoming,\ndiverse, inclusive, and healthy community.\n\n## Our Standards\n\nExamples of behavior that contributes to a positive environment for our\ncommunity include:\n\n* Demonstrating empathy and kindness toward other people\n* Being respectful of differing opinions, viewpoints, and experiences\n* Giving and gracefully accepting constructive feedback\n* Accepting responsibility and apologizing to those affected by our mistakes,\n  and learning from the experience\n* Focusing on what is best not just for us as individuals, but for the overall\n  community\n\nExamples of unacceptable behavior include:\n\n* The use of sexualized language or imagery, and sexual attention or advances of\n  any kind\n* Trolling, insulting or derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or email address,\n  without their explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Enforcement Responsibilities\n\nCommunity leaders are responsible for clarifying and enforcing our standards of\nacceptable behavior and will take appropriate and fair corrective action in\nresponse to any behavior that they deem inappropriate, threatening, offensive,\nor harmful.\n\nCommunity leaders have the right and responsibility to remove, edit, or reject\ncomments, commits, code, wiki edits, issues, and other contributions that are\nnot aligned to this Code of Conduct, and will communicate reasons for moderation\ndecisions when appropriate.\n\n## Scope\n\nThis Code of Conduct applies within all community spaces, and also applies when\nan individual is officially representing the community in public spaces.\nExamples of representing our community include using an official e-mail address,\nposting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported to the community leaders responsible for enforcement at\n[engineering@phylum.io](mailto:engineering@phylum.io).\nAll complaints will be reviewed and investigated promptly and fairly.\n\nAll community leaders are obligated to respect the privacy and security of the\nreporter of any incident.\n\n## Enforcement Guidelines\n\nCommunity leaders will follow these Community Impact Guidelines in determining\nthe consequences for any action they deem in violation of this Code of Conduct:\n\n### 1. Correction\n\n**Community Impact**: Use of inappropriate language or other behavior deemed\nunprofessional or unwelcome in the community.\n\n**Consequence**: A private, written warning from community leaders, providing\nclarity around the nature of the violation and an explanation of why the\nbehavior was inappropriate. A public apology may be requested.\n\n### 2. Warning\n\n**Community Impact**: A violation through a single incident or series of\nactions.\n\n**Consequence**: A warning with consequences for continued behavior. No\ninteraction with the people involved, including unsolicited interaction with\nthose enforcing the Code of Conduct, for a specified period of time. This\nincludes avoiding interactions in community spaces as well as external channels\nlike social media. Violating these terms may lead to a temporary or permanent\nban.\n\n### 3. Temporary Ban\n\n**Community Impact**: A serious violation of community standards, including\nsustained inappropriate behavior.\n\n**Consequence**: A temporary ban from any sort of interaction or public\ncommunication with the community for a specified period of time. No public or\nprivate interaction with the people involved, including unsolicited interaction\nwith those enforcing the Code of Conduct, is allowed during this period.\nViolating these terms may lead to a permanent ban.\n\n### 4. Permanent Ban\n\n**Community Impact**: Demonstrating a pattern of violation of community\nstandards, including sustained inappropriate behavior, harassment of an\nindividual, or aggression toward or disparagement of classes of individuals.\n\n**Consequence**: A permanent ban from any sort of public interaction within the\ncommunity.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage],\nversion 2.1, available at\n[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].\n\nCommunity Impact Guidelines were inspired by\n[Mozilla's code of conduct enforcement ladder][Mozilla CoC].\n\nFor answers to common questions about this code of conduct, see the FAQ at\n[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at\n[https://www.contributor-covenant.org/translations][translations].\n\n[homepage]: https://www.contributor-covenant.org\n[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html\n[Mozilla CoC]: https://github.com/mozilla/diversity\n[FAQ]: https://www.contributor-covenant.org/faq\n[translations]: https://www.contributor-covenant.org/translations\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"birdcage\"\nversion = \"0.8.1\"\ndescription = \"Cross-platform embeddable sandbox\"\nauthors = [\"Phylum, Inc. <engineering@phylum.io>\"]\nrepository = \"https://github.com/phylum-dev/birdcage\"\ndocumentation = \"https://docs.rs/birdcage\"\nrust-version = \"1.70.0\"\nlicense = \"GPL-3.0-or-later\"\nedition = \"2021\"\n\n[[test]]\nname = \"harness\"\npath = \"integration/harness.rs\"\nharness = false\n\n[[test]]\nname = \"command_io\"\npath = \"integration/command_io.rs\"\nharness = false\n\n[target.'cfg(target_os = \"linux\")'.dependencies]\nlibc = \"0.2.132\"\nlog = \"0.4.20\"\nrustix = { version = \"0.38.31\", features = [\"pipe\", \"stdio\", \"thread\", \"process\", \"fs\"] }\nseccompiler = \"0.3.0\"\n\n[dev-dependencies]\nclap = { version = \"3.2.17\", features = [\"derive\"] }\nserde_json = \"1.0.108\"\nserde = { version = \"1.0.193\", features = [\"derive\"] }\ntempfile = \"3.3.0\"\n\n[dependencies]\nbitflags = \"2.4.0\"\n"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\nVersion 3, 29 June 2007\n\nCopyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>\n\nEveryone is permitted to copy and distribute verbatim copies of this license\ndocument, but changing it is not allowed.\n\nPreamble\n\nThe GNU General Public License is a free, copyleft license for software and\nother kinds of works.\n\nThe licenses for most software and other practical works are designed to take\naway your freedom to share and change the works. By contrast, the GNU General\nPublic License is intended to guarantee your freedom to share and change all\nversions of a program--to make sure it remains free software for all its users.\nWe, the Free Software Foundation, use the GNU General Public License for most\nof our software; it applies also to any other work released this way by its\nauthors. You can apply it to your programs, too.\n\nWhen we speak of free software, we are referring to freedom, not price. Our\nGeneral Public Licenses are designed to make sure that you have the freedom\nto distribute copies of free software (and charge for them if you wish), that\nyou receive source code or can get it if you want it, that you can change\nthe software or use pieces of it in new free programs, and that you know you\ncan do these things.\n\nTo protect your rights, we need to prevent others from denying you these rights\nor asking you to surrender the rights. Therefore, you have certain responsibilities\nif you distribute copies of the software, or if you modify it: responsibilities\nto respect the freedom of others.\n\nFor example, if you distribute copies of such a program, whether gratis or\nfor a fee, you must pass on to the recipients the same freedoms that you received.\nYou must make sure that they, too, receive or can get the source code. And\nyou must show them these terms so they know their rights.\n\nDevelopers that use the GNU GPL protect your rights with two steps: (1) assert\ncopyright on the software, and (2) offer you this License giving you legal\npermission to copy, distribute and/or modify it.\n\nFor the developers' and authors' protection, the GPL clearly explains that\nthere is no warranty for this free software. For both users' and authors'\nsake, the GPL requires that modified versions be marked as changed, so that\ntheir problems will not be attributed erroneously to authors of previous versions.\n\nSome devices are designed to deny users access to install or run modified\nversions of the software inside them, although the manufacturer can do so.\nThis is fundamentally incompatible with the aim of protecting users' freedom\nto change the software. The systematic pattern of such abuse occurs in the\narea of products for individuals to use, which is precisely where it is most\nunacceptable. Therefore, we have designed this version of the GPL to prohibit\nthe practice for those products. If such problems arise substantially in other\ndomains, we stand ready to extend this provision to those domains in future\nversions of the GPL, as needed to protect the freedom of users.\n\nFinally, every program is threatened constantly by software patents. States\nshould not allow patents to restrict development and use of software on general-purpose\ncomputers, but in those that do, we wish to avoid the special danger that\npatents applied to a free program could make it effectively proprietary. To\nprevent this, the GPL assures that patents cannot be used to render the program\nnon-free.\n\nThe precise terms and conditions for copying, distribution and modification\nfollow.\n\nTERMS AND CONDITIONS\n\n0. Definitions.\n\n“This License” refers to version 3 of the GNU General Public License.\n\n“Copyright” also means copyright-like laws that apply to other kinds of works,\nsuch as semiconductor masks.\n\n“The Program” refers to any copyrightable work licensed under this License.\nEach licensee is addressed as “you”. “Licensees” and “recipients” may be individuals\nor organizations.\n\nTo “modify” a work means to copy from or adapt all or part of the work in\na fashion requiring copyright permission, other than the making of an exact\ncopy. The resulting work is called a “modified version” of the earlier work\nor a work “based on” the earlier work.\n\nA “covered work” means either the unmodified Program or a work based on the\nProgram.\n\nTo “propagate” a work means to do anything with it that, without permission,\nwould make you directly or secondarily liable for infringement under applicable\ncopyright law, except executing it on a computer or modifying a private copy.\nPropagation includes copying, distribution (with or without modification),\nmaking available to the public, and in some countries other activities as\nwell.\n\nTo “convey” a work means any kind of propagation that enables other parties\nto make or receive copies. Mere interaction with a user through a computer\nnetwork, with no transfer of a copy, is not conveying.\n\nAn interactive user interface displays “Appropriate Legal Notices” to the\nextent that it includes a convenient and prominently visible feature that\n(1) displays an appropriate copyright notice, and (2) tells the user that\nthere is no warranty for the work (except to the extent that warranties are\nprovided), that licensees may convey the work under this License, and how\nto view a copy of this License. If the interface presents a list of user commands\nor options, such as a menu, a prominent item in the list meets this criterion.\n\n1. Source Code.\nThe “source code” for a work means the preferred form of the work for making\nmodifications to it. “Object code” means any non-source form of a work.\n\nA “Standard Interface” means an interface that either is an official standard\ndefined by a recognized standards body, or, in the case of interfaces specified\nfor a particular programming language, one that is widely used among developers\nworking in that language.\n\nThe “System Libraries” of an executable work include anything, other than\nthe work as a whole, that (a) is included in the normal form of packaging\na Major Component, but which is not part of that Major Component, and (b)\nserves only to enable use of the work with that Major Component, or to implement\na Standard Interface for which an implementation is available to the public\nin source code form. A “Major Component”, in this context, means a major essential\ncomponent (kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to produce\nthe work, or an object code interpreter used to run it.\n\nThe “Corresponding Source” for a work in object code form means all the source\ncode needed to generate, install, and (for an executable work) run the object\ncode and to modify the work, including scripts to control those activities.\nHowever, it does not include the work's System Libraries, or general-purpose\ntools or generally available free programs which are used unmodified in performing\nthose activities but which are not part of the work. For example, Corresponding\nSource includes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically linked\nsubprograms that the work is specifically designed to require, such as by\nintimate data communication or control flow between those subprograms and\nother parts of the work.\n\nThe Corresponding Source need not include anything that users can regenerate\nautomatically from other parts of the Corresponding Source.\n\nThe Corresponding Source for a work in source code form is that same work.\n\n2. Basic Permissions.\nAll rights granted under this License are granted for the term of copyright\non the Program, and are irrevocable provided the stated conditions are met.\nThis License explicitly affirms your unlimited permission to run the unmodified\nProgram. The output from running a covered work is covered by this License\nonly if the output, given its content, constitutes a covered work. This License\nacknowledges your rights of fair use or other equivalent, as provided by copyright\nlaw.\n\nYou may make, run and propagate covered works that you do not convey, without\nconditions so long as your license otherwise remains in force. You may convey\ncovered works to others for the sole purpose of having them make modifications\nexclusively for you, or provide you with facilities for running those works,\nprovided that you comply with the terms of this License in conveying all material\nfor which you do not control copyright. Those thus making or running the covered\nworks for you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of your copyrighted\nmaterial outside their relationship with you.\n\nConveying under any other circumstances is permitted solely under the conditions\nstated below. Sublicensing is not allowed; section 10 makes it unnecessary.\n\n3. Protecting Users' Legal Rights From Anti-Circumvention Law.\nNo covered work shall be deemed part of an effective technological measure\nunder any applicable law fulfilling obligations under article 11 of the WIPO\ncopyright treaty adopted on 20 December 1996, or similar laws prohibiting\nor restricting circumvention of such measures.\n\nWhen you convey a covered work, you waive any legal power to forbid circumvention\nof technological measures to the extent such circumvention is effected by\nexercising rights under this License with respect to the covered work, and\nyou disclaim any intention to limit operation or modification of the work\nas a means of enforcing, against the work's users, your or third parties'\nlegal rights to forbid circumvention of technological measures.\n\n4. Conveying Verbatim Copies.\nYou may convey verbatim copies of the Program's source code as you receive\nit, in any medium, provided that you conspicuously and appropriately publish\non each copy an appropriate copyright notice; keep intact all notices stating\nthat this License and any non-permissive terms added in accord with section\n7 apply to the code; keep intact all notices of the absence of any warranty;\nand give all recipients a copy of this License along with the Program.\n\nYou may charge any price or no price for each copy that you convey, and you\nmay offer support or warranty protection for a fee.\n\n5. Conveying Modified Source Versions.\nYou may convey a work based on the Program, or the modifications to produce\nit from the Program, in the form of source code under the terms of section\n4, provided that you also meet all of these conditions:\n\na) The work must carry prominent notices stating that you modified it, and\ngiving a relevant date.\n\nb) The work must carry prominent notices stating that it is released under\nthis License and any conditions added under section 7. This requirement modifies\nthe requirement in section 4 to “keep intact all notices”.\n\nc) You must license the entire work, as a whole, under this License to anyone\nwho comes into possession of a copy. This License will therefore apply, along\nwith any applicable section 7 additional terms, to the whole of the work,\nand all its parts, regardless of how they are packaged. This License gives\nno permission to license the work in any other way, but it does not invalidate\nsuch permission if you have separately received it.\n\nd) If the work has interactive user interfaces, each must display Appropriate\nLegal Notices; however, if the Program has interactive interfaces that do\nnot display Appropriate Legal Notices, your work need not make them do so.\n\nA compilation of a covered work with other separate and independent works,\nwhich are not by their nature extensions of the covered work, and which are\nnot combined with it such as to form a larger program, in or on a volume of\na storage or distribution medium, is called an “aggregate” if the compilation\nand its resulting copyright are not used to limit the access or legal rights\nof the compilation's users beyond what the individual works permit. Inclusion\nof a covered work in an aggregate does not cause this License to apply to\nthe other parts of the aggregate.\n\n6. Conveying Non-Source Forms.\nYou may convey a covered work in object code form under the terms of sections\n4 and 5, provided that you also convey the machine-readable Corresponding\nSource under the terms of this License, in one of these ways:\n\na) Convey the object code in, or embodied in, a physical product (including\na physical distribution medium), accompanied by the Corresponding Source fixed\non a durable physical medium customarily used for software interchange.\n\nb) Convey the object code in, or embodied in, a physical product (including\na physical distribution medium), accompanied by a written offer, valid for\nat least three years and valid for as long as you offer spare parts or customer\nsupport for that product model, to give anyone who possesses the object code\neither (1) a copy of the Corresponding Source for all the software in the\nproduct that is covered by this License, on a durable physical medium customarily\nused for software interchange, for a price no more than your reasonable cost\nof physically performing this conveying of source, or (2) access to copy the\nCorresponding Source from a network server at no charge.\n\nc) Convey individual copies of the object code with a copy of the written\noffer to provide the Corresponding Source. This alternative is allowed only\noccasionally and noncommercially, and only if you received the object code\nwith such an offer, in accord with subsection 6b.\n\nd) Convey the object code by offering access from a designated place (gratis\nor for a charge), and offer equivalent access to the Corresponding Source\nin the same way through the same place at no further charge. You need not\nrequire recipients to copy the Corresponding Source along with the object\ncode. If the place to copy the object code is a network server, the Corresponding\nSource may be on a different server (operated by you or a third party) that\nsupports equivalent copying facilities, provided you maintain clear directions\nnext to the object code saying where to find the Corresponding Source. Regardless\nof what server hosts the Corresponding Source, you remain obligated to ensure\nthat it is available for as long as needed to satisfy these requirements.\n\ne) Convey the object code using peer-to-peer transmission, provided you inform\nother peers where the object code and Corresponding Source of the work are\nbeing offered to the general public at no charge under subsection 6d.\n\nA separable portion of the object code, whose source code is excluded from\nthe Corresponding Source as a System Library, need not be included in conveying\nthe object code work.\n\nA “User Product” is either (1) a “consumer product”, which means any tangible\npersonal property which is normally used for personal, family, or household\npurposes, or (2) anything designed or sold for incorporation into a dwelling.\nIn determining whether a product is a consumer product, doubtful cases shall\nbe resolved in favor of coverage. For a particular product received by a particular\nuser, “normally used” refers to a typical or common use of that class of product,\nregardless of the status of the particular user or of the way in which the\nparticular user actually uses, or expects or is expected to use, the product.\nA product is a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent the\nonly significant mode of use of the product.\n\n“Installation Information” for a User Product means any methods, procedures,\nauthorization keys, or other information required to install and execute modified\nversions of a covered work in that User Product from a modified version of\nits Corresponding Source. The information must suffice to ensure that the\ncontinued functioning of the modified object code is in no case prevented\nor interfered with solely because modification has been made.\n\nIf you convey an object code work under this section in, or with, or specifically\nfor use in, a User Product, and the conveying occurs as part of a transaction\nin which the right of possession and use of the User Product is transferred\nto the recipient in perpetuity or for a fixed term (regardless of how the\ntransaction is characterized), the Corresponding Source conveyed under this\nsection must be accompanied by the Installation Information. But this requirement\ndoes not apply if neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has been installed\nin ROM).\n\nThe requirement to provide Installation Information does not include a requirement\nto continue to provide support service, warranty, or updates for a work that\nhas been modified or installed by the recipient, or for the User Product in\nwhich it has been modified or installed. Access to a network may be denied\nwhen the modification itself materially and adversely affects the operation\nof the network or violates the rules and protocols for communication across\nthe network.\n\nCorresponding Source conveyed, and Installation Information provided, in accord\nwith this section must be in a format that is publicly documented (and with\nan implementation available to the public in source code form), and must require\nno special password or key for unpacking, reading or copying.\n\n7. Additional Terms.\n“Additional permissions” are terms that supplement the terms of this License\nby making exceptions from one or more of its conditions. Additional permissions\nthat are applicable to the entire Program shall be treated as though they\nwere included in this License, to the extent that they are valid under applicable\nlaw. If additional permissions apply only to part of the Program, that part\nmay be used separately under those permissions, but the entire Program remains\ngoverned by this License without regard to the additional permissions.\n\nWhen you convey a copy of a covered work, you may at your option remove any\nadditional permissions from that copy, or from any part of it. (Additional\npermissions may be written to require their own removal in certain cases when\nyou modify the work.) You may place additional permissions on material, added\nby you to a covered work, for which you have or can give appropriate copyright\npermission.\n\nNotwithstanding any other provision of this License, for material you add\nto a covered work, you may (if authorized by the copyright holders of that\nmaterial) supplement the terms of this License with terms:\n\na) Disclaiming warranty or limiting liability differently from the terms of\nsections 15 and 16 of this License; or\n\nb) Requiring preservation of specified reasonable legal notices or author\nattributions in that material or in the Appropriate Legal Notices displayed\nby works containing it; or\n\nc) Prohibiting misrepresentation of the origin of that material, or requiring\nthat modified versions of such material be marked in reasonable ways as different\nfrom the original version; or\n\nd) Limiting the use for publicity purposes of names of licensors or authors\nof the material; or\n\ne) Declining to grant rights under trademark law for use of some trade names,\ntrademarks, or service marks; or\n\nf) Requiring indemnification of licensors and authors of that material by\nanyone who conveys the material (or modified versions of it) with contractual\nassumptions of liability to the recipient, for any liability that these contractual\nassumptions directly impose on those licensors and authors.\n\nAll other non-permissive additional terms are considered “further restrictions”\nwithin the meaning of section 10. If the Program as you received it, or any\npart of it, contains a notice stating that it is governed by this License\nalong with a term that is a further restriction, you may remove that term.\nIf a license document contains a further restriction but permits relicensing\nor conveying under this License, you may add to a covered work material governed\nby the terms of that license document, provided that the further restriction\ndoes not survive such relicensing or conveying.\n\nIf you add terms to a covered work in accord with this section, you must place,\nin the relevant source files, a statement of the additional terms that apply\nto those files, or a notice indicating where to find the applicable terms.\n\nAdditional terms, permissive or non-permissive, may be stated in the form\nof a separately written license, or stated as exceptions; the above requirements\napply either way.\n\n8. Termination.\nYou may not propagate or modify a covered work except as expressly provided\nunder this License. Any attempt otherwise to propagate or modify it is void,\nand will automatically terminate your rights under this License (including\nany patent licenses granted under the third paragraph of section 11).\n\nHowever, if you cease all violation of this License, then your license from\na particular copyright holder is reinstated (a) provisionally, unless and\nuntil the copyright holder explicitly and finally terminates your license,\nand (b) permanently, if the copyright holder fails to notify you of the violation\nby some reasonable means prior to 60 days after the cessation.\n\nMoreover, your license from a particular copyright holder is reinstated permanently\nif the copyright holder notifies you of the violation by some reasonable means,\nthis is the first time you have received notice of violation of this License\n(for any work) from that copyright holder, and you cure the violation prior\nto 30 days after your receipt of the notice.\n\nTermination of your rights under this section does not terminate the licenses\nof parties who have received copies or rights from you under this License.\nIf your rights have been terminated and not permanently reinstated, you do\nnot qualify to receive new licenses for the same material under section 10.\n\n9. Acceptance Not Required for Having Copies.\nYou are not required to accept this License in order to receive or run a copy\nof the Program. Ancillary propagation of a covered work occurring solely as\na consequence of using peer-to-peer transmission to receive a copy likewise\ndoes not require acceptance. However, nothing other than this License grants\nyou permission to propagate or modify any covered work. These actions infringe\ncopyright if you do not accept this License. Therefore, by modifying or propagating\na covered work, you indicate your acceptance of this License to do so.\n\n10. Automatic Licensing of Downstream Recipients.\nEach time you convey a covered work, the recipient automatically receives\na license from the original licensors, to run, modify and propagate that work,\nsubject to this License. You are not responsible for enforcing compliance\nby third parties with this License.\n\nAn “entity transaction” is a transaction transferring control of an organization,\nor substantially all assets of one, or subdividing an organization, or merging\norganizations. If propagation of a covered work results from an entity transaction,\neach party to that transaction who receives a copy of the work also receives\nwhatever licenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the Corresponding\nSource of the work from the predecessor in interest, if the predecessor has\nit or can get it with reasonable efforts.\n\nYou may not impose any further restrictions on the exercise of the rights\ngranted or affirmed under this License. For example, you may not impose a\nlicense fee, royalty, or other charge for exercise of rights granted under\nthis License, and you may not initiate litigation (including a cross-claim\nor counterclaim in a lawsuit) alleging that any patent claim is infringed\nby making, using, selling, offering for sale, or importing the Program or\nany portion of it.\n\n11. Patents.\nA “contributor” is a copyright holder who authorizes use under this License\nof the Program or a work on which the Program is based. The work thus licensed\nis called the contributor's “contributor version”.\n\nA contributor's “essential patent claims” are all patent claims owned or controlled\nby the contributor, whether already acquired or hereafter acquired, that would\nbe infringed by some manner, permitted by this License, of making, using,\nor selling its contributor version, but do not include claims that would be\ninfringed only as a consequence of further modification of the contributor\nversion. For purposes of this definition, “control” includes the right to\ngrant patent sublicenses in a manner consistent with the requirements of this\nLicense.\n\nEach contributor grants you a non-exclusive, worldwide, royalty-free patent\nlicense under the contributor's essential patent claims, to make, use, sell,\noffer for sale, import and otherwise run, modify and propagate the contents\nof its contributor version.\n\nIn the following three paragraphs, a “patent license” is any express agreement\nor commitment, however denominated, not to enforce a patent (such as an express\npermission to practice a patent or covenant not to sue for patent infringement).\nTo “grant” such a patent license to a party means to make such an agreement\nor commitment not to enforce a patent against the party.\n\nIf you convey a covered work, knowingly relying on a patent license, and the\nCorresponding Source of the work is not available for anyone to copy, free\nof charge and under the terms of this License, through a publicly available\nnetwork server or other readily accessible means, then you must either (1)\ncause the Corresponding Source to be so available, or (2) arrange to deprive\nyourself of the benefit of the patent license for this particular work, or\n(3) arrange, in a manner consistent with the requirements of this License,\nto extend the patent license to downstream recipients. “Knowingly relying”\nmeans you have actual knowledge that, but for the patent license, your conveying\nthe covered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that country\nthat you have reason to believe are valid.\n\nIf, pursuant to or in connection with a single transaction or arrangement,\nyou convey, or propagate by procuring conveyance of, a covered work, and grant\na patent license to some of the parties receiving the covered work authorizing\nthem to use, propagate, modify or convey a specific copy of the covered work,\nthen the patent license you grant is automatically extended to all recipients\nof the covered work and works based on it.\n\nA patent license is “discriminatory” if it does not include within the scope\nof its coverage, prohibits the exercise of, or is conditioned on the non-exercise\nof one or more of the rights that are specifically granted under this License.\nYou may not convey a covered work if you are a party to an arrangement with\na third party that is in the business of distributing software, under which\nyou make payment to the third party based on the extent of your activity of\nconveying the work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory patent\nlicense (a) in connection with copies of the covered work conveyed by you\n(or copies made from those copies), or (b) primarily for and in connection\nwith specific products or compilations that contain the covered work, unless\nyou entered into that arrangement, or that patent license was granted, prior\nto 28 March 2007.\n\nNothing in this License shall be construed as excluding or limiting any implied\nlicense or other defenses to infringement that may otherwise be available\nto you under applicable patent law.\n\n12. No Surrender of Others' Freedom.\nIf conditions are imposed on you (whether by court order, agreement or otherwise)\nthat contradict the conditions of this License, they do not excuse you from\nthe conditions of this License. If you cannot convey a covered work so as\nto satisfy simultaneously your obligations under this License and any other\npertinent obligations, then as a consequence you may not convey it at all.\nFor example, if you agree to terms that obligate you to collect a royalty\nfor further conveying from those to whom you convey the Program, the only\nway you could satisfy both those terms and this License would be to refrain\nentirely from conveying the Program.\n\n13. Use with the GNU Affero General Public License.\nNotwithstanding any other provision of this License, you have permission to\nlink or combine any covered work with a work licensed under version 3 of the\nGNU Affero General Public License into a single combined work, and to convey\nthe resulting work. The terms of this License will continue to apply to the\npart which is the covered work, but the special requirements of the GNU Affero\nGeneral Public License, section 13, concerning interaction through a network\nwill apply to the combination as such.\n\n14. Revised Versions of this License.\nThe Free Software Foundation may publish revised and/or new versions of the\nGNU General Public License from time to time. Such new versions will be similar\nin spirit to the present version, but may differ in detail to address new\nproblems or concerns.\n\nEach version is given a distinguishing version number. If the Program specifies\nthat a certain numbered version of the GNU General Public License “or any\nlater version” applies to it, you have the option of following the terms and\nconditions either of that numbered version or of any later version published\nby the Free Software Foundation. If the Program does not specify a version\nnumber of the GNU General Public License, you may choose any version ever\npublished by the Free Software Foundation.\n\nIf the Program specifies that a proxy can decide which future versions of\nthe GNU General Public License can be used, that proxy's public statement\nof acceptance of a version permanently authorizes you to choose that version\nfor the Program.\n\nLater license versions may give you additional or different permissions. However,\nno additional obligations are imposed on any author or copyright holder as\na result of your choosing to follow a later version.\n\n15. Disclaimer of Warranty.\nTHERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE\nLAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR\nOTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER\nEXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\nOF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM\nPROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR\nCORRECTION.\n\n16. Limitation of Liability.\nIN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL\nANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM\nAS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,\nINCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO\nUSE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED\nINACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE\nPROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER\nPARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n\n17. Interpretation of Sections 15 and 16.\nIf the disclaimer of warranty and limitation of liability provided above cannot\nbe given local legal effect according to their terms, reviewing courts shall\napply local law that most closely approximates an absolute waiver of all civil\nliability in connection with the Program, unless a warranty or assumption\nof liability accompanies a copy of the Program in return for a fee.\n\nEND OF TERMS AND CONDITIONS\n\nHow to Apply These Terms to Your New Programs\n\nIf you develop a new program, and you want it to be of the greatest possible\nuse to the public, the best way to achieve this is to make it free software\nwhich everyone can redistribute and change under these terms.\n\nTo do so, attach the following notices to the program. It is safest to attach\nthem to the start of each source file to most effectively state the exclusion\nof warranty; and each file should have at least the “copyright” line and a\npointer to where the full notice is found.\n\n     Birdcage, cross-platform embeddable sandbox\n     Copyright (C) 2022  Phylum, Inc.\n\nThis program is free software: you can redistribute it and/or modify it under\nthe terms of the GNU General Public License as published by the Free Software\nFoundation, either version 3 of the License, or (at your option) any later\nversion.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT\nANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\nFOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along with\nthis program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program does terminal interaction, make it output a short notice like\nthis when it starts in an interactive mode:\n\n     Birdcage  Copyright (C) 2022  Phylum, Inc.\n     This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\nThis is free software, and you are welcome to redistribute it under certain\nconditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License. Of course, your program's commands might\nbe different; for a GUI interface, you would use an “about box”.\n\nYou should also get your employer (if you work as a programmer) or school,\nif any, to sign a “copyright disclaimer” for the program, if necessary. For\nmore information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.\n\nThe GNU General Public License does not permit incorporating your program\ninto proprietary programs. If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary. If this is what you want to do, use the GNU Lesser General Public\nLicense instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Birdcage\n\n<div align=\"center\">\n\n[![GitHub](https://img.shields.io/github/license/phylum-dev/birdcage)][license]\n[![GitHub issues](https://img.shields.io/github/issues/phylum-dev/birdcage)][issues]\n[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)][CoC]\n[![Crate](https://img.shields.io/crates/v/birdcage)](https://crates.io/crates/birdcage)\n[![Documentation](https://docs.rs/birdcage/badge.svg)](https://docs.rs/birdcage)\n\n[license]: https://github.com/phylum-dev/birdcage/blob/main/LICENSE\n[issues]: https://github.com/phylum-dev/birdcage/issues\n[CoC]: https://github.com/phylum-dev/birdcage/blob/main/CODE_OF_CONDUCT.md\n\n[![Birdcage logo](./assets/Birdcage.png)][protection]\n\n</div>\n\n## About\n\nBirdcage is a cross-platform embeddable sandboxing library allowing restrictions\nto Filesystem and Network operations using native operating system APIs.\n\nBirdcage was originally developed for use by the [Phylum CLI] as an extra layer\nof [protection] against potentially malicious dependencies (see the [blog post]\nfor details). To better protect yourself from these security risks, [sign up\nnow]!\n\n[phylum cli]: https://github.com/phylum-dev/cli\n[protection]: https://www.phylum.io/defend-developers\n[blog post]: https://blog.phylum.io/sandboxing-package-installations-arms-developers-with-defense-against-open-source-attacks-and-unintended-consequences/\n[sign up now]: https://www.phylum.io/\n\nBirdcage focuses **only** on Filesystem and Network operations. It **is not** a\ncomplete sandbox preventing all side-effects or permanent damage. Applications\ncan still execute most system calls, which is especially dangerous when\nexecution is performed as root. Birdcage should be combined with other security\nmechanisms, especially if you are executing known-malicious code.\n\n## Example\n\nAn example for using Birdcage's API can be found in `./examples/sandbox`, which\nruns an application with CLI-configurable restrictions applied.\n\nTrying to run without any exceptions will produce an error:\n\n```bash\n$ cargo run --example sandbox -- echo \"Hello, Sandbox\\!\"\nError: Os { code: 13, kind: PermissionDenied, message: \"Permission denied\" }\n```\n\nRunning the same command with explicit permissions allows execution:\n\n```bash\n$ cargo run --example sandbox -- -e /usr/bin/echo -e /usr/lib echo \"Hello, Sandbox\\!\"\nHello, Sandbox!\n```\n\nCheck out `cargo run --example sandbox -- --help` for more information on how to\nuse the example.\n\n## Supported Platforms\n\n - Linux via [namespaces]\n - macOS via `sandbox_init()` (aka Seatbelt)\n\n[namespaces]: https://man7.org/linux/man-pages/man7/namespaces.7.html\n"
  },
  {
    "path": "SECURITY.md",
    "content": "# Security Policy\n\nPhylum was founded by a team of security researchers at heart, and we take the security of our tooling seriously.\n\n## Reporting a Vulnerability\n\nWe love coordinated disclosure!\nPlease email [security@phylum.io](mailto:security@phylum.io) to start a conversation!\nWe'll coordinate a secure communication mechanism first, then evaluate the reported issue(s)\nand keep you apprised each step of the way.\n"
  },
  {
    "path": "examples/sandbox.rs",
    "content": "//! Sandbox arbitrary executables.\n\nuse std::error::Error;\nuse std::path::PathBuf;\n\nuse birdcage::process::Command;\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse clap::{Parser, ValueHint};\n\n#[derive(Parser)]\n#[clap(author, about)]\nstruct Cli {\n    /// Allowed read paths.\n    #[clap(short = 'r', long, value_name = \"PATH\", value_hint = ValueHint::AnyPath)]\n    allow_read: Vec<PathBuf>,\n\n    /// Allowed write paths.\n    #[clap(short = 'w', long, value_name = \"PATH\", value_hint = ValueHint::AnyPath)]\n    allow_write: Vec<PathBuf>,\n\n    /// Allowed read and execute paths.\n    #[clap(short = 'e', long, value_name = \"PATH\", value_hint = ValueHint::AnyPath)]\n    allow_execute: Vec<PathBuf>,\n\n    /// Allowed environment variable access.\n    #[clap(long, value_name = \"VAR\")]\n    allow_env: Vec<String>,\n\n    /// Allow networking.\n    #[clap(short = 'n', long)]\n    allow_networking: bool,\n\n    /// Command to be executed in the sandbox.\n    cmd: String,\n\n    /// Arguments for the sandboxed command.\n    #[clap(allow_hyphen_values = true, multiple_values = true)]\n    args: Vec<String>,\n}\n\nfn main() -> Result<(), Box<dyn Error>> {\n    let cli = Cli::parse();\n\n    // Setup sandbox and its exceptions.\n    let mut birdcage = Birdcage::new();\n\n    for path in cli.allow_read {\n        birdcage.add_exception(Exception::Read(path))?;\n    }\n\n    for path in cli.allow_write {\n        birdcage.add_exception(Exception::WriteAndRead(path))?;\n    }\n\n    for path in cli.allow_execute {\n        birdcage.add_exception(Exception::ExecuteAndRead(path))?;\n    }\n\n    for var in cli.allow_env {\n        birdcage.add_exception(Exception::Environment(var))?;\n    }\n\n    if cli.allow_networking {\n        birdcage.add_exception(Exception::Networking)?;\n    }\n\n    // Activate sandbox.\n    let mut command = Command::new(cli.cmd);\n    command.args(&cli.args);\n    let mut child = birdcage.spawn(command)?;\n\n    // Wait for sandboxee to exit.\n    child.wait()?;\n\n    std::process::exit(0);\n}\n"
  },
  {
    "path": "integration/canonicalize.rs",
    "content": "use std::fs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::Read(\"./\".into())).unwrap();\n\n    TestSetup { sandbox, data: String::new() }\n}\n\npub fn validate(_data: String) {\n    // Check for success on reading the `Cargo.toml` file.\n    let file = fs::read_to_string(\"./Cargo.toml\").unwrap();\n    assert!(file.contains(\"birdcage\"));\n}\n"
  },
  {
    "path": "integration/command_io.rs",
    "content": "use std::io::Write;\nuse std::os::unix::process::ExitStatusExt;\n\nuse birdcage::process::{Command, Stdio};\nuse birdcage::{Birdcage, Exception, Sandbox};\n\n// macOs uses `std::process` and thus does not require explicit testing. This\n// allows running multiple tests in the same process rather than having to add\n// multiple integeration tests.\n#[cfg(not(target_os = \"linux\"))]\nfn main() {}\n\n#[cfg(target_os = \"linux\")]\nfn main() {\n    pipe_stdin_to_stdout();\n    exit_signal();\n}\n\n#[cfg(target_os = \"linux\")]\nfn pipe_stdin_to_stdout() {\n    // Setup echo-back command.\n    let mut cmd = Command::new(\"cat\");\n    cmd.stdin(Stdio::piped());\n    cmd.stdout(Stdio::piped());\n\n    // Spawn sandbox child.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::ExecuteAndRead(\"/\".into())).unwrap();\n    sandbox.add_exception(Exception::WriteAndRead(\"/\".into())).unwrap();\n    let mut child = sandbox.spawn(cmd).unwrap();\n\n    // Write test data to stdin.\n    let expected = b\"test\\n\";\n    child.stdin.as_mut().unwrap().write_all(expected).unwrap();\n\n    // Read stdout.\n    let output = child.wait_with_output().unwrap();\n    assert_eq!(&output.stdout, expected);\n}\n\n#[cfg(target_os = \"linux\")]\nfn exit_signal() {\n    // Setup echo-back command.\n    let cmd = Command::new(\"cat\");\n\n    // Spawn sandbox child.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::ExecuteAndRead(\"/\".into())).unwrap();\n    sandbox.add_exception(Exception::WriteAndRead(\"/\".into())).unwrap();\n    let mut child = sandbox.spawn(cmd).unwrap();\n\n    // Kill the child.\n    child.kill().unwrap();\n\n    // Read stdout.\n    let status = child.wait().unwrap();\n    assert_eq!(status.signal(), Some(9));\n}\n"
  },
  {
    "path": "integration/consistent_id_mappings.rs",
    "content": "use std::path::PathBuf;\nuse birdcage::{Birdcage, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    uid: u32,\n    gid: u32,\n    euid: u32,\n    egid: u32,\n}\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    let uid = unsafe { libc::getuid() };\n    let gid = unsafe { libc::getgid() };\n    let euid = unsafe { libc::geteuid() };\n    let egid = unsafe { libc::getegid() };\n\n    let sandbox = Birdcage::new();\n\n    // Serialize test data.\n    let data = TestData { uid, gid, euid, egid };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    assert_eq!(data.uid, unsafe { libc::getuid() });\n    assert_eq!(data.gid, unsafe { libc::getgid() });\n    assert_eq!(data.euid, unsafe { libc::geteuid() });\n    assert_eq!(data.egid, unsafe { libc::getegid() });\n}\n"
  },
  {
    "path": "integration/delete_before_lockdown.rs",
    "content": "use std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse tempfile::NamedTempFile;\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    // Create temporary file.\n    let tempfile = NamedTempFile::new().unwrap();\n\n    // Setup sandbox exceptions.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::Read(tempfile.path().into())).unwrap();\n\n    tempfile.close().unwrap();\n\n    TestSetup { sandbox, data: String::new() }\n}\n\npub fn validate(_data: String) {\n    // We just want to test sandbox creation worked.\n}\n"
  },
  {
    "path": "integration/env.rs",
    "content": "use std::path::PathBuf;\nuse std::env;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    // Setup our environment variables\n    env::set_var(\"PUBLIC\", \"GOOD\");\n    env::set_var(\"PRIVATE\", \"BAD\");\n\n    // Activate our sandbox.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::Environment(\"PUBLIC\".into())).unwrap();\n\n    TestSetup { sandbox, data: String::new() }\n}\n\npub fn validate(_data: String) {\n    // Only the `PUBLIC` environment variable remains.\n    let env: Vec<_> = env::vars().collect();\n    assert_eq!(env, vec![(\"PUBLIC\".into(), \"GOOD\".into())]);\n}\n"
  },
  {
    "path": "integration/exec.rs",
    "content": "use std::path::PathBuf;\nuse std::fs;\nuse std::process::Command;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::ExecuteAndRead(\"/usr/bin/true\".into())).unwrap();\n\n    TestSetup { sandbox, data: String::new() }\n}\n\npub fn validate(_data: String) {\n    // Check for success when executing `true`.\n    let cmd = Command::new(\"/usr/bin/true\").status().unwrap();\n    assert!(cmd.success());\n\n    // Check for success on reading the `true` file.\n    let cmd_file = fs::read(\"/usr/bin/true\");\n    assert!(cmd_file.is_ok());\n}\n"
  },
  {
    "path": "integration/exec_symlinked_dir.rs",
    "content": "use std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\nuse std::process::Command;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    symlink_dir: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Create symlinked executable dir.\n    let symlink_dir = tempdir.join(\"bin\");\n    unixfs::symlink(\"/usr/bin\", &symlink_dir).unwrap();\n\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::ExecuteAndRead(symlink_dir.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { symlink_dir };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Ensure symlinked dir's executable works.\n    let symlink_dir_exec = data.symlink_dir.join(\"true\");\n    let cmd = Command::new(symlink_dir_exec).status().unwrap();\n    assert!(cmd.success());\n\n    // Ensure original dir's executable works.\n    let cmd = Command::new(\"/usr/bin/true\").status().unwrap();\n    assert!(cmd.success());\n}\n"
  },
  {
    "path": "integration/exec_symlinked_dirs_exec.rs",
    "content": "use std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\nuse std::process::Command;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    symlink_dir_exec: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Create symlinked executable dir.\n    let symlink_dir = tempdir.join(\"bin\");\n    let symlink_dir_exec = symlink_dir.join(\"true\");\n    unixfs::symlink(\"/usr/bin\", &symlink_dir).unwrap();\n\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::ExecuteAndRead(symlink_dir_exec.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { symlink_dir_exec };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Ensure symlinked dir's executable works.\n    let cmd = Command::new(data.symlink_dir_exec).status().unwrap();\n    assert!(cmd.success());\n\n    // Ensure original dir's executable works.\n    let cmd = Command::new(\"/usr/bin/true\").status().unwrap();\n    assert!(cmd.success());\n}\n"
  },
  {
    "path": "integration/exec_symlinked_file.rs",
    "content": "use std::fs;\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\nuse std::process::Command;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    symlink_exec: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Create symlinked executable.\n    let exec_dir = tempdir.join(\"bin\");\n    fs::create_dir(&exec_dir).unwrap();\n    let symlink_exec = exec_dir.join(\"true\");\n    unixfs::symlink(\"/usr/bin/true\", &symlink_exec).unwrap();\n\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::ExecuteAndRead(symlink_exec.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { symlink_exec };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Ensure symlinked executable works.\n    let cmd = Command::new(data.symlink_exec).status().unwrap();\n    assert!(cmd.success());\n\n    // Ensure original executable works.\n    let cmd = Command::new(\"/usr/bin/true\").status().unwrap();\n    assert!(cmd.success());\n}\n"
  },
  {
    "path": "integration/fs.rs",
    "content": "use std::fs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\nconst FILE_CONTENT: &str = \"expected content\";\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    public_path: PathBuf,\n    private_path: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Setup our test files.\n    let private_path = tempdir.join(\"private\");\n    fs::write(&private_path, FILE_CONTENT.as_bytes()).unwrap();\n    let public_path = tempdir.join(\"public\");\n    fs::write(&public_path, FILE_CONTENT.as_bytes()).unwrap();\n\n    // Setup sandbox exceptions.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::Read(public_path.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { public_path, private_path };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Access to the public file is allowed.\n    let content = fs::read_to_string(data.public_path).unwrap();\n    assert_eq!(content, FILE_CONTENT);\n\n    // Access to the private file is prohibited.\n    let result = fs::read_to_string(data.private_path);\n    assert!(result.is_err());\n}\n"
  },
  {
    "path": "integration/fs_broken_symlink.rs",
    "content": "use std::fs::{self, File};\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\n\nuse birdcage::error::Error;\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    symlink: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Create a target for the symlink.\n    let tempfile_path = tempdir.join(\"broken_target\");\n    File::create(&tempfile_path).unwrap();\n\n    // Setup a symlink to the target file.\n    let symlink_str = tempfile_path.to_string_lossy() + \"_symlink\";\n    let symlink = PathBuf::from(symlink_str.as_ref());\n    unixfs::symlink(&tempfile_path, &symlink).unwrap();\n\n    // Remove the target, breaking the symlink.\n    fs::remove_file(&tempfile_path).unwrap();\n    assert!(!tempfile_path.exists());\n\n    // Sandbox exception fails with invalid path error.\n    let mut sandbox = Birdcage::new();\n    let result = sandbox.add_exception(Exception::Read(symlink.clone()));\n    assert!(matches!(result, Err(Error::InvalidPath(_))));\n\n    // Serialize test data.\n    let data = TestData { symlink };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Read/Write results in error.\n    let result = fs::read_to_string(&data.symlink);\n    assert!(result.is_err());\n    let result = fs::write(&data.symlink, \"bob\");\n    assert!(result.is_err());\n}\n"
  },
  {
    "path": "integration/fs_null.rs",
    "content": "use std::path::PathBuf;\nuse std::fs;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    // Activate our sandbox.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::WriteAndRead(\"/dev/null\".into())).unwrap();\n\n    TestSetup { sandbox, data: String::new() }\n}\n\npub fn validate(_data: String) {\n    // Writing to `/dev/null` is allowed.\n    fs::write(\"/dev/null\", \"blub\").unwrap();\n}\n"
  },
  {
    "path": "integration/fs_readonly.rs",
    "content": "use std::fs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\nconst FILE_CONTENT: &str = \"expected content\";\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    file: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Setup the test file.\n    let file = tempdir.join(\"fs_readonly\");\n    fs::write(&file, FILE_CONTENT.as_bytes()).unwrap();\n\n    // Activate our sandbox.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::Read(file.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { file };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Reading from the file is allowed.\n    let content = fs::read_to_string(&data.file).unwrap();\n    assert_eq!(content, FILE_CONTENT);\n\n    // Writing to the file is prohibited.\n    let result = fs::write(&data.file, FILE_CONTENT.as_bytes());\n    assert!(result.is_err());\n}\n"
  },
  {
    "path": "integration/fs_restrict_child.rs",
    "content": "use std::fs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\nconst FILE_CONTENT: &str = \"expected content\";\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    tempfile: PathBuf,\n    tempdir: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Setup our test tree.\n    let tempfile = tempdir.join(\"target-file\");\n    fs::write(&tempfile, FILE_CONTENT.as_bytes()).unwrap();\n\n    // Setup sandbox, allowing read/write to dir, but only read for the file.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::WriteAndRead(tempdir.clone())).unwrap();\n    sandbox.add_exception(Exception::Read(tempfile.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { tempfile, tempdir };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Write access to directory works.\n    fs::create_dir(data.tempdir.join(\"boop\")).unwrap();\n\n    // Read access to file works.\n    let content = fs::read_to_string(&data.tempfile).unwrap();\n    assert_eq!(content, FILE_CONTENT);\n\n    // Write access to file is denied.\n    let result = fs::write(&data.tempfile, \"no\");\n    assert!(result.is_err());\n}\n"
  },
  {
    "path": "integration/fs_symlink.rs",
    "content": "use std::fs;\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\nconst FILE_CONTENT: &str = \"expected content\";\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    private: PathBuf,\n    public: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Setup our test files.\n    let private_path = tempdir.join(\"private\");\n    fs::write(&private_path, FILE_CONTENT.as_bytes()).unwrap();\n    let public_path = tempdir.join(\"public\");\n    fs::write(&public_path, FILE_CONTENT.as_bytes()).unwrap();\n\n    // Create symlinks for the files.\n    let private_str = private_path.to_string_lossy() + \"_tmpfile\";\n    let private = PathBuf::from(private_str.as_ref());\n    let public_str = public_path.to_string_lossy() + \"_tmpfile\";\n    let public = PathBuf::from(public_str.as_ref());\n    unixfs::symlink(&private_path, &private).unwrap();\n    unixfs::symlink(&public_path, &public).unwrap();\n\n    // Activate our sandbox.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::Read(public.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { private, public };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Access to the public file is allowed.\n    let content = fs::read_to_string(&data.public).unwrap();\n    assert_eq!(content, FILE_CONTENT);\n\n    // Access to the private file is prohibited.\n    let result = fs::read_to_string(&data.private);\n    assert!(result.is_err());\n}\n"
  },
  {
    "path": "integration/fs_symlink_dir.rs",
    "content": "use std::fs;\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\nconst FILE_CONTENT: &str = \"expected content\";\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    symlink: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Setup our test directory.\n    let symlink_target = tempdir.join(\"target\");\n    fs::create_dir(symlink_target).unwrap();\n    let symlink = tempdir.join(\"symlink\");\n    unixfs::symlink(&tempdir, &symlink).unwrap();\n\n    // Activate our sandbox.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::WriteAndRead(symlink.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { symlink };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Try to create a file in the symlinked directory.\n    let path = data.symlink.join(\"tmpfile\");\n    fs::write(&path, FILE_CONTENT.as_bytes()).unwrap();\n    let content = fs::read_to_string(&path).unwrap();\n    assert_eq!(content, FILE_CONTENT);\n}\n"
  },
  {
    "path": "integration/fs_symlink_dir_separate_perms.rs",
    "content": "use std::fs;\nuse std::os::unix::fs as unixfs;\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\nconst FILE_CONTENT: &str = \"expected content\";\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    symlink_src: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Setup our test directories.\n    let symlink_src = tempdir.join(\"src\");\n    fs::create_dir(&symlink_src).unwrap();\n    let symlink_dst = tempdir.join(\"dst\");\n    unixfs::symlink(&symlink_src, &symlink_dst).unwrap();\n\n    // Add read+write for src, but also add readonly for dst.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::WriteAndRead(symlink_src.clone())).unwrap();\n    sandbox.add_exception(Exception::Read(symlink_dst.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { symlink_src };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Ensure writing works.\n    let testfile = data.symlink_src.join(\"file\");\n    fs::write(&testfile, FILE_CONTENT).unwrap();\n\n    // Ensure reading works.\n    let content = fs::read_to_string(&testfile).unwrap();\n    assert_eq!(content, FILE_CONTENT);\n}\n"
  },
  {
    "path": "integration/fs_write_also_read.rs",
    "content": "use std::fs::{self, File};\nuse std::path::PathBuf;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\nconst FILE_CONTENT: &str = \"expected content\";\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    path: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    // Setup our test files.\n    let path = tempdir.join(\"fs_write_also_read\");\n    File::create(&path).unwrap();\n\n    // Activate our sandbox.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::WriteAndRead(path.clone())).unwrap();\n\n    // Serialize test data.\n    let data = TestData { path };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Write access is allowed.\n    fs::write(&data.path, FILE_CONTENT.as_bytes()).unwrap();\n\n    // Read access is allowed.\n    let content = fs::read_to_string(data.path).unwrap();\n    assert_eq!(content, FILE_CONTENT);\n}\n"
  },
  {
    "path": "integration/full_env.rs",
    "content": "use std::path::PathBuf;\nuse std::env;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    // Setup our environment variables\n    env::set_var(\"PUBLIC\", \"GOOD\");\n\n    // Activate our sandbox.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::FullEnvironment).unwrap();\n\n    TestSetup { sandbox, data: String::new() }\n}\n\npub fn validate(_data: String) {\n    // The `PUBLIC` environment variable can be accessed.\n    assert_eq!(env::var(\"PUBLIC\"), Ok(\"GOOD\".into()));\n}\n"
  },
  {
    "path": "integration/full_sandbox.rs",
    "content": "use std::net::TcpStream;\nuse std::path::PathBuf;\nuse std::process::Command;\nuse std::{env, fs};\n\nuse birdcage::{Birdcage, Sandbox};\nuse serde::{Deserialize, Serialize};\n\nuse crate::TestSetup;\n\n#[derive(Serialize, Deserialize)]\nstruct TestData {\n    path: PathBuf,\n}\n\npub fn setup(tempdir: PathBuf) -> TestSetup {\n    const FILE_CONTENT: &str = \"expected content\";\n\n    // Create testfile.\n    let path = tempdir.join(\"full_sandbox\");\n\n    // Ensure non-sandboxed write works.\n    fs::write(&path, FILE_CONTENT.as_bytes()).unwrap();\n\n    // Ensure non-sandboxed read works.\n    let content = fs::read_to_string(&path).unwrap();\n    assert_eq!(content, FILE_CONTENT);\n\n    // Ensure non-sandboxed socket connect works.\n    let stream = TcpStream::connect(\"phylum.io:443\");\n    assert!(stream.is_ok());\n    drop(stream);\n\n    // Ensure non-sandboxed execution works.\n    let cmd = Command::new(\"/usr/bin/true\").status();\n    assert!(cmd.is_ok());\n\n    // Ensure non-sandboxed env access works.\n    env::set_var(\"TEST\", \"value\");\n    assert_eq!(env::var(\"TEST\"), Ok(\"value\".into()));\n\n    // Setup birdcage sandbox.\n    let sandbox = Birdcage::new();\n\n    // Serialize test data.\n    let data = TestData { path };\n    let data = serde_json::to_string(&data).unwrap();\n\n    TestSetup { sandbox, data }\n}\n\npub fn validate(data: String) {\n    // Deserialize test data.\n    let data: TestData = serde_json::from_str(&data).unwrap();\n\n    // Ensure sandboxed write is blocked.\n    let result = fs::write(&data.path, b\"x\");\n    assert!(result.is_err());\n\n    // Ensure sandboxed read is blocked.\n    let result = fs::read_to_string(data.path);\n    assert!(result.is_err());\n\n    // Ensure sandboxed socket connect is blocked.\n    let stream = TcpStream::connect(\"phylum.io:443\");\n    assert!(stream.is_err());\n    drop(stream);\n\n    // Ensure sandboxed execution is blocked.\n    let cmd = Command::new(\"/usr/bin/true\").status();\n    assert!(cmd.is_err());\n\n    // Ensure sandboxed env access is blocked.\n    assert_eq!(env::var_os(\"TEST\"), None);\n}\n"
  },
  {
    "path": "integration/harness.rs",
    "content": "use std::path::PathBuf;\nuse std::process::{self, Command, Stdio};\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\ntest_mods! {\n    mod canonicalize;\n    #[cfg(target_os = \"linux\")]\n    mod consistent_id_mappings;\n    mod delete_before_lockdown;\n    mod env;\n    mod exec;\n    mod exec_symlinked_dir;\n    mod exec_symlinked_dirs_exec;\n    mod exec_symlinked_file;\n    mod fs;\n    mod fs_broken_symlink;\n    mod fs_null;\n    mod fs_readonly;\n    mod fs_restrict_child;\n    mod fs_symlink;\n    mod fs_symlink_dir;\n    mod fs_symlink_dir_separate_perms;\n    mod fs_write_also_read;\n    mod full_env;\n    mod full_sandbox;\n    mod missing_exception;\n    mod net;\n    #[cfg(target_os = \"linux\")]\n    mod seccomp;\n}\n\n/// Integration test directory.\nconst TEST_DIR: &str = \"integration\";\n\n/// Test setup state.\npub struct TestSetup {\n    pub sandbox: Birdcage,\n    pub data: String,\n}\n\nfn main() {\n    let mut args = std::env::args().skip(1);\n\n    // Get test name or spawn all the tests.\n    let test_name = match args.next() {\n        Some(test_name) => test_name,\n        None => {\n            spawn_tests();\n            return;\n        },\n    };\n\n    // Find test matching the name.\n    let test = match TESTS.iter().find(|(cmd, ..)| cmd == &test_name) {\n        Some(test) => test,\n        None => unreachable!(\"invalid test module name: {test_name:?}\"),\n    };\n\n    // Run setup or test validation.\n    let arg = args.next().unwrap();\n    match arg.as_str() {\n        \"--setup\" => {\n            let tempdir = args.next().unwrap();\n            run_setup(&test_name, tempdir, &test.1);\n        },\n        _ => test.2(arg),\n    }\n}\n\n/// Reexecute binary to launch tests as separate processes.\n///\n/// Returns `true` on success.\nfn spawn_tests() {\n    eprintln!(\"\\nrunning {} tests\", TESTS.len());\n\n    // Spawn child processes for all tests.\n    let current_exe = std::env::current_exe().unwrap();\n    let mut children = Vec::new();\n    for (cmd, ..) in TESTS {\n        let tempdir = tempfile::tempdir().unwrap();\n        let child = Command::new(&current_exe)\n            .arg(cmd)\n            .arg(\"--setup\")\n            .arg(tempdir.path())\n            .stderr(Stdio::piped())\n            .spawn()\n            .unwrap();\n        children.push((cmd, child, tempdir));\n    }\n\n    // Check results for each test.\n    let mut passed = 0;\n    for (name, child, tempdir) in children {\n        let output = match child.wait_with_output() {\n            Ok(output) => output,\n            Err(err) => {\n                eprintln!(\"test {TEST_DIR}/{name}.rs ... \\x1b[31mHARNESS FAILURE\\x1b[0m: {err}\");\n                continue;\n            },\n        };\n\n        // Report individual test results.\n        if !output.status.success() {\n            eprintln!(\"test {TEST_DIR}/{name}.rs ... \\x1b[31mFAILED\\x1b[0m\");\n\n            // Print stderr on failure if there is some.\n            let stderr = String::from_utf8_lossy(&output.stderr);\n            if !stderr.is_empty() {\n                eprintln!(\"\\n---- {TEST_DIR}/{name}.rs stderr ----\\n{}\\n\", stderr.trim());\n            }\n        } else {\n            eprintln!(\"test {TEST_DIR}/{name}.rs ... \\x1b[32mok\\x1b[0m\");\n            passed += 1;\n        }\n\n        // Cleanup tempdir.\n        tempdir.close().unwrap();\n    }\n\n    // Print total results.\n    let failed = TESTS.len() - passed;\n    if failed > 0 {\n        eprintln!(\"\\ntest result: \\x1b[31mFAILED\\x1b[0m. {} passed; {} failed\", passed, failed);\n    } else {\n        eprintln!(\"\\ntest result: \\x1b[32mok\\x1b[0m. {} passed; {} failed\", passed, failed);\n    }\n\n    eprintln!();\n}\n\n/// Run test's setup step and spawn validation child.\nfn run_setup(test_name: &str, tempdir: String, setup: &fn(PathBuf) -> TestSetup) {\n    // Run test setup.\n    let mut test_setup = setup(PathBuf::from(tempdir));\n\n    // Add exceptions to allow self-execution.\n    let current_exe = std::env::current_exe().unwrap();\n    for path in [current_exe.clone(), \"/usr/lib\".into(), \"/lib64\".into(), \"/lib\".into()] {\n        if path.exists() {\n            test_setup.sandbox.add_exception(Exception::ExecuteAndRead(path)).unwrap();\n        }\n    }\n\n    // Reexecute test with sandbox enabled.\n    let mut command = birdcage::process::Command::new(current_exe);\n    command.args([test_name, test_setup.data.as_str()]);\n    let child = test_setup.sandbox.spawn(command).unwrap();\n\n    // Validate test results.\n    let output = child.wait_with_output().unwrap();\n    if !output.status.success() {\n        process::exit(output.status.code().unwrap_or(1));\n    }\n}\n\n#[macro_export]\nmacro_rules! test_mods {\n    ($($(#[$cfg:meta])? mod $mod:ident);*;) => {\n        $(\n            $( #[$cfg] )?\n            mod $mod;\n        )*\n\n        const TESTS: &[(&str, fn(std::path::PathBuf) -> $crate::TestSetup, fn(String))] = &[$(\n            $( #[$cfg] )?\n            (stringify!($mod), $mod :: setup, $mod :: validate),\n        )*];\n    };\n}\n"
  },
  {
    "path": "integration/missing_exception.rs",
    "content": "use std::path::PathBuf;\n\nuse birdcage::error::Error;\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    let mut sandbox = Birdcage::new();\n\n    // Add a path that doesn't exist.\n    let result = sandbox.add_exception(Exception::Read(\"/does/not/exist\".into()));\n\n    // Ensure it is appropriately reported that exception was NOT added.\n    match result {\n        Err(Error::InvalidPath(path)) => assert_eq!(path, PathBuf::from(\"/does/not/exist\")),\n        _ => panic!(\"expected path error\"),\n    }\n\n    TestSetup { sandbox, data: String::new() }\n}\n\npub fn validate(_data: String) {\n    // Ensure locking is always successful.\n}\n"
  },
  {
    "path": "integration/net.rs",
    "content": "use std::path::PathBuf;\nuse std::net::TcpStream;\n\nuse birdcage::{Birdcage, Exception, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    // Setup sandbox exceptions.\n    let mut sandbox = Birdcage::new();\n    sandbox.add_exception(Exception::Networking).unwrap();\n\n    TestSetup { sandbox, data: String::new() }\n}\n\npub fn validate(_data: String) {\n    let result = TcpStream::connect(\"8.8.8.8:443\");\n    assert!(result.is_ok());\n}\n"
  },
  {
    "path": "integration/seccomp.rs",
    "content": "use std::path::PathBuf;\nuse std::ffi::CString;\n\nuse birdcage::{Birdcage, Sandbox};\n\nuse crate::TestSetup;\n\npub fn setup(_tempdir: PathBuf) -> TestSetup {\n    TestSetup { sandbox: Birdcage::new(), data: String::new() }\n}\n\npub fn validate(_data: String) {\n    // Ensure `chdir` is allowed.\n    let root_path = CString::new(\"/\").unwrap();\n    let result = unsafe { libc::chdir(root_path.as_ptr()) };\n    assert_eq!(result, 0);\n\n    // Ensure `unshare` is always blocked.\n    let result = unsafe { libc::unshare(libc::CLONE_NEWUSER) };\n    assert_eq!(result, -1);\n\n    // Ensure `clone` is blocked with `CLONE_NEWUSER`.\n    let stack = unsafe { libc::malloc(4096) };\n    let flags = libc::CLONE_NEWUSER as libc::c_ulong;\n    let result = unsafe { libc::syscall(libc::SYS_clone, flags, stack) };\n    assert_eq!(result, -1);\n}\n"
  },
  {
    "path": "rustfmt.toml",
    "content": "format_code_in_doc_comments = true\ngroup_imports = \"StdExternalCrate\"\nmatch_block_trailing_comma = true\ncondense_wildcard_suffixes = true\nuse_field_init_shorthand = true\nnormalize_doc_attributes = true\noverflow_delimited_expr = true\nimports_granularity = \"Module\"\nuse_small_heuristics = \"Max\"\nnormalize_comments = true\nreorder_impl_items = true\nuse_try_shorthand = true\nnewline_style = \"Unix\"\nformat_strings = true\nwrap_comments = true\n"
  },
  {
    "path": "src/error.rs",
    "content": "//! Sandboxing errors.\n\nuse std::error::Error as StdError;\nuse std::fmt::{self, Display, Formatter};\nuse std::io::Error as IoError;\n#[cfg(target_os = \"linux\")]\nuse std::io::ErrorKind as IoErrorKind;\nuse std::path::PathBuf;\nuse std::result::Result as StdResult;\n\n#[cfg(target_os = \"linux\")]\nuse seccompiler::{BackendError, Error as SeccompError};\n\n/// Birdcage result type.\npub type Result<T> = StdResult<T, Error>;\n\n/// Sandboxing error.\n#[derive(Debug)]\npub enum Error {\n    /// Seccomp errors.\n    #[cfg(target_os = \"linux\")]\n    Seccomp(SeccompError),\n\n    /// Invalid sandbox exception path.\n    InvalidPath(PathBuf),\n\n    /// I/O error.\n    Io(IoError),\n\n    /// Sandbox activation failed.\n    ActivationFailed(String),\n}\n\nimpl StdError for Error {}\n\nimpl Display for Error {\n    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {\n        match self {\n            #[cfg(target_os = \"linux\")]\n            Self::Seccomp(error) => write!(f, \"seccomp error: {error}\"),\n            Self::InvalidPath(path) => write!(f, \"invalid path: {path:?}\"),\n            #[cfg(target_os = \"linux\")]\n            Self::Io(error) if error.kind() == IoErrorKind::Unsupported => {\n                write!(\n                    f,\n                    \"unsupported operation, please ensure Kernel version is at least 5.12: {error}\"\n                )\n            },\n            Self::Io(error) => write!(f, \"input/output error: {error}\"),\n            Self::ActivationFailed(error) => {\n                write!(f, \"failed to initialize a sufficient sandbox: {error}\")\n            },\n        }\n    }\n}\n\n#[cfg(target_os = \"linux\")]\nimpl From<SeccompError> for Error {\n    fn from(error: SeccompError) -> Self {\n        Self::Seccomp(error)\n    }\n}\n\n#[cfg(target_os = \"linux\")]\nimpl From<BackendError> for Error {\n    fn from(error: BackendError) -> Self {\n        Self::Seccomp(SeccompError::Backend(error))\n    }\n}\n\nimpl From<IoError> for Error {\n    fn from(error: IoError) -> Self {\n        Self::Io(error)\n    }\n}\n"
  },
  {
    "path": "src/lib.rs",
    "content": "//! Birdcage sandbox.\n//!\n//! This crate provides a cross-platform API for an embedded sandbox for macOS\n//! and Linux.\n//!\n//! # Example\n//!\n//! ```rust\n//! use std::fs;\n//!\n//! use birdcage::process::Command;\n//! use birdcage::{Birdcage, Exception, Sandbox};\n//!\n//! // Reads without sandbox work.\n//! fs::read_to_string(\"./Cargo.toml\").unwrap();\n//!\n//! // Allow access to our test executable.\n//! let mut sandbox = Birdcage::new();\n//! sandbox.add_exception(Exception::ExecuteAndRead(\"/bin/cat\".into())).unwrap();\n//! let _ = sandbox.add_exception(Exception::ExecuteAndRead(\"/lib64\".into()));\n//! let _ = sandbox.add_exception(Exception::ExecuteAndRead(\"/lib\".into()));\n//!\n//! // Initialize the sandbox; by default everything is prohibited.\n//! let mut command = Command::new(\"/bin/cat\");\n//! command.arg(\"./Cargo.toml\");\n//! let mut child = sandbox.spawn(command).unwrap();\n//!\n//! // Reads with sandbox should fail.\n//! let status = child.wait().unwrap();\n//! assert!(!status.success());\n//! ```\n\nuse std::env;\nuse std::path::PathBuf;\n\nuse crate::error::Result;\n#[cfg(target_os = \"linux\")]\nuse crate::linux::LinuxSandbox;\n#[cfg(target_os = \"macos\")]\nuse crate::macos::MacSandbox;\nuse crate::process::{Child, Command};\n\npub mod error;\n#[cfg(target_os = \"linux\")]\nmod linux;\n#[cfg(target_os = \"macos\")]\nmod macos;\npub mod process;\n\n/// Default platform sandbox.\n///\n/// This type will automatically pick the default sandbox for each available\n/// platform.\n#[cfg(target_os = \"linux\")]\npub type Birdcage = LinuxSandbox;\n\n/// Default platform sandbox.\n///\n/// This type will automatically pick the default sandbox for each available\n/// platform.\n#[cfg(target_os = \"macos\")]\npub type Birdcage = MacSandbox;\n\npub trait Sandbox: Sized {\n    /// Setup the sandboxing environment.\n    fn new() -> Self;\n\n    /// Add a new exception to the sandbox.\n    ///\n    /// Exceptions added for symlinks will also automatically apply to the\n    /// symlink's target.\n    fn add_exception(&mut self, exception: Exception) -> Result<&mut Self>;\n\n    /// Setup sandbox and spawn a new process.\n    ///\n    /// This will setup the sandbox in the **CURRENT** process, before launching\n    /// the sandboxee. Since most of the restrictions will also be applied to\n    /// the calling process, it is recommended to create a separate process\n    /// before calling this method. The calling process is **NOT** fully\n    /// sandboxed.\n    ///\n    /// # Errors\n    ///\n    /// Sandboxing will fail if the calling process is not single-threaded.\n    ///\n    /// After failure, the calling process might still be affected by partial\n    /// sandboxing restrictions.\n    fn spawn(self, sandboxee: Command) -> Result<Child>;\n}\n\n/// Sandboxing exception rule.\n///\n/// An exception excludes certain resources from the sandbox, allowing sandboxed\n/// applications to still access these resources.\n#[derive(Debug, Clone)]\npub enum Exception {\n    /// Allow read access to the path and anything beneath it.\n    Read(PathBuf),\n\n    /// Allow writing and reading the path and anything beneath it.\n    WriteAndRead(PathBuf),\n\n    /// Allow executing and reading the path and anything beneath it.\n    ///\n    /// This is grouped with reading as a convenience, since execution will\n    /// always also require read access.\n    ExecuteAndRead(PathBuf),\n\n    /// Allow reading an environment variable.\n    Environment(String),\n\n    /// Allow reading **all** environment variables.\n    FullEnvironment,\n\n    /// Allow networking.\n    Networking,\n}\n\n/// Restrict access to environment variables.\npub(crate) fn restrict_env_variables(exceptions: &[String]) {\n    // Invalid unicode will cause `env::vars()` to panic, so we don't have to worry\n    // about them getting ignored.\n    for (key, _) in env::vars().filter(|(key, _)| !exceptions.contains(key)) {\n        env::remove_var(key);\n    }\n}\n"
  },
  {
    "path": "src/linux/mod.rs",
    "content": "//! Linux sandboxing.\n\nuse std::collections::HashMap;\nuse std::ffi::CString;\nuse std::io::{Error as IoError, ErrorKind as IoErrorKind};\nuse std::os::fd::OwnedFd;\nuse std::os::unix::ffi::OsStrExt;\nuse std::path::{Component, Path, PathBuf};\nuse std::{env, fs, io, ptr};\n\nuse rustix::pipe::pipe;\nuse rustix::process::{Gid, Pid, Uid, WaitOptions};\n\nuse crate::error::{Error, Result};\nuse crate::linux::namespaces::{MountAttrFlags, Namespaces};\nuse crate::linux::seccomp::SyscallFilter;\nuse crate::{Child, Command, Exception, Sandbox};\n\nmod namespaces;\nmod seccomp;\n\n/// Linux sandboxing.\n#[derive(Default)]\npub struct LinuxSandbox {\n    env_exceptions: Vec<String>,\n    path_exceptions: PathExceptions,\n    allow_networking: bool,\n    full_env: bool,\n}\n\nimpl Sandbox for LinuxSandbox {\n    fn new() -> Self {\n        Self::default()\n    }\n\n    fn add_exception(&mut self, exception: Exception) -> Result<&mut Self> {\n        match exception {\n            Exception::Read(path) => self.path_exceptions.update(path, false, false)?,\n            Exception::WriteAndRead(path) => self.path_exceptions.update(path, true, false)?,\n            Exception::ExecuteAndRead(path) => self.path_exceptions.update(path, false, true)?,\n            Exception::Environment(key) => self.env_exceptions.push(key),\n            Exception::FullEnvironment => self.full_env = true,\n            Exception::Networking => self.allow_networking = true,\n        }\n\n        Ok(self)\n    }\n\n    fn spawn(self, sandboxee: Command) -> Result<Child> {\n        // Ensure calling process is not multi-threaded.\n        assert!(\n            thread_count().unwrap_or(0) == 1,\n            \"`Sandbox::spawn` must be called from a single-threaded process\"\n        );\n\n        // Remove environment variables.\n        if !self.full_env {\n            crate::restrict_env_variables(&self.env_exceptions);\n        }\n\n        // Create pipes to hook up init's stdio.\n        let stdin_pipe = sandboxee.stdin.make_pipe(true)?;\n        let stdout_pipe = sandboxee.stdout.make_pipe(false)?;\n        let stderr_pipe = sandboxee.stderr.make_pipe(false)?;\n        let exit_signal_pipe = pipe().map_err(IoError::from)?;\n\n        // Spawn isolated sandbox PID 1.\n        let allow_networking = self.allow_networking;\n        let init_arg = ProcessInitArg::new(\n            self,\n            sandboxee,\n            exit_signal_pipe,\n            stdin_pipe,\n            stdout_pipe,\n            stderr_pipe,\n        );\n        let init_arg = spawn_sandbox_init(init_arg, allow_networking)?;\n\n        // Deconstruct init args, dropping unused FDs.\n        let (pid, stdin_tx, stdout_rx, stderr_rx, exit_signal_rx) = {\n            let ProcessInitArg {\n                // Extract used fields.\n                pid,\n                stdin_tx,\n                stdout_rx,\n                stderr_rx,\n                exit_signal_rx,\n\n                // Deconstruct all remaining fields to manually drop them.\n                path_exceptions: _x0,\n                exit_signal_tx: _x1,\n                parent_euid: _x2,\n                parent_egid: _x3,\n                stdout_tx: _x4,\n                stderr_tx: _x5,\n                sandboxee: _x6,\n                stdin_rx: _x7,\n            } = init_arg;\n            (pid, stdin_tx, stdout_rx, stderr_rx, exit_signal_rx)\n        };\n\n        let child = Child::new(pid, exit_signal_rx, stdin_tx, stdout_rx, stderr_rx)?;\n\n        Ok(child)\n    }\n}\n\n/// Create sandbox child process.\n///\n/// This function uses `clone` to setup the sandbox's init process with user\n/// namespace isolations in place.\n///\n/// Returns PID of the child process if successful.\nfn spawn_sandbox_init(init_arg: ProcessInitArg, allow_networking: bool) -> Result<ProcessInitArg> {\n    unsafe {\n        // Initialize child process stack memory.\n        let stack_size = 1024 * 1024;\n        let child_stack = libc::mmap(\n            ptr::null_mut(),\n            stack_size,\n            libc::PROT_READ | libc::PROT_WRITE,\n            libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_STACK,\n            -1,\n            0,\n        );\n        if child_stack == libc::MAP_FAILED {\n            return Err(IoError::last_os_error().into());\n        }\n\n        // Stack grows downward on all relevant Linux processors.\n        let stack_top = child_stack.add(stack_size);\n\n        // Construct clone flags with required namespaces.\n        let mut flags =\n            libc::CLONE_NEWIPC | libc::CLONE_NEWNS | libc::CLONE_NEWPID | libc::CLONE_NEWUSER;\n        if !allow_networking {\n            flags |= libc::CLONE_NEWNET;\n        }\n\n        // Spawn sandbox init process.\n        let init_arg_raw = Box::into_raw(Box::new(init_arg));\n        let init_pid =\n            libc::clone(sandbox_init, stack_top, flags | libc::SIGCHLD, init_arg_raw as _);\n        if init_pid == -1 {\n            Err(IoError::last_os_error().into())\n        } else {\n            let mut init_arg = Box::from_raw(init_arg_raw);\n            init_arg.pid = init_pid;\n            Ok(*init_arg)\n        }\n    }\n}\n\n/// PID 1 inside the sandbox.\n///\n/// This function is the entry point for the process which is used to launch the\n/// sandboxee and act as init system for the PID namespace.\nextern \"C\" fn sandbox_init(arg: *mut libc::c_void) -> libc::c_int {\n    let init_arg: Box<ProcessInitArg> = unsafe { Box::from_raw(arg as _) };\n\n    match sandbox_init_inner(*init_arg) {\n        Ok(exit_code) => exit_code,\n        Err(err) => {\n            eprintln!(\"sandboxing failure: {err}\");\n            1\n        },\n    }\n}\n\n/// PID 1 inside the sandbox.\n///\n/// Wrapper to simplify error handling.\nfn sandbox_init_inner(mut init_arg: ProcessInitArg) -> io::Result<libc::c_int> {\n    // Close all unused FDs.\n    init_arg.stdin_tx.take();\n    init_arg.stdout_rx.take();\n    init_arg.stderr_rx.take();\n    drop(init_arg.exit_signal_rx);\n\n    // Hook up stdio to parent process.\n    if let Some(stdin_pipe) = &mut init_arg.stdin_rx {\n        rustix::stdio::dup2_stdin(stdin_pipe)?;\n    }\n    if let Some(stdout_pipe) = &init_arg.stdout_tx {\n        rustix::stdio::dup2_stdout(stdout_pipe)?;\n    }\n    if let Some(stderr_pipe) = &init_arg.stderr_tx {\n        rustix::stdio::dup2_stderr(stderr_pipe)?;\n    }\n\n    // Map root UID and GID.\n    namespaces::map_ids(init_arg.parent_euid.as_raw(), init_arg.parent_egid.as_raw(), 0, 0)?;\n\n    // Isolate filesystem using a mount namespace.\n    namespaces::setup_mount_namespace(init_arg.path_exceptions)?;\n\n    // Create new procfs directory.\n    let new_proc_c = CString::new(\"/proc\")?;\n    namespaces::mount_proc(&new_proc_c)?;\n\n    // Drop root user mapping.\n    namespaces::create_user_namespace(\n        init_arg.parent_euid.as_raw(),\n        init_arg.parent_egid.as_raw(),\n        Namespaces::empty(),\n    )?;\n\n    // Setup system call filters.\n    SyscallFilter::apply().map_err(|err| IoError::new(IoErrorKind::Other, err))?;\n\n    // Block suid/sgid.\n    //\n    // This is also blocked by our bind mount's MS_NOSUID flag, so we're just\n    // doubling-down here.\n    rustix::thread::set_no_new_privs(true)?;\n\n    // Spawn sandboxed process.\n    let mut std_command = std::process::Command::from(init_arg.sandboxee);\n    std_command.stdin(std::process::Stdio::inherit());\n    std_command.stdout(std::process::Stdio::inherit());\n    std_command.stderr(std::process::Stdio::inherit());\n    let child = std_command.spawn()?;\n\n    // Reap zombie children.\n    let child_pid = Pid::from_raw(child.id() as i32);\n    loop {\n        // Wait for any child to exit.\n        match rustix::process::wait(WaitOptions::empty())? {\n            Some((pid, status)) if Some(pid) == child_pid => match status.terminating_signal() {\n                Some(signal) => {\n                    // Send exit signal to parent.\n                    rustix::io::write(init_arg.exit_signal_tx, &signal.to_le_bytes())?;\n                    return Ok(1);\n                },\n                None => return Ok(status.exit_status().unwrap_or(1) as i32),\n            },\n            Some(_) => (),\n            None => unreachable!(\"none without nohang\"),\n        }\n    }\n}\n\n/// Init process argument passed to `clone`.\nstruct ProcessInitArg {\n    path_exceptions: PathExceptions,\n\n    sandboxee: Command,\n\n    parent_euid: Uid,\n    parent_egid: Gid,\n\n    // FDs used by the child process.\n    stdin_rx: Option<OwnedFd>,\n    stdout_tx: Option<OwnedFd>,\n    stderr_tx: Option<OwnedFd>,\n    exit_signal_tx: OwnedFd,\n\n    // FDs passed to the child for closing them.\n    stdin_tx: Option<OwnedFd>,\n    stdout_rx: Option<OwnedFd>,\n    stderr_rx: Option<OwnedFd>,\n    exit_signal_rx: OwnedFd,\n\n    pid: i32,\n}\n\nimpl ProcessInitArg {\n    fn new(\n        sandbox: LinuxSandbox,\n        sandboxee: Command,\n        exit_signal: (OwnedFd, OwnedFd),\n        stdin: (Option<OwnedFd>, Option<OwnedFd>),\n        stdout: (Option<OwnedFd>, Option<OwnedFd>),\n        stderr: (Option<OwnedFd>, Option<OwnedFd>),\n    ) -> Self {\n        // Get EUID/EGID outside of the namespaces.\n        let parent_euid = rustix::process::geteuid();\n        let parent_egid = rustix::process::getegid();\n\n        Self {\n            parent_euid,\n            parent_egid,\n            sandboxee,\n            path_exceptions: sandbox.path_exceptions,\n            stdin_rx: stdin.0,\n            stdout_tx: stdout.1,\n            stderr_tx: stderr.1,\n            exit_signal_tx: exit_signal.1,\n            stdin_tx: stdin.1,\n            stdout_rx: stdout.0,\n            stderr_rx: stderr.0,\n            exit_signal_rx: exit_signal.0,\n            pid: -1,\n        }\n    }\n}\n\n/// Path permissions required for the sandbox.\n#[derive(Default)]\npub(crate) struct PathExceptions {\n    bind_mounts: HashMap<PathBuf, MountAttrFlags>,\n    symlinks: Vec<(PathBuf, PathBuf)>,\n}\n\nimpl PathExceptions {\n    /// Add or modify a path's exceptions.\n    ///\n    /// This will add a new bind mount for the canonical path with the specified\n    /// permission if it does not exist already.\n    ///\n    /// If the bind mount already exists, it will *ADD* the additional\n    /// permissions.\n    fn update(&mut self, path: PathBuf, write: bool, execute: bool) -> Result<()> {\n        // Use canonical path for indexing.\n        //\n        // This ensures that a symlink and its target are treated like the same path for\n        // exceptions.\n        //\n        // If the home path cannot be accessed, we ignore the exception.\n        let canonical_path = match path.canonicalize() {\n            Ok(path) => path,\n            Err(_) => return Err(Error::InvalidPath(path)),\n        };\n\n        // Store original symlink path to create it if necessary.\n        if path_has_symlinks(&path) {\n            // Normalize symlink's path.\n            let absolute = absolute(&path)?;\n            let normalized = normalize_path(&absolute);\n\n            self.symlinks.push((normalized, canonical_path.clone()));\n        }\n\n        // Update bind mount's permission flags.\n\n        let flags = self\n            .bind_mounts\n            .entry(canonical_path)\n            .or_insert(MountAttrFlags::RDONLY | MountAttrFlags::NOEXEC);\n\n        if write {\n            flags.remove(MountAttrFlags::RDONLY);\n        }\n\n        if execute {\n            flags.remove(MountAttrFlags::NOEXEC);\n        }\n\n        Ok(())\n    }\n}\n\n// Copied from Rust's STD:\n// https://github.com/rust-lang/rust/blob/42faef503f3e765120ca0ef06991337668eafc32/library/std/src/sys/unix/path.rs#L23C1-L63C2\n//\n// Licensed under MIT:\n// https://github.com/rust-lang/rust/blob/master/LICENSE-MIT\n//\n/// Make a POSIX path absolute without changing its semantics.\nfn absolute(path: &Path) -> io::Result<PathBuf> {\n    // This is mostly a wrapper around collecting `Path::components`, with\n    // exceptions made where this conflicts with the POSIX specification.\n    // See 4.13 Pathname Resolution, IEEE Std 1003.1-2017\n    // https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13\n\n    // Get the components, skipping the redundant leading \".\" component if it\n    // exists.\n    let mut components = path.strip_prefix(\".\").unwrap_or(path).components();\n    let path_os = path.as_os_str().as_bytes();\n\n    let mut normalized = if path.is_absolute() {\n        // \"If a pathname begins with two successive <slash> characters, the\n        // first component following the leading <slash> characters may be\n        // interpreted in an implementation-defined manner, although more than\n        // two leading <slash> characters shall be treated as a single <slash>\n        // character.\"\n        if path_os.starts_with(b\"//\") && !path_os.starts_with(b\"///\") {\n            components.next();\n            PathBuf::from(\"//\")\n        } else {\n            PathBuf::new()\n        }\n    } else {\n        env::current_dir()?\n    };\n    normalized.extend(components);\n\n    // \"Interfaces using pathname resolution may specify additional constraints\n    // when a pathname that does not name an existing directory contains at\n    // least one non- <slash> character and contains one or more trailing\n    // <slash> characters\".\n    // A trailing <slash> is also meaningful if \"a symbolic link is\n    // encountered during pathname resolution\".\n    if path_os.ends_with(b\"/\") {\n        normalized.push(\"\");\n    }\n\n    Ok(normalized)\n}\n\n/// Normalize path components, stripping out `.` and `..`.\nfn normalize_path(path: &Path) -> PathBuf {\n    let mut normalized = PathBuf::new();\n\n    for component in path.components() {\n        match component {\n            Component::Prefix(_) => unreachable!(\"impl does not consider windows\"),\n            Component::RootDir => normalized.push(\"/\"),\n            Component::CurDir => continue,\n            Component::ParentDir => {\n                normalized.pop();\n            },\n            Component::Normal(segment) => normalized.push(segment),\n        }\n    }\n\n    normalized\n}\n\n/// Check if a path contains any symlinks.\nfn path_has_symlinks(path: &Path) -> bool {\n    path.ancestors().any(|path| path.read_link().is_ok())\n}\n\n/// Get the number of threads used by the current process.\nfn thread_count() -> io::Result<usize> {\n    // Read process status from procfs.\n    let status = fs::read_to_string(\"/proc/self/status\")?;\n\n    // Parse procfs output.\n    let (_, threads_start) = status.split_once(\"Threads:\").ok_or_else(|| {\n        io::Error::new(io::ErrorKind::InvalidData, \"/proc/self/status missing \\\"Threads:\\\"\")\n    })?;\n    let thread_count = threads_start.split_whitespace().next().ok_or_else(|| {\n        io::Error::new(io::ErrorKind::InvalidData, \"/proc/self/status output malformed\")\n    })?;\n\n    // Convert to number.\n    let thread_count = thread_count\n        .parse::<usize>()\n        .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;\n\n    Ok(thread_count)\n}\n"
  },
  {
    "path": "src/linux/namespaces.rs",
    "content": "//! Linux namespaces.\n\nuse std::cmp::Ordering;\nuse std::ffi::{CStr, CString};\nuse std::fs::{self, File};\nuse std::io::Error as IoError;\nuse std::os::unix::ffi::OsStrExt;\nuse std::os::unix::fs as unixfs;\nuse std::path::{Component, Path, PathBuf};\nuse std::{env, io, mem, ptr};\n\nuse bitflags::bitflags;\n\nuse crate::linux::PathExceptions;\n\n/// Path for mount namespace's new root.\nconst NEW_ROOT: &str = \"/tmp/birdcage-root\";\n\n/// Isolate filesystem access in an existing mount namespace.\n///\n/// This will deny access to any path which isn't part of `bind_mounts`. Allowed\n/// paths are mounted according to their bind mount flags.\npub(crate) fn setup_mount_namespace(exceptions: PathExceptions) -> io::Result<()> {\n    // Get target paths for new and old root.\n    let new_root = PathBuf::from(NEW_ROOT);\n\n    // Ensure new root is available as an empty directory.\n    if !new_root.exists() {\n        fs::create_dir_all(&new_root)?;\n    }\n\n    // Create C-friendly versions for our paths.\n    let new_root_c = CString::new(new_root.as_os_str().as_bytes()).unwrap();\n\n    // Create tmpfs mount for the new root, allowing pivot and ensuring directories\n    // aren't created outside the sandbox.\n    mount_tmpfs(&new_root_c)?;\n\n    // Sort bind mounts by shortest length, to create parents before their children.\n    let mut bind_mounts: Vec<_> = exceptions.bind_mounts.into_iter().collect();\n    bind_mounts.sort_unstable_by(|(a_path, a_flags), (b_path, b_flags)| {\n        match a_path.components().count().cmp(&b_path.components().count()) {\n            Ordering::Equal => (a_path, a_flags).cmp(&(b_path, b_flags)),\n            ord => ord,\n        }\n    });\n\n    // Bind mount all allowed directories.\n    for (path, flags) in bind_mounts {\n        let src_c = CString::new(path.as_os_str().as_bytes()).unwrap();\n\n        // Get bind mount destination.\n        let unrooted_path = path.strip_prefix(\"/\").unwrap();\n        let dst = new_root.join(unrooted_path);\n        let dst_c = CString::new(dst.as_os_str().as_bytes()).unwrap();\n\n        // Create mount target.\n        if let Err(err) = copy_tree(&path, &new_root) {\n            log::error!(\"skipping birdcage exception {path:?}: {err}\");\n            continue;\n        }\n\n        // Bind path with full permissions.\n        bind_mount(&src_c, &dst_c)?;\n\n        // Remount to update permissions.\n        update_mount_flags(&dst_c, flags | MountAttrFlags::NOSUID)?;\n    }\n\n    // Ensure original symlink paths are available.\n    create_symlinks(&new_root, exceptions.symlinks)?;\n\n    // Bind mount old procfs.\n    let old_proc_c = CString::new(\"/proc\").unwrap();\n    let new_proc = new_root.join(\"proc\");\n    let new_proc_c = CString::new(new_proc.as_os_str().as_bytes()).unwrap();\n    fs::create_dir_all(&new_proc)?;\n    bind_mount(&old_proc_c, &new_proc_c)?;\n\n    // Pivot root to `new_root`, placing the old root at the same location.\n    pivot_root(&new_root_c, &new_root_c)?;\n\n    // Remove old root mounted at /, leaving only the new root at the same location.\n    let root_c = CString::new(\"/\").unwrap();\n    umount(&root_c)?;\n\n    // Prevent child mount namespaces from accessing this namespace's mounts.\n    deny_mount_propagation()?;\n\n    Ok(())\n}\n\n/// Create missing symlinks.\n///\n/// If the parent directory of a symlink is mapped, we do not need to map the\n/// symlink ourselves and it's not possible to mount on top of it anyway. So\n/// here we make sure that symlinks are created if no bind mount was created for\n/// their parent directory.\nfn create_symlinks(new_root: &Path, symlinks: Vec<(PathBuf, PathBuf)>) -> io::Result<()> {\n    for (symlink, target) in symlinks {\n        // Ignore symlinks if a parent bind mount exists.\n        let unrooted_path = symlink.strip_prefix(\"/\").unwrap();\n        let dst = new_root.join(unrooted_path);\n        if dst.symlink_metadata().is_ok() {\n            continue;\n        }\n\n        // Create all parent directories.\n        let parent = match symlink.parent() {\n            Some(parent) => parent,\n            None => continue,\n        };\n        copy_tree(parent, new_root)?;\n\n        // Create the symlink.\n        unixfs::symlink(target, dst)?;\n    }\n\n    Ok(())\n}\n\n/// Replicate a directory tree under a different directory.\n///\n/// This will create all missing empty diretories and copy their permissions\n/// from the source tree.\n///\n/// If `src` ends in a file, an empty file with matching permissions will be\n/// created.\nfn copy_tree(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> io::Result<()> {\n    let mut dst = dst.as_ref().to_path_buf();\n    let mut src_sub = PathBuf::new();\n    let src = src.as_ref();\n\n    for component in src.components() {\n        // Append root only to source.\n        if component == Component::RootDir {\n            src_sub = src_sub.join(component);\n            continue;\n        }\n\n        src_sub = src_sub.join(component);\n        dst = dst.join(component);\n\n        // Skip nodes that already exist.\n        if dst.exists() {\n            continue;\n        }\n\n        // Create target file/directory.\n        let metadata = src_sub.metadata()?;\n        if metadata.is_dir() {\n            fs::create_dir(&dst)?;\n        } else {\n            File::create(&dst)?;\n        }\n\n        // Copy permissions.\n        let permissions = metadata.permissions();\n        fs::set_permissions(&dst, permissions)?;\n    }\n\n    Ok(())\n}\n\n/// Mount a new tmpfs.\nfn mount_tmpfs(dst: &CStr) -> io::Result<()> {\n    let flags = MountFlags::empty();\n    let fstype = CString::new(\"tmpfs\").unwrap();\n    let res = unsafe {\n        libc::mount(ptr::null(), dst.as_ptr(), fstype.as_ptr(), flags.bits(), ptr::null())\n    };\n\n    if res == 0 {\n        Ok(())\n    } else {\n        Err(IoError::last_os_error())\n    }\n}\n\n/// Mount a new procfs.\npub fn mount_proc(dst: &CStr) -> io::Result<()> {\n    let flags = MountFlags::NOSUID | MountFlags::NODEV | MountFlags::NOEXEC;\n    let fstype = CString::new(\"proc\").unwrap();\n    let res = unsafe {\n        libc::mount(fstype.as_ptr(), dst.as_ptr(), fstype.as_ptr(), flags.bits(), ptr::null())\n    };\n\n    if res == 0 {\n        Ok(())\n    } else {\n        Err(IoError::last_os_error())\n    }\n}\n\n/// Create a new bind mount.\nfn bind_mount(src: &CStr, dst: &CStr) -> io::Result<()> {\n    let flags = MountFlags::BIND | MountFlags::RECURSIVE;\n    let res =\n        unsafe { libc::mount(src.as_ptr(), dst.as_ptr(), ptr::null(), flags.bits(), ptr::null()) };\n\n    if res == 0 {\n        Ok(())\n    } else {\n        Err(IoError::last_os_error())\n    }\n}\n\n/// Remount an existing bind mount with a new set of mount flags.\nfn update_mount_flags(mount: &CStr, flags: MountAttrFlags) -> io::Result<()> {\n    let attrs = MountAttr { attr_set: flags.bits(), ..Default::default() };\n\n    let res = unsafe {\n        libc::syscall(\n            libc::SYS_mount_setattr,\n            libc::AT_FDCWD,\n            mount.as_ptr(),\n            libc::AT_RECURSIVE,\n            &attrs as *const _,\n            mem::size_of::<MountAttr>(),\n        )\n    };\n\n    if res == 0 {\n        Ok(())\n    } else {\n        Err(IoError::last_os_error())\n    }\n}\n\n/// Recursively update the root to deny mount propagation.\nfn deny_mount_propagation() -> io::Result<()> {\n    let flags = MountFlags::PRIVATE | MountFlags::RECURSIVE;\n    let root = CString::new(\"/\").unwrap();\n    let res =\n        unsafe { libc::mount(ptr::null(), root.as_ptr(), ptr::null(), flags.bits(), ptr::null()) };\n\n    if res == 0 {\n        Ok(())\n    } else {\n        Err(IoError::last_os_error())\n    }\n}\n\n/// Change root directory to `new_root` and mount the old root in `put_old`.\n///\n/// The `put_old` directory must be at or undearneath `new_root`.\nfn pivot_root(new_root: &CStr, put_old: &CStr) -> io::Result<()> {\n    // Get target working directory path.\n    let working_dir = env::current_dir().unwrap_or_else(|_| PathBuf::from(\"/\"));\n\n    let result =\n        unsafe { libc::syscall(libc::SYS_pivot_root, new_root.as_ptr(), put_old.as_ptr()) };\n\n    if result != 0 {\n        return Err(IoError::last_os_error());\n    }\n\n    // Attempt to recover working directory, or switch to root.\n    //\n    // Without this, the user's working directory would stay the same, giving him\n    // full access to it even if it is not bound.\n    if env::set_current_dir(working_dir).is_err() {\n        env::set_current_dir(\"/\")?;\n    }\n\n    Ok(())\n}\n\n/// Unmount a filesystem.\nfn umount(target: &CStr) -> io::Result<()> {\n    let result = unsafe { libc::umount2(target.as_ptr(), libc::MNT_DETACH) };\n\n    match result {\n        0 => Ok(()),\n        _ => Err(IoError::last_os_error()),\n    }\n}\n\n/// Create a new user namespace.\n///\n/// The parent and child UIDs and GIDs define the user and group mappings\n/// between the parent namespace and the new user namespace.\npub fn create_user_namespace(\n    child_uid: u32,\n    child_gid: u32,\n    extra_namespaces: Namespaces,\n) -> io::Result<()> {\n    // Get current user's EUID and EGID.\n    let parent_euid = unsafe { libc::geteuid() };\n    let parent_egid = unsafe { libc::getegid() };\n\n    // Create the namespace.\n    unshare(Namespaces::USER | extra_namespaces)?;\n\n    // Map the UID and GID.\n    map_ids(parent_euid, parent_egid, child_uid, child_gid)?;\n\n    Ok(())\n}\n\n/// Update /proc uid/gid maps.\n///\n/// This should be called after creating a user namespace to ensure proper ID\n/// mappings.\npub fn map_ids(\n    parent_euid: u32,\n    parent_egid: u32,\n    child_uid: u32,\n    child_gid: u32,\n) -> io::Result<()> {\n    let uid_map = format!(\"{child_uid} {parent_euid} 1\\n\");\n    let gid_map = format!(\"{child_gid} {parent_egid} 1\\n\");\n    fs::write(\"/proc/self/uid_map\", uid_map.as_bytes())?;\n    fs::write(\"/proc/self/setgroups\", b\"deny\")?;\n    fs::write(\"/proc/self/gid_map\", gid_map.as_bytes())?;\n    Ok(())\n}\n\n/// Enter a namespace.\nfn unshare(namespaces: Namespaces) -> io::Result<()> {\n    let result = unsafe { libc::unshare(namespaces.bits()) };\n    match result {\n        0 => Ok(()),\n        _ => Err(IoError::last_os_error()),\n    }\n}\n\nbitflags! {\n    /// Mount syscall flags.\n    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n    pub struct MountFlags: libc::c_ulong {\n        /// Ignore suid and sgid bits.\n        const NOSUID = libc::MS_NOSUID;\n        /// Disallow access to device special files.\n        const NODEV = libc::MS_NODEV;\n        /// Disallow program execution.\n        const NOEXEC = libc::MS_NOEXEC;\n        /// Create a bind mount.\n        const BIND = libc::MS_BIND;\n        /// Used in conjuction with [`Self::BIND`] to create a recursive bind mount, and\n        /// in conjuction with the propagation type flags to recursively change the\n        /// propagation type of all of the mounts in a sub-tree.\n        const RECURSIVE = libc::MS_REC;\n        /// Make this mount private. Mount and unmount events do not propagate into or\n        /// out of this mount.\n        const PRIVATE = libc::MS_PRIVATE;\n        /// Do not follow symbolic links when resolving paths.\n        const NOSYMFOLLOW = 256;\n    }\n}\n\n/// Parameter for the `mount_setattr` syscall.\n#[repr(C)]\n#[derive(Default)]\nstruct MountAttr {\n    attr_set: u64,\n    attr_clr: u64,\n    propagation: u64,\n    userns_fd: u64,\n}\n\nbitflags! {\n    /// Flags for the `mount_setattr` syscall.\n    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n    pub struct MountAttrFlags: u64 {\n        /// Mount read-only.\n        const RDONLY          = 0x00000001;\n        /// Ignore suid and sgid bits.\n        const NOSUID          = 0x00000002;\n        /// Disallow access to device special files.\n        const NODEV\t          = 0x00000004;\n        /// Disallow program execution.\n        const NOEXEC          = 0x00000008;\n\n        /// Setting on how atime should be updated.\n        const _ATIME          = 0x00000070;\n        /// - Update atime relative to mtime/ctime.\n        const RELATI          = 0x00000000;\n        /// - Do not update access times.\n        const NOATIM          = 0x00000010;\n        /// - Always perform atime updates.\n        const STRICTATIME     = 0x00000020;\n\n        /// Do not update directory access times.\n        const NODIRATIME      = 0x00000080;\n        /// Idmap mount to @userns_fd in struct mount_attr.\n        const IDMAP           = 0x00100000;\n        /// Do not follow symlinks.\n        const NOSYMFOLLOW     = 0x00200000;\n    }\n}\n\nbitflags! {\n    /// Unshare system call namespace flags.\n    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n    pub struct Namespaces: libc::c_int {\n        /// Unshare the file descriptor table, so that the calling process no longer\n        /// shares its file descriptors with any other process.\n        const FILES = libc::CLONE_FILES;\n        /// Unshare filesystem attributes, so that the calling process no longer shares\n        /// its root directory, current directory, or umask attributes with any other process.\n        const FS = libc::CLONE_FS;\n        /// Unshare the cgroup namespace.\n        const CGROUP = libc::CLONE_NEWCGROUP;\n        /// Unshare the IPC namespace, so that the calling process has a private copy of\n        /// the IPC namespace which is not shared with any other process. Specifying\n        /// this flag automatically implies [`Namespaces::SYSVSEM`] as well.\n        const IPC = libc::CLONE_NEWIPC;\n        /// Unshare the network namespace, so that the calling process is moved into a\n        /// new network namespace which is not shared with any previously existing process.\n        const NETWORK = libc::CLONE_NEWNET;\n        /// Unshare the mount namespace, so that the calling process has a private copy\n        /// of its namespace which is not shared with any other process. Specifying this\n        /// flag automatically implies [`Namespaces::FS`] as well.\n        const MOUNT = libc::CLONE_NEWNS;\n        /// Unshare the PID namespace, so that the calling process has a new PID\n        /// namespace for its children which is not shared with any previously existing\n        /// process. The calling process is **not** moved into the new namespace. The\n        /// first child created by the calling process will have the process ID 1 and\n        /// will assume the role of init in the new namespace. Specifying this flag\n        /// automatically implies [`libc::CLONE_THREAD`] as well.\n        const PID = libc::CLONE_NEWPID;\n        /// Unshare the time namespace, so that the calling process has a new time\n        /// namespace for its children which is not shared with any previously existing\n        /// process. The calling process is **not** moved into the new namespace.\n        const TIME = 0x80;\n        /// Unshare the user namespace, so that the calling process is moved into a new\n        /// user namespace which is not shared with any previously existing process. The\n        /// caller obtains a full set of capabilities in the new namespace.\n        ///\n        /// Requires that the calling process is not threaded; specifying this flag\n        /// automatically implies [`libc::CLONE_THREAD`] and [`Namespaces::FS`] as well.\n        const USER = libc::CLONE_NEWUSER;\n        /// Unshare the UTS IPC namespace, so that the calling process has a private\n        /// copy of the UTS namespace which is not shared with any other process.\n        const UTS = libc::CLONE_NEWUTS;\n        /// Unshare System V semaphore adjustment (semadj) values, so that the calling\n        /// process has a new empty semadj list that is not shared with any other\n        /// process. If this is the last process that has a reference to the process's\n        /// current semadj list, then the adjustments in that list are applied to the\n        /// corresponding semaphores\n        const SYSVSEM = libc::CLONE_SYSVSEM;\n    }\n}\n"
  },
  {
    "path": "src/linux/seccomp.rs",
    "content": "//! Seccomp system call filtering.\n\nuse std::collections::BTreeMap;\n\nuse seccompiler::{\n    BpfProgram, SeccompAction, SeccompCmpArgLen, SeccompCmpOp, SeccompCondition, SeccompFilter,\n    SeccompRule, TargetArch,\n};\n\nuse crate::Result;\n\n#[cfg(target_arch = \"x86_64\")]\nconst ARCH: TargetArch = TargetArch::x86_64;\n#[cfg(target_arch = \"aarch64\")]\nconst ARCH: TargetArch = TargetArch::aarch64;\n\n/// Bitmask for the clone syscall seccomp filter.\n///\n/// A 1 in the bitmask means system calls with this flag set will be denied.\n///\n/// Filtered flags:\n///  - CLONE_NEWNS     = 0x00020000\n///  - CLONE_NEWCGROUP = 0x02000000\n///  - CLONE_NEWUTS    = 0x04000000\n///  - CLONE_NEWIPC    = 0x08000000\n///  - CLONE_NEWUSER   = 0x10000000\n///  - CLONE_NEWPID    = 0x20000000\n///  - CLONE_NEWNET    = 0x40000000\nconst CLONE_NAMESPACE_FILTER: u32 = 0b01111110000000100000000000000000;\n\n/// Seccomp system call filter.\n///\n/// This filter is aimed at restricting system calls which shouldn't be\n/// executable by an untrusted client.\n#[derive(Default)]\npub struct SyscallFilter;\n\nimpl SyscallFilter {\n    /// Apply the seccomp filter.\n    pub fn apply() -> Result<()> {\n        let mut rules = BTreeMap::new();\n\n        // Add exceptions for allowed syscalls.\n        for syscall in SYSCALL_WHITELIST {\n            rules.insert(*syscall, Vec::new());\n        }\n\n        // Add exception for the `clone` syscall.\n        let allow_clone = SeccompCondition::new(\n            0,\n            SeccompCmpArgLen::Qword,\n            SeccompCmpOp::MaskedEq(CLONE_NAMESPACE_FILTER as u64),\n            0,\n        )?;\n        let clone_rule = SeccompRule::new(vec![allow_clone])?;\n        rules.insert(libc::SYS_clone, vec![clone_rule]);\n\n        // Apply seccomp filter.\n        let filter = SeccompFilter::new(\n            rules,\n            // Action performed if no rule matches.\n            SeccompAction::Errno(libc::EACCES as u32),\n            // Action performed if any rule matches.\n            SeccompAction::Allow,\n            ARCH,\n        )?;\n        let program: BpfProgram = filter.try_into()?;\n        seccompiler::apply_filter(&program)?;\n\n        // Change `clone3` syscall error to \"not implemented\", to force `clone` usage.\n        let mut rules = BTreeMap::new();\n        rules.insert(libc::SYS_clone3, Vec::new());\n        let filter = SeccompFilter::new(\n            rules,\n            // Action performed if no rule matches.\n            SeccompAction::Allow,\n            // Action performed if any rule matches.\n            SeccompAction::Errno(libc::ENOSYS as u32),\n            ARCH,\n        )?;\n        let program: BpfProgram = filter.try_into()?;\n        seccompiler::apply_filter(&program)?;\n\n        Ok(())\n    }\n}\n\n/// Unconditionally allowed syscalls for networking.\nconst SYSCALL_WHITELIST: &[libc::c_long] = &[\n    libc::SYS_read,\n    libc::SYS_write,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_open,\n    libc::SYS_close,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_stat,\n    libc::SYS_fstat,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_lstat,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_poll,\n    libc::SYS_lseek,\n    libc::SYS_mmap,\n    libc::SYS_mprotect,\n    libc::SYS_munmap,\n    libc::SYS_brk,\n    libc::SYS_rt_sigaction,\n    libc::SYS_rt_sigprocmask,\n    libc::SYS_rt_sigreturn,\n    libc::SYS_ioctl,\n    libc::SYS_pread64,\n    libc::SYS_pwrite64,\n    libc::SYS_readv,\n    libc::SYS_writev,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_access,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_pipe,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_select,\n    libc::SYS_sched_yield,\n    libc::SYS_mremap,\n    libc::SYS_msync,\n    libc::SYS_mincore,\n    libc::SYS_madvise,\n    libc::SYS_shmget,\n    libc::SYS_shmat,\n    libc::SYS_shmctl,\n    libc::SYS_dup,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_dup2,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_pause,\n    libc::SYS_nanosleep,\n    libc::SYS_getitimer,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_alarm,\n    libc::SYS_setitimer,\n    libc::SYS_getpid,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_sendfile,\n    libc::SYS_connect,\n    libc::SYS_accept,\n    libc::SYS_sendto,\n    libc::SYS_recvfrom,\n    libc::SYS_sendmsg,\n    libc::SYS_recvmsg,\n    libc::SYS_shutdown,\n    libc::SYS_bind,\n    libc::SYS_listen,\n    libc::SYS_getsockname,\n    libc::SYS_getpeername,\n    libc::SYS_setsockopt,\n    libc::SYS_getsockopt,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_fork,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_vfork,\n    libc::SYS_execve,\n    libc::SYS_exit,\n    libc::SYS_wait4,\n    libc::SYS_kill,\n    libc::SYS_uname,\n    libc::SYS_semget,\n    libc::SYS_semop,\n    libc::SYS_semctl,\n    libc::SYS_shmdt,\n    libc::SYS_msgget,\n    libc::SYS_msgsnd,\n    libc::SYS_msgrcv,\n    libc::SYS_msgctl,\n    libc::SYS_fcntl,\n    libc::SYS_flock,\n    libc::SYS_fsync,\n    libc::SYS_fdatasync,\n    libc::SYS_truncate,\n    libc::SYS_ftruncate,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_getdents,\n    libc::SYS_getcwd,\n    libc::SYS_chdir,\n    libc::SYS_fchdir,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_rename,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_mkdir,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_rmdir,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_creat,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_link,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_unlink,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_symlink,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_readlink,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_chmod,\n    libc::SYS_fchmod,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_chown,\n    libc::SYS_fchown,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_lchown,\n    libc::SYS_umask,\n    libc::SYS_gettimeofday,\n    libc::SYS_getrlimit,\n    libc::SYS_getrusage,\n    libc::SYS_sysinfo,\n    libc::SYS_times,\n    libc::SYS_getuid,\n    libc::SYS_getgid,\n    libc::SYS_setuid,\n    libc::SYS_setgid,\n    libc::SYS_geteuid,\n    libc::SYS_getegid,\n    libc::SYS_setpgid,\n    libc::SYS_getppid,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_getpgrp,\n    libc::SYS_setsid,\n    libc::SYS_setreuid,\n    libc::SYS_setregid,\n    libc::SYS_getgroups,\n    libc::SYS_setgroups,\n    libc::SYS_setresuid,\n    libc::SYS_getresuid,\n    libc::SYS_setresgid,\n    libc::SYS_getresgid,\n    libc::SYS_getpgid,\n    libc::SYS_setfsuid,\n    libc::SYS_setfsgid,\n    libc::SYS_getsid,\n    libc::SYS_capget,\n    libc::SYS_capset,\n    libc::SYS_rt_sigpending,\n    libc::SYS_rt_sigtimedwait,\n    libc::SYS_rt_sigqueueinfo,\n    libc::SYS_rt_sigsuspend,\n    libc::SYS_sigaltstack,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_utime,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_mknod,\n    libc::SYS_statfs,\n    libc::SYS_fstatfs,\n    libc::SYS_getpriority,\n    libc::SYS_setpriority,\n    libc::SYS_sched_setparam,\n    libc::SYS_sched_getparam,\n    libc::SYS_sched_setscheduler,\n    libc::SYS_sched_getscheduler,\n    libc::SYS_sched_get_priority_max,\n    libc::SYS_sched_get_priority_min,\n    libc::SYS_sched_rr_get_interval,\n    libc::SYS_mlock,\n    libc::SYS_munlock,\n    libc::SYS_mlockall,\n    libc::SYS_munlockall,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_modify_ldt,\n    libc::SYS_prctl,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_arch_prctl,\n    libc::SYS_adjtimex,\n    libc::SYS_setrlimit,\n    libc::SYS_sync,\n    libc::SYS_gettid,\n    libc::SYS_readahead,\n    libc::SYS_setxattr,\n    libc::SYS_lsetxattr,\n    libc::SYS_fsetxattr,\n    libc::SYS_getxattr,\n    libc::SYS_lgetxattr,\n    libc::SYS_fgetxattr,\n    libc::SYS_listxattr,\n    libc::SYS_llistxattr,\n    libc::SYS_flistxattr,\n    libc::SYS_removexattr,\n    libc::SYS_lremovexattr,\n    libc::SYS_fremovexattr,\n    libc::SYS_tkill,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_time,\n    libc::SYS_futex,\n    libc::SYS_sched_setaffinity,\n    libc::SYS_sched_getaffinity,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_set_thread_area,\n    libc::SYS_io_setup,\n    libc::SYS_io_destroy,\n    libc::SYS_io_getevents,\n    libc::SYS_io_submit,\n    libc::SYS_io_cancel,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_get_thread_area,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_epoll_create,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_epoll_ctl_old,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_epoll_wait_old,\n    libc::SYS_remap_file_pages,\n    libc::SYS_getdents64,\n    libc::SYS_set_tid_address,\n    libc::SYS_restart_syscall,\n    libc::SYS_semtimedop,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_fadvise64,\n    libc::SYS_timer_create,\n    libc::SYS_timer_settime,\n    libc::SYS_timer_gettime,\n    libc::SYS_timer_getoverrun,\n    libc::SYS_timer_delete,\n    libc::SYS_clock_gettime,\n    libc::SYS_clock_getres,\n    libc::SYS_clock_nanosleep,\n    libc::SYS_exit_group,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_epoll_wait,\n    libc::SYS_epoll_ctl,\n    libc::SYS_tgkill,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_utimes,\n    libc::SYS_mq_open,\n    libc::SYS_mq_unlink,\n    libc::SYS_mq_timedsend,\n    libc::SYS_mq_timedreceive,\n    libc::SYS_mq_notify,\n    libc::SYS_mq_getsetattr,\n    libc::SYS_waitid,\n    libc::SYS_ioprio_set,\n    libc::SYS_ioprio_get,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_inotify_init,\n    libc::SYS_inotify_add_watch,\n    libc::SYS_inotify_rm_watch,\n    libc::SYS_migrate_pages,\n    libc::SYS_openat,\n    libc::SYS_mkdirat,\n    libc::SYS_mknodat,\n    libc::SYS_fchownat,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_futimesat,\n    libc::SYS_newfstatat,\n    libc::SYS_unlinkat,\n    libc::SYS_renameat,\n    libc::SYS_linkat,\n    libc::SYS_symlinkat,\n    libc::SYS_readlinkat,\n    libc::SYS_fchmodat,\n    libc::SYS_faccessat,\n    libc::SYS_pselect6,\n    libc::SYS_ppoll,\n    libc::SYS_set_robust_list,\n    libc::SYS_get_robust_list,\n    libc::SYS_splice,\n    libc::SYS_tee,\n    libc::SYS_sync_file_range,\n    libc::SYS_vmsplice,\n    libc::SYS_utimensat,\n    libc::SYS_epoll_pwait,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_signalfd,\n    libc::SYS_timerfd_create,\n    #[cfg(target_arch = \"x86_64\")]\n    libc::SYS_eventfd,\n    libc::SYS_fallocate,\n    libc::SYS_timerfd_settime,\n    libc::SYS_timerfd_gettime,\n    libc::SYS_accept4,\n    libc::SYS_signalfd4,\n    libc::SYS_eventfd2,\n    libc::SYS_epoll_create1,\n    libc::SYS_dup3,\n    libc::SYS_pipe2,\n    libc::SYS_inotify_init1,\n    libc::SYS_preadv,\n    libc::SYS_pwritev,\n    libc::SYS_rt_tgsigqueueinfo,\n    libc::SYS_recvmmsg,\n    libc::SYS_fanotify_mark,\n    libc::SYS_prlimit64,\n    libc::SYS_name_to_handle_at,\n    libc::SYS_syncfs,\n    libc::SYS_sendmmsg,\n    libc::SYS_getcpu,\n    libc::SYS_sched_setattr,\n    libc::SYS_sched_getattr,\n    libc::SYS_renameat2,\n    libc::SYS_seccomp,\n    libc::SYS_getrandom,\n    libc::SYS_memfd_create,\n    libc::SYS_execveat,\n    libc::SYS_membarrier,\n    libc::SYS_mlock2,\n    libc::SYS_copy_file_range,\n    libc::SYS_preadv2,\n    libc::SYS_pwritev2,\n    libc::SYS_pkey_mprotect,\n    libc::SYS_pkey_alloc,\n    libc::SYS_pkey_free,\n    libc::SYS_statx,\n    libc::SYS_rseq,\n    libc::SYS_pidfd_send_signal,\n    libc::SYS_pidfd_open,\n    libc::SYS_close_range,\n    libc::SYS_openat2,\n    libc::SYS_faccessat2,\n    libc::SYS_epoll_pwait2,\n    libc::SYS_landlock_create_ruleset,\n    libc::SYS_landlock_add_rule,\n    libc::SYS_landlock_restrict_self,\n    libc::SYS_memfd_secret,\n    libc::SYS_process_mrelease,\n    libc::SYS_futex_waitv,\n    libc::SYS_socketpair,\n    libc::SYS_socket,\n    libc::SYS_io_uring_enter,\n    libc::SYS_io_uring_register,\n    libc::SYS_io_uring_setup,\n];\n"
  },
  {
    "path": "src/macos.rs",
    "content": "//! Linux sandboxing.\n//!\n//! This module implements sandboxing on macOS using `sandbox_init`.\n\nuse std::collections::HashMap;\nuse std::ffi::{CStr, CString};\nuse std::io::{Result as IoResult, Write};\nuse std::path::{Path, PathBuf};\nuse std::{fs, ptr};\n\nuse bitflags::bitflags;\n\nuse crate::error::{Error, Result};\nuse crate::{Child, Command, Exception, Sandbox};\n\n/// Deny-all fallback rule.\nstatic DEFAULT_RULE: &[u8] = b\"\\\n(version 1)\n(import \\\"system.sb\\\")\n\n(deny default)\n(allow mach*)\n(allow ipc*)\n(allow signal (target others))\n(allow process-fork)\n(allow sysctl*)\n(allow system*)\n(allow file-read-metadata)\n(system-network)\n\";\n\n/// macOS sandboxing based on Seatbelt.\n#[derive(Default)]\npub struct MacSandbox {\n    path_exceptions: HashMap<String, PathException>,\n    env_exceptions: Vec<String>,\n    net_exception: bool,\n    full_env: bool,\n}\n\nimpl Sandbox for MacSandbox {\n    fn new() -> Self {\n        Self::default()\n    }\n\n    fn add_exception(&mut self, exception: Exception) -> Result<&mut Self> {\n        match exception {\n            Exception::Read(path) => self.update_path_exceptions(path, PathException::READ)?,\n            Exception::WriteAndRead(path) => {\n                self.update_path_exceptions(path, PathException::WRITE | PathException::READ)?\n            },\n            Exception::ExecuteAndRead(path) => {\n                self.update_path_exceptions(path, PathException::EXECUTE | PathException::READ)?\n            },\n            Exception::Networking => self.net_exception = true,\n            Exception::Environment(key) => {\n                self.env_exceptions.push(key);\n                return Ok(self);\n            },\n            Exception::FullEnvironment => {\n                self.full_env = true;\n                return Ok(self);\n            },\n        }\n        Ok(self)\n    }\n\n    fn spawn(self, mut sandboxee: Command) -> Result<Child> {\n        // Remove environment variables.\n        if !self.full_env {\n            crate::restrict_env_variables(&self.env_exceptions);\n        }\n\n        // Create the seatbelt sandbox profile.\n        let profile = self.create_profile()?;\n        let profile =\n            CString::new(profile).map_err(|_| Error::ActivationFailed(\"invalid profile\".into()))?;\n\n        let mut error = ptr::null_mut();\n        let result = unsafe { sandbox_init(profile.as_ptr(), 0, &mut error) };\n\n        if result == 0 {\n            Ok(sandboxee.spawn()?)\n        } else {\n            unsafe {\n                let error_text = CStr::from_ptr(error)\n                    .to_str()\n                    .map_err(|_| Error::ActivationFailed(\"sandbox_init failed\".into()))?\n                    .to_owned();\n                sandbox_free_error(error);\n\n                Err(Error::ActivationFailed(error_text))\n            }\n        }\n    }\n}\n\nimpl MacSandbox {\n    /// Add or modify a path's exceptions.\n    fn update_path_exceptions(&mut self, path: PathBuf, exceptions: PathException) -> Result<()> {\n        // Canonicalize all exception paths.\n        //\n        // Since the macOS sandbox only cares about permissions for symlink targets, due\n        // to the `(allow file-read-metadata)` rule, we don't need to bother with\n        // keeping the original paths.\n        let escaped_path = escape_path(&path)?;\n\n        let exception = self.path_exceptions.entry(escaped_path).or_insert(PathException::empty());\n        exception.insert(exceptions);\n\n        Ok(())\n    }\n\n    /// Create a seatbelt profile for the requested sandbox configuration.\n    fn create_profile(&self) -> Result<Vec<u8>> {\n        let mut profile = DEFAULT_RULE.to_vec();\n\n        // Sort by component count to ensure parent paths appear before descendants.\n        let mut path_exceptions: Vec<_> = self.path_exceptions.iter().collect();\n        path_exceptions.sort_unstable_by(|a, b| a.0.len().cmp(&b.0.len()));\n\n        for (path, exception) in path_exceptions {\n            // Deny all access to clear existing permission grants.\n            Self::revoke_path_access(&mut profile, path)?;\n\n            if exception.contains(PathException::READ) {\n                let rule = PathRule::new(RuleMode::Allow, \"file-read*\", path.into());\n                rule.write_to(&mut profile)?;\n            }\n            if exception.contains(PathException::WRITE) {\n                let rule = PathRule::new(RuleMode::Allow, \"file-write*\", path.into());\n                rule.write_to(&mut profile)?;\n            }\n            if exception.contains(PathException::EXECUTE) {\n                let rule = PathRule::new(RuleMode::Allow, \"process-exec\", path.into());\n                rule.write_to(&mut profile)?;\n            }\n        }\n\n        if self.net_exception {\n            profile.write_all(b\"(allow network*)\\n\")?;\n        }\n\n        Ok(profile)\n    }\n\n    /// Revoke all access permisisons for a path.\n    ///\n    /// This is necessary to grant more restrictive permissions to a child of a\n    /// directory which was previously granted permissions.\n    fn revoke_path_access(buffer: &mut Vec<u8>, path: &str) -> Result<()> {\n        let rule = PathRule::new(RuleMode::Deny, \"file-read*\", path.into());\n        rule.write_to(buffer)?;\n\n        let rule = PathRule::new(RuleMode::Deny, \"file-write*\", path.into());\n        rule.write_to(buffer)?;\n\n        let rule = PathRule::new(RuleMode::Deny, \"process-exec\", path.into());\n        rule.write_to(buffer)?;\n\n        Ok(())\n    }\n}\n\nstruct PathRule {\n    mode: RuleMode,\n    access_type: &'static str,\n    path: String,\n}\n\nimpl PathRule {\n    fn new(mode: RuleMode, access_type: &'static str, path: String) -> Self {\n        Self { mode, access_type, path }\n    }\n\n    /// Write this rule to a profile.\n    fn write_to(&self, buffer: &mut Vec<u8>) -> IoResult<()> {\n        buffer.write_all(b\"(\")?;\n        buffer.write_all(self.mode.as_str().as_bytes())?;\n        buffer.write_all(b\" \")?;\n\n        buffer.write_all(self.access_type.as_bytes())?;\n\n        buffer.write_all(b\" (subpath \")?;\n        buffer.write_all(self.path.as_bytes())?;\n        buffer.write_all(b\"))\\n\")?;\n\n        Ok(())\n    }\n}\n\n/// Mode for a seatbelt rule.\nenum RuleMode {\n    Allow,\n    Deny,\n}\n\nimpl RuleMode {\n    fn as_str(&self) -> &str {\n        match self {\n            Self::Allow => \"allow\",\n            Self::Deny => \"deny\",\n        }\n    }\n}\n\nbitflags! {\n    /// Types of sandbox filesystem exceptions.\n    struct PathException: u8 {\n        const EXECUTE = 0b0001;\n        const WRITE   = 0b0010;\n        const READ    = 0b0100;\n    }\n}\n\n/// Escape a path: /tt/in\\a\"x -> \"/tt/in\\\\a\\\"x\"\nfn escape_path(path: &Path) -> Result<String> {\n    // Canonicalize the incoming path to support relative paths.\n    // The `subpath` action only allows absolute paths.\n    let canonical_path =\n        fs::canonicalize(&path).map_err(|_| Error::InvalidPath(path.to_path_buf()))?;\n\n    let mut path_str = canonical_path\n        .into_os_string()\n        .into_string()\n        .map_err(|_| Error::InvalidPath(path.to_path_buf()))?;\n    // Paths in `subpath` expressions must not end with /.\n    while path_str.ends_with('/') && path_str != \"/\" {\n        String::pop(&mut path_str);\n    }\n    path_str = path_str.replace('\"', r#\"\\\"\"#);\n    path_str = path_str.replace('\\\\', r#\"\\\\\"#);\n    Ok(format!(\"\\\"{path_str}\\\"\"))\n}\n\nextern \"C\" {\n    fn sandbox_init(profile: *const i8, flags: u64, errorbuf: *mut *mut i8) -> i32;\n    fn sandbox_free_error(errorbuf: *mut i8);\n}\n"
  },
  {
    "path": "src/process/linux.rs",
    "content": "//! Linux process implementation.\n//!\n//! Documentation in this module has been largely copied from [STD] and is\n//! thus dual-licensed under MIT and Apache.\n//!\n//! [STD]: https://doc.rust-lang.org/std/process/index.html\n\nuse std::ffi::{OsStr, OsString};\nuse std::io::{self, Read, Write};\nuse std::mem;\nuse std::os::fd::{AsRawFd, OwnedFd, RawFd};\nuse std::os::unix::ffi::OsStrExt;\nuse std::os::unix::process::ExitStatusExt;\npub use std::process::{ExitStatus, Output};\n\nuse rustix::fs::{Mode, OFlags};\nuse rustix::pipe::pipe;\nuse rustix::process::{Pid, Signal};\n\n/// A process builder, providing fine-grained control\n/// over how a new process should be spawned.\n///\n/// A default configuration can be generated using `Command::new(program)`,\n/// where `program` gives a path to the program to be executed. Additional\n/// builder methods allow the configuration to be changed (for example, by\n/// adding arguments) prior to spawning:\n///\n/// ```no_run\n/// use birdcage::process::Command;\n///\n/// Command::new(\"sh\").arg(\"-c\").arg(\"echo hello\");\n/// ```\npub struct Command {\n    program: OsString,\n    args: Vec<OsString>,\n    pub(crate) stdin: Stdio,\n    pub(crate) stdout: Stdio,\n    pub(crate) stderr: Stdio,\n}\n\nimpl Command {\n    /// Constructs a new `Command` for launching the program at\n    /// path `program`, with the following default configuration:\n    ///\n    /// * No arguments to the program\n    /// * Inherit the current process's working directory\n    /// * Inherit stdin/stdout/stderr\n    ///\n    /// Builder methods are provided to change these defaults and\n    /// otherwise configure the process.\n    ///\n    /// If `program` is not an absolute path, the `PATH` will be searched in\n    /// an OS-defined way.\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::Command;\n    ///\n    /// Command::new(\"sh\");\n    /// ```\n    pub fn new<S: AsRef<OsStr>>(program: S) -> Self {\n        let program = program.as_ref().to_os_string();\n        Self {\n            program,\n            stdout: Default::default(),\n            stderr: Default::default(),\n            stdin: Default::default(),\n            args: Default::default(),\n        }\n    }\n\n    /// Adds an argument to pass to the program.\n    ///\n    /// Only one argument can be passed per use. So instead of:\n    ///\n    /// ```no_run\n    /// # birdcage::process::Command::new(\"sh\")\n    /// .arg(\"-C /path/to/repo\")\n    /// # ;\n    /// ```\n    ///\n    /// usage would be:\n    ///\n    /// ```no_run\n    /// # birdcage::process::Command::new(\"sh\")\n    /// .arg(\"-C\")\n    /// .arg(\"/path/to/repo\")\n    /// # ;\n    /// ```\n    ///\n    /// To pass multiple arguments see [`args`].\n    ///\n    /// [`args`]: Command::args\n    ///\n    /// Note that the argument is not passed through a shell, but given\n    /// literally to the program. This means that shell syntax like quotes,\n    /// escaped characters, word splitting, glob patterns, variable\n    /// substitution, etc. have no effect.\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::Command;\n    ///\n    /// Command::new(\"ls\").arg(\"-l\").arg(\"-a\");\n    /// ```\n    pub fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {\n        let arg = arg.as_ref().to_os_string();\n        self.args.push(arg);\n        self\n    }\n\n    /// Adds multiple arguments to pass to the program.\n    ///\n    /// To pass a single argument see [`arg`].\n    ///\n    /// [`arg`]: Command::arg\n    ///\n    /// Note that the arguments are not passed through a shell, but given\n    /// literally to the program. This means that shell syntax like quotes,\n    /// escaped characters, word splitting, glob patterns, variable\n    /// substitution, etc. have no effect.\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::Command;\n    ///\n    /// Command::new(\"ls\").args([\"-l\", \"-a\"]);\n    /// ```\n    pub fn args<I, S>(&mut self, args: I) -> &mut Self\n    where\n        I: IntoIterator<Item = S>,\n        S: AsRef<OsStr>,\n    {\n        for arg in args {\n            let arg = arg.as_ref().to_os_string();\n            self.args.push(arg);\n        }\n        self\n    }\n\n    /// Configuration for the child process's standard input (stdin) handle.\n    ///\n    /// Defaults to [`inherit`].\n    ///\n    /// [`inherit`]: Stdio::inherit\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::{Command, Stdio};\n    ///\n    /// Command::new(\"ls\").stdin(Stdio::null());\n    /// ```\n    pub fn stdin<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {\n        self.stdin = cfg.into();\n        self\n    }\n\n    /// Configuration for the child process's standard output (stdout) handle.\n    ///\n    /// Defaults to [`inherit`].\n    ///\n    /// [`inherit`]: Stdio::inherit\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::{Command, Stdio};\n    ///\n    /// Command::new(\"ls\").stdout(Stdio::null());\n    /// ```\n    pub fn stdout<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {\n        self.stdout = cfg.into();\n        self\n    }\n\n    /// Configuration for the child process's standard error (stderr) handle.\n    ///\n    /// Defaults to [`inherit`].\n    ///\n    /// [`inherit`]: Stdio::inherit\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::{Command, Stdio};\n    ///\n    /// Command::new(\"ls\").stderr(Stdio::null());\n    /// ```\n    pub fn stderr<T: Into<Stdio>>(&mut self, cfg: T) -> &mut Self {\n        self.stderr = cfg.into();\n        self\n    }\n\n    /// Returns the path to the program that was given to [`Command::new`].\n    ///\n    /// # Examples\n    ///\n    /// ```\n    /// use birdcage::process::Command;\n    ///\n    /// let cmd = Command::new(\"echo\");\n    /// assert_eq!(cmd.get_program(), \"echo\");\n    /// ```\n    pub fn get_program(&self) -> &OsStr {\n        OsStr::from_bytes(self.program.as_bytes())\n    }\n}\n\nimpl From<Command> for std::process::Command {\n    fn from(command: Command) -> Self {\n        let mut std_command = std::process::Command::new(command.program);\n        std_command.args(command.args);\n\n        let stdin: Option<std::process::Stdio> = command.stdin.into();\n        if let Some(stdin) = stdin {\n            std_command.stdin(stdin);\n        }\n\n        let stdout: Option<std::process::Stdio> = command.stdout.into();\n        if let Some(stdout) = stdout {\n            std_command.stdout(stdout);\n        }\n\n        let stderr: Option<std::process::Stdio> = command.stderr.into();\n        if let Some(stderr) = stderr {\n            std_command.stderr(stderr);\n        }\n\n        std_command\n    }\n}\n\n/// Representation of a running or exited child process.\n///\n/// This structure is used to represent and manage child processes. A child\n/// process is created via the [`Command`] struct, which configures the\n/// spawning process and can itself be constructed using a builder-style\n/// interface.\n///\n/// There is no implementation of [`Drop`] for child processes,\n/// so if you do not ensure the `Child` has exited then it will continue to\n/// run, even after the `Child` handle to the child process has gone out of\n/// scope.\n///\n/// Calling [`wait`] (or other functions that wrap around it) will make\n/// the parent process wait until the child has actually exited before\n/// continuing.\n///\n/// # Warning\n///\n/// On some systems, calling [`wait`] or similar is necessary for the OS to\n/// release resources. A process that terminated but has not been waited on is\n/// still around as a \"zombie\". Leaving too many zombies around may exhaust\n/// global resources (for example process IDs).\n///\n/// Birdcage does *not* automatically wait on child processes (not even if the\n/// `Child` is dropped), it is up to the application developer to do so. As a\n/// consequence, dropping `Child` handles without waiting on them first is not\n/// recommended in long-running applications.\n///\n/// # Examples\n///\n/// ```should_panic\n/// use birdcage::process::Command;\n/// use birdcage::{Birdcage, Sandbox};\n///\n/// let mut cmd = Command::new(\"/bin/cat\");\n/// cmd.arg(\"file.txt\");\n/// let mut child = Birdcage::new().spawn(cmd).expect(\"failed to execute child\");\n///\n/// let ecode = child.wait().expect(\"failed to wait on child\");\n///\n/// assert!(ecode.success());\n/// ```\n///\n/// [`wait`]: Child::wait\npub struct Child {\n    /// The handle for writing to the child's standard input (stdin), if it\n    /// has been captured. You might find it helpful to do\n    ///\n    /// ```compile_fail,E0425\n    /// let stdin = child.stdin.take().unwrap();\n    /// ```\n    ///\n    /// to avoid partially moving the `child` and thus blocking yourself from\n    /// calling functions on `child` while using `stdin`.\n    pub stdin: Option<ChildStdin>,\n\n    /// The handle for reading from the child's standard output (stdout), if it\n    /// has been captured. You might find it helpful to do\n    ///\n    /// ```compile_fail,E0425\n    /// let stdout = child.stdout.take().unwrap();\n    /// ```\n    ///\n    /// to avoid partially moving the `child` and thus blocking yourself from\n    /// calling functions on `child` while using `stdout`.\n    pub stdout: Option<ChildStdout>,\n\n    /// The handle for reading from the child's standard error (stderr), if it\n    /// has been captured. You might find it helpful to do\n    ///\n    /// ```compile_fail,E0425\n    /// let stderr = child.stderr.take().unwrap();\n    /// ```\n    ///\n    /// to avoid partially moving the `child` and thus blocking yourself from\n    /// calling functions on `child` while using `stderr`.\n    pub stderr: Option<ChildStderr>,\n\n    exit_signal: OwnedFd,\n    pid: u32,\n}\n\nimpl Child {\n    /// Create child from a process and its Stdio pipes.\n    pub(crate) fn new(\n        pid: i32,\n        exit_signal: OwnedFd,\n        stdin: Option<OwnedFd>,\n        stdout: Option<OwnedFd>,\n        stderr: Option<OwnedFd>,\n    ) -> io::Result<Self> {\n        Ok(Self {\n            exit_signal,\n            pid: pid as u32,\n            stdin: stdin.map(ChildStdin::new).transpose()?,\n            stdout: stdout.map(ChildStdout::new).transpose()?,\n            stderr: stderr.map(ChildStderr::new).transpose()?,\n        })\n    }\n\n    /// Forces the child process to exit. If the child has already exited,\n    /// `Ok(())` is returned.\n    ///\n    /// The mapping to [`ErrorKind`]s is not part of the compatibility contract\n    /// of the function.\n    ///\n    /// This is equivalent to sending a SIGKILL.\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::Command;\n    /// use birdcage::{Birdcage, Sandbox};\n    ///\n    /// let command = Command::new(\"yes\");\n    /// if let Ok(mut child) = Birdcage::new().spawn(command) {\n    ///     child.kill().expect(\"command couldn't be killed\");\n    /// } else {\n    ///     println!(\"yes command didn't start\");\n    /// }\n    /// ```\n    ///\n    /// [`ErrorKind`]: io::ErrorKind\n    /// [`InvalidInput`]: io::ErrorKind::InvalidInput\n    pub fn kill(&mut self) -> io::Result<()> {\n        let pid = Pid::from_raw(self.pid as i32).unwrap();\n        rustix::process::kill_process(pid, Signal::Kill)?;\n        Ok(())\n    }\n\n    /// Returns the OS-assigned process identifier associated with this child.\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::Command;\n    /// use birdcage::{Birdcage, Sandbox};\n    ///\n    /// let command = Command::new(\"ls\");\n    /// if let Ok(child) = Birdcage::new().spawn(command) {\n    ///     println!(\"Child's ID is {}\", child.id());\n    /// } else {\n    ///     println!(\"ls command didn't start\");\n    /// }\n    /// ```\n    pub fn id(&self) -> u32 {\n        self.pid\n    }\n\n    /// Waits for the child to exit completely, returning the status that it\n    /// exited with. This function will continue to have the same return value\n    /// after it has been called at least once.\n    ///\n    /// The stdin handle to the child process, if any, will be closed\n    /// before waiting. This helps avoid deadlock: it ensures that the\n    /// child does not block waiting for input from the parent, while\n    /// the parent waits for the child to exit.\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::Command;\n    /// use birdcage::{Birdcage, Sandbox};\n    ///\n    /// let mut command = Command::new(\"ls\");\n    /// if let Ok(mut child) = Birdcage::new().spawn(command) {\n    ///     child.wait().expect(\"command wasn't running\");\n    ///     println!(\"Child has finished its execution!\");\n    /// } else {\n    ///     println!(\"ls command didn't start\");\n    /// }\n    /// ```\n    pub fn wait(&mut self) -> io::Result<ExitStatus> {\n        // Wait for child process to exit.\n        unsafe {\n            let mut status: libc::c_int = 0;\n            if libc::waitpid(self.pid as i32, &mut status, 0) == -1 {\n                Err(io::Error::last_os_error())\n            } else {\n                match self.exit_signal()? {\n                    Some(exit_signal) => Ok(exit_signal),\n                    None => Ok(ExitStatus::from_raw(status)),\n                }\n            }\n        }\n    }\n\n    /// Attempts to collect the exit status of the child if it has already\n    /// exited.\n    ///\n    /// This function will not block the calling thread and will only\n    /// check to see if the child process has exited or not. If the child has\n    /// exited then on Unix the process ID is reaped. This function is\n    /// guaranteed to repeatedly return a successful exit status so long as the\n    /// child has already exited.\n    ///\n    /// If the child has exited, then `Ok(Some(status))` is returned. If the\n    /// exit status is not available at this time then `Ok(None)` is returned.\n    /// If an error occurs, then that error is returned.\n    ///\n    /// Note that unlike `wait`, this function will not attempt to drop stdin.\n    ///\n    /// # Examples\n    ///\n    /// Basic usage:\n    ///\n    /// ```no_run\n    /// use birdcage::process::Command;\n    /// use birdcage::{Birdcage, Sandbox};\n    ///\n    /// let cmd = Command::new(\"ls\");\n    /// let mut child = Birdcage::new().spawn(cmd).unwrap();\n    ///\n    /// match child.try_wait() {\n    ///     Ok(Some(status)) => println!(\"exited with: {status}\"),\n    ///     Ok(None) => {\n    ///         println!(\"status not ready yet, let's really wait\");\n    ///         let res = child.wait();\n    ///         println!(\"result: {res:?}\");\n    ///     },\n    ///     Err(e) => println!(\"error attempting to wait: {e}\"),\n    /// }\n    /// ```\n    pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {\n        // Wait for child process to exit.\n        unsafe {\n            let mut status: libc::c_int = 0;\n            let pid = libc::waitpid(self.pid as i32, &mut status, libc::WNOHANG);\n            if pid == -1 {\n                Err(io::Error::last_os_error())\n            } else if pid == 0 {\n                Ok(None)\n            } else {\n                match self.exit_signal()? {\n                    Some(exit_signal) => Ok(Some(exit_signal)),\n                    None => Ok(Some(ExitStatus::from_raw(status))),\n                }\n            }\n        }\n    }\n\n    /// Simultaneously waits for the child to exit and collect all remaining\n    /// output on the stdout/stderr handles, returning an `Output`\n    /// instance.\n    ///\n    /// The stdin handle to the child process, if any, will be closed\n    /// before waiting. This helps avoid deadlock: it ensures that the\n    /// child does not block waiting for input from the parent, while\n    /// the parent waits for the child to exit.\n    ///\n    /// By default, stdin, stdout and stderr are inherited from the parent.\n    /// In order to capture the output into this `Result<Output>` it is\n    /// necessary to create new pipes between parent and child. Use\n    /// `stdout(Stdio::piped())` or `stderr(Stdio::piped())`, respectively.\n    ///\n    /// # Examples\n    ///\n    /// ```should_panic\n    /// use birdcage::process::{Command, Stdio};\n    /// use birdcage::{Birdcage, Sandbox};\n    ///\n    /// let mut cmd = Command::new(\"/bin/cat\");\n    /// cmd.arg(\"file.txt\");\n    /// cmd.stdout(Stdio::piped());\n    /// let child = Birdcage::new().spawn(cmd).expect(\"failed to execute child\");\n    ///\n    /// let output = child.wait_with_output().expect(\"failed to wait on child\");\n    ///\n    /// assert!(output.status.success());\n    /// ```\n    pub fn wait_with_output(mut self) -> io::Result<Output> {\n        // Drop stdin, to avoid deadlocks.\n        let _ = self.stdin.take();\n\n        // Collect stdio buffers.\n        let reader = ChildReader::new(self.stdout.take(), self.stderr.take())?;\n        let (stdout, stderr) = reader.read()?;\n\n        // Wait for process termination.\n        let status = self.wait()?;\n\n        Ok(Output { status, stdout, stderr })\n    }\n\n    /// Get the child's exit signal.\n    fn exit_signal(&self) -> io::Result<Option<ExitStatus>> {\n        // Don't block when trying to read.\n        rustix::fs::fcntl_setfl(&self.exit_signal, OFlags::NONBLOCK)?;\n\n        // Read exit signal from pipe.\n        let mut bytes = [0; mem::size_of::<u32>()];\n        let read = match rustix::io::read(&self.exit_signal, &mut bytes) {\n            Ok(read) => read,\n            Err(err) if err.kind() == io::ErrorKind::WouldBlock => return Ok(None),\n            Err(err) => return Err(err.into()),\n        };\n\n        // Convert signal to exit status.\n        if read == mem::size_of::<u32>() {\n            let signal = u32::from_le_bytes(bytes);\n\n            // Exit signal are the lowest 7 bits of wstatus:\n            // https://github.com/torvalds/linux/blob/259f7d5e2baf87fcbb4fabc46526c9c47fed1914/tools/include/nolibc/types.h#L110\n            assert!(signal <= 0x7f);\n\n            Ok(Some(ExitStatus::from_raw(signal as i32)))\n        } else {\n            Ok(None)\n        }\n    }\n}\n\n/// Describes what to do with a standard I/O stream for a child process when\n/// passed to the [`stdin`], [`stdout`], and [`stderr`] methods of [`Command`].\n///\n/// [`stdin`]: Command::stdin\n/// [`stdout`]: Command::stdout\n/// [`stderr`]: Command::stderr\n#[derive(Default)]\npub struct Stdio {\n    pub(crate) ty: StdioType,\n}\n\nimpl Stdio {\n    /// A new pipe should be arranged to connect the parent and child processes.\n    ///\n    /// # Examples\n    ///\n    /// With stdout:\n    ///\n    /// ```no_run\n    /// use birdcage::process::{Command, Stdio};\n    ///\n    /// Command::new(\"echo\").arg(\"Hello, world!\").stdout(Stdio::piped());\n    /// ```\n    ///\n    /// With stdin:\n    ///\n    /// ```no_run\n    /// use std::io::Write;\n    ///\n    /// use birdcage::process::{Command, Stdio};\n    /// use birdcage::{Birdcage, Sandbox};\n    ///\n    /// let mut cmd = Command::new(\"rev\");\n    /// cmd.stdin(Stdio::piped());\n    /// cmd.stdout(Stdio::piped());\n    /// let mut child = Birdcage::new().spawn(cmd).expect(\"Failed to spawn child process\");\n    ///\n    /// let mut stdin = child.stdin.take().expect(\"Failed to open stdin\");\n    /// std::thread::spawn(move || {\n    ///     stdin.write_all(\"Hello, world!\".as_bytes()).expect(\"Failed to write to stdin\");\n    /// });\n    ///\n    /// let output = child.wait_with_output().expect(\"Failed to read stdout\");\n    /// assert_eq!(String::from_utf8_lossy(&output.stdout), \"!dlrow ,olleH\");\n    /// ```\n    ///\n    /// Writing more than a pipe buffer's worth of input to stdin without also\n    /// reading stdout and stderr at the same time may cause a deadlock.\n    /// This is an issue when running any program that doesn't guarantee that it\n    /// reads its entire stdin before writing more than a pipe buffer's\n    /// worth of output. The size of a pipe buffer varies on different\n    /// targets.\n    pub fn piped() -> Self {\n        Self { ty: StdioType::Piped }\n    }\n\n    /// The child inherits from the corresponding parent descriptor.\n    ///\n    /// # Examples\n    ///\n    /// ```no_run\n    /// use birdcage::process::{Command, Stdio};\n    ///\n    /// let output = Command::new(\"echo\").arg(\"Hello, world!\").stdout(Stdio::inherit());\n    /// ```\n    pub fn inherit() -> Self {\n        Self { ty: StdioType::Inherit }\n    }\n\n    /// This stream will be ignored. This is the equivalent of attaching the\n    /// stream to `/dev/null`.\n    ///\n    /// # Examples\n    ///\n    /// ```no_run\n    /// use birdcage::process::{Command, Stdio};\n    ///\n    /// let output = Command::new(\"echo\").arg(\"Hello, world!\").stdout(Stdio::null());\n    /// ```\n    pub fn null() -> Self {\n        Self { ty: StdioType::Null }\n    }\n\n    /// Create pipes necessary for the stdio type.\n    ///\n    /// This will return the corresponding read and write FDs.\n    pub(crate) fn make_pipe(&self, stdin: bool) -> io::Result<(Option<OwnedFd>, Option<OwnedFd>)> {\n        match self.ty {\n            StdioType::Inherit | StdioType::Default => Ok((None, None)),\n            StdioType::Piped => {\n                let (rx, tx) = pipe()?;\n                Ok((Some(rx), Some(tx)))\n            },\n            StdioType::Null => {\n                let null_fd = rustix::fs::open(\"/dev/null\", OFlags::RDWR, Mode::empty())?;\n                if stdin {\n                    Ok((Some(null_fd), None))\n                } else {\n                    Ok((None, Some(null_fd)))\n                }\n            },\n        }\n    }\n}\n\nimpl From<Stdio> for Option<std::process::Stdio> {\n    fn from(stdio: Stdio) -> Option<std::process::Stdio> {\n        match stdio.ty {\n            StdioType::Default => None,\n            StdioType::Inherit => Some(std::process::Stdio::inherit()),\n            StdioType::Piped => Some(std::process::Stdio::piped()),\n            StdioType::Null => Some(std::process::Stdio::null()),\n        }\n    }\n}\n\n/// Type of parent/child I/O coupling.\n#[derive(Default, Copy, Clone)]\npub(crate) enum StdioType {\n    #[default]\n    Default,\n    Piped,\n    Inherit,\n    Null,\n}\n\n/// A handle to a child process's standard input (stdin).\n///\n/// This struct is used in the [`stdin`] field on [`Child`].\n///\n/// When an instance of `ChildStdin` is [dropped], the `ChildStdin`'s underlying\n/// file handle will be closed. If the child process was blocked on input prior\n/// to being dropped, it will become unblocked after dropping.\n///\n/// [`stdin`]: Child::stdin\n/// [dropped]: Drop\npub struct ChildStdin {\n    fd: OwnedFd,\n}\n\nimpl ChildStdin {\n    fn new(fd: OwnedFd) -> io::Result<Self> {\n        Ok(Self { fd })\n    }\n}\n\nimpl Write for ChildStdin {\n    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {\n        rustix::io::write(&self.fd, buf).map_err(io::Error::from)\n    }\n\n    fn flush(&mut self) -> io::Result<()> {\n        Ok(())\n    }\n}\n\n/// A handle to a child process's standard output (stdout).\n///\n/// This struct is used in the [`stdout`] field on [`Child`].\n///\n/// When an instance of `ChildStdout` is [dropped], the `ChildStdout`'s\n/// underlying file handle will be closed.\n///\n/// [`stdout`]: Child::stdout\n/// [dropped]: Drop\npub struct ChildStdout {\n    fd: OwnedFd,\n}\n\nimpl ChildStdout {\n    fn new(fd: OwnedFd) -> io::Result<Self> {\n        Ok(Self { fd })\n    }\n}\n\nimpl Read for ChildStdout {\n    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {\n        rustix::io::read(&self.fd, buf).map_err(io::Error::from)\n    }\n}\n\n/// A handle to a child process's stderr.\n///\n/// This struct is used in the [`stderr`] field on [`Child`].\n///\n/// When an instance of `ChildStderr` is [dropped], the `ChildStderr`'s\n/// underlying file handle will be closed.\n///\n/// [`stderr`]: Child::stderr\n/// [dropped]: Drop\npub type ChildStderr = ChildStdout;\n\nstruct ChildReader {\n    poll_fds: Vec<libc::pollfd>,\n    stdout: Option<ChildStdout>,\n    stderr: Option<ChildStderr>,\n    stdout_buffer: Vec<u8>,\n    stderr_buffer: Vec<u8>,\n}\n\nimpl ChildReader {\n    fn new(stdout: Option<ChildStdout>, stderr: Option<ChildStderr>) -> io::Result<Self> {\n        let mut poll_fds = Vec::new();\n\n        if let Some(stdout) = &stdout {\n            rustix::fs::fcntl_setfl(&stdout.fd, OFlags::NONBLOCK)?;\n            let fd = stdout.fd.as_raw_fd();\n            poll_fds.push(libc::pollfd { fd, events: libc::POLLIN, revents: 0 });\n        }\n\n        if let Some(stderr) = &stderr {\n            rustix::fs::fcntl_setfl(&stderr.fd, OFlags::NONBLOCK)?;\n            let fd = stderr.fd.as_raw_fd();\n            poll_fds.push(libc::pollfd { fd, events: libc::POLLIN, revents: 0 });\n        }\n\n        Ok(Self {\n            poll_fds,\n            stdout,\n            stderr,\n            stdout_buffer: Default::default(),\n            stderr_buffer: Default::default(),\n        })\n    }\n\n    /// Read stdout and stderr into buffers.\n    fn read(mut self) -> io::Result<(Vec<u8>, Vec<u8>)> {\n        while !self.poll_fds.is_empty() {\n            // Block for next FD readiness.\n            let result = unsafe { libc::poll(self.poll_fds.as_mut_ptr(), 2, -1) };\n            if result == -1 {\n                return Err(io::Error::last_os_error());\n            }\n\n            // Read from all FDs.\n            for i in (0..self.poll_fds.len()).rev() {\n                // Ignore FDs that aren't ready.\n                let poll_fd = &self.poll_fds[i];\n                if poll_fd.revents == 0 {\n                    continue;\n                }\n\n                // Get stdio/buffer corresponding to the FD.\n                let (stdio, buffer) = self.stdio_from_fd(poll_fd.fd);\n\n                // Read all available data.\n                match stdio.read_to_end(buffer) {\n                    Ok(_) => {\n                        self.poll_fds.remove(i);\n                    },\n                    Err(err) if err.kind() == io::ErrorKind::WouldBlock => (),\n                    Err(err) => return Err(err),\n                }\n            }\n        }\n\n        Ok((self.stdout_buffer, self.stderr_buffer))\n    }\n\n    /// Get the stdio handles corresponding to a FD.\n    fn stdio_from_fd(&mut self, fd: RawFd) -> (&mut ChildStdout, &mut Vec<u8>) {\n        match (self.stdout.as_mut(), self.stderr.as_mut()) {\n            (Some(stdout), _) if stdout.fd.as_raw_fd() == fd => (stdout, &mut self.stdout_buffer),\n            (_, Some(stderr)) if stderr.fd.as_raw_fd() == fd => (stderr, &mut self.stderr_buffer),\n            _ => unreachable!(),\n        }\n    }\n}\n"
  },
  {
    "path": "src/process/macos.rs",
    "content": "//! macOS process implementation.\n\n// We just re-export STD, since we can spawn this command directly.\npub use std::process::{\n    Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus, Output, Stdio,\n};\n"
  },
  {
    "path": "src/process/mod.rs",
    "content": "#[cfg(target_os = \"linux\")]\nmod linux;\n#[cfg(target_os = \"macos\")]\nmod macos;\n\n#[cfg(target_os = \"linux\")]\npub use crate::process::linux::{\n    Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus, Output, Stdio,\n};\n#[cfg(target_os = \"macos\")]\npub use crate::process::macos::{\n    Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus, Output, Stdio,\n};\n"
  }
]