pax_global_header00006660000000000000000000000064144564205260014522gustar00rootroot0000000000000052 comment=86cdd4c02dc40b1cbff207e37d3a3076344c8e09 sshoot-1.6.0/000077500000000000000000000000001445642052600130455ustar00rootroot00000000000000sshoot-1.6.0/.github/000077500000000000000000000000001445642052600144055ustar00rootroot00000000000000sshoot-1.6.0/.github/workflows/000077500000000000000000000000001445642052600164425ustar00rootroot00000000000000sshoot-1.6.0/.github/workflows/ci.yml000066400000000000000000000030631445642052600175620ustar00rootroot00000000000000name: CI on: push: branches: - main pull_request: branches: - main jobs: lint: runs-on: ubuntu-latest steps: - name: Repository checkout uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: "3.10" - name: Install dependencies run: | pip install --upgrade pip tox - name: Lint run: | tox -e lint check: runs-on: ubuntu-latest steps: - name: Repository checkout uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: "3.10" - name: Install dependencies run: | pip install --upgrade pip tox - name: Check run: | tox -e check test: strategy: matrix: python: - "3.8" - "3.9" - "3.10" - "3.11" runs-on: ubuntu-latest steps: - name: Repository checkout uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: ${{ matrix.python }} - name: Install dependencies run: | pip install --upgrade pip tox - name: Test run: | tox -e coverage -- --cov-report xml:coverage.xml - name: Codecov uses: codecov/codecov-action@v3 with: token: ${{ secrets.CODECOV_TOKEN }} env_vars: PYTHON full_report: coverage.xml sshoot-1.6.0/.gitignore000066400000000000000000000001521445642052600150330ustar00rootroot00000000000000*.pyc *.pyo /build /html /*.egg-info /.coverage /.mypy_cache /.tox .eggs .pybuild .cache /snap/.snapcraft sshoot-1.6.0/CHANGES.rst000066400000000000000000000053421445642052600146530ustar00rootroot00000000000000v1.6.0 - 2022-07-21 =================== - Support defining global extra options to pass to ``sshuttle`` (#14). - Add hint to look at syslog log for ``sshuttle`` output (#13). - Require Python3.8+. - [snap] Rebase snap on core22. - Rework project setup. - Update i18n setup. v1.5.1 - 2020-12-18 =================== - [snap] Ship Python3.8 in the snap not to depend on version from OS. - Drop legacy config file path compatibility. - Drop Python3.6 support. - Add unittests for main script. - Only pass action parameters to Manager methods (Fixes: #10). v1.5.0 - 2020-11-20 =================== - Add ``restart`` option for a profile. - Use ``toolrack.script.Script`` as base for main script. - [snap] Move to ``core20``. - Add type hints. v1.4.2 - 2019-06-13 =================== - Rework tests and project setup. - Fix yaml warning (Fixes: #6). v1.4.1 - 2018-06-30 =================== - Use pathlib.Path instead of strings. - I8n-related cleanups. v1.4.0 - 2017-10-22 =================== - Add i18n support and it_IT translation. v1.3.2 - 2017-10-15 =================== - Use ``pyxdg`` instead of ``xdg``. v1.3.1 - 2017-10-10 =================== - Specify long description content-type. v1.3.0 - 2017-10-02 =================== - Support profiles listing in different formats (table, CSV, YAML, JSON) (Fixes: #3). - Move configuration path to XDG conventions (Fixes: #1). v1.2.6 - 2017-05-25 =================== - Move project to GitHub, small test cleanups. v1.2.5 - 2016-11-29 =================== - Filter running sessions for start/stop commands autocompletion. v1.2.4 - 2016-11-20 =================== - Fix autocompletion setup again. v1.2.3 - 2016-11-20 =================== - Fix autocompletion. v1.2.2 - 2016-11-20 =================== - Add support for bash-completion. v1.2.1 - 2015-11-04 =================== - Fix error message decoding when profile fails to start. v1.2.0 - 2015-09-04 =================== - Add is-running command to check whether a profile is running. v1.1.0 - 2015-05-27 =================== - Switch to Python3. v1.0.3 - 2015-04-15 =================== - Support passing extra options to sshuttle when starting a profile. v1.0.1 - 2014-11-23 =================== - Add get-command subcommand to return the sshuttle command line. v1.0.0 - 2014-10-08 =================== - Separate (optional) configuration and sessions files. - Directory for pidfiles is created in temporary directory, rather than home, to avoid issues if the home is shared. v0.0.3 - 2014-09-01 =================== - Fix dependencies. v0.0.2 - 2014-08-24 =================== - Support for managing sshuttle sessions (add, remove start, stop). v0.0.1 - 2014-08-05 =================== - Initial release. sshoot-1.6.0/LICENSE.txt000066400000000000000000001045131445642052600146740ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . sshoot-1.6.0/README.rst000066400000000000000000000042551445642052600145420ustar00rootroot00000000000000sshoot - Manage sshuttle VPN sessions ===================================== |Latest Version| |Build Status| |Coverage Status| |Snap Package| Command-line interface to manage multiple sshuttle_ VPN sessions. ``sshuttle`` creates a VPN connection from your machine to any remote server that you can connect to via ssh. ``sshoot`` allows to define multiple VPN sessions using ``sshuttle`` and start/stop them as needed. It supports configuration options for most of ``sshuttle``'s features, providing flexible configuration for profiles. Usage ----- Create a profile: .. code:: bash $ sshoot create -r host1.remote -HNd vpn1 10.0.0.0/24 Start it: .. code:: bash $ sshoot start vpn1 Profile started. List existing profiles (active ones are marked): .. code:: bash $ sshoot list Profile Remote host Subnets -------------------------------------------- * vpn1 host1.remote 10.0.0.0/24 vpn2 host2.remote 192.168.0.0/16 Stop the profile: .. code:: bash $ sshoot stop vpn1 Remove it: .. code:: bash $ sshoot delete vpn1 Install from Snap ----------------- |Get it from the Snap Store| ``sshoot`` can be installed from `Snap Store`_ on systems where classic Snaps are supported, via:: sudo snap install --classic sshoot .. _sshuttle: https://github.com/sshuttle/sshuttle .. _`Snap Store`: https://snapcraft.io .. |Latest Version| image:: https://img.shields.io/pypi/v/sshoot.svg :alt: Latest Version :target: https://pypi.python.org/pypi/sshoot .. |Build Status| image:: https://github.com/albertodonato/sshoot/workflows/CI/badge.svg :alt: Build Status :target: https://github.com/albertodonato/sshoot/actions?query=workflow%3ACI .. |Coverage Status| image:: https://img.shields.io/codecov/c/github/albertodonato/sshoot/main.svg :alt: Coverage Status :target: https://codecov.io/gh/albertodonato/sshoot .. |Snap Package| image:: https://snapcraft.io/sshoot/badge.svg :alt: Snap Package :target: https://snapcraft.io/sshoot .. |Get it from the Snap Store| image:: https://snapcraft.io/static/images/badges/en/snap-store-black.svg :alt: Get it from the Snap Store :target: https://snapcraft.io/sshoot sshoot-1.6.0/pyproject.toml000066400000000000000000000043111445642052600157600ustar00rootroot00000000000000[build-system] build-backend = "setuptools.build_meta" requires = [ "setuptools", ] [project] name = "sshoot" description = "Manage multiple sshuttle VPN sessions" readme = "README.rst" keywords = [ "ssh", "sshuttle", "vpn", ] license = {file = "LICENSE.txt"} maintainers = [ {name = "Alberto Donato", email = "alberto.donato@gmail.com"}, ] authors = [ {name = "Alberto Donato", email = "alberto.donato@gmail.com"}, ] requires-python = ">=3.8" classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Topic :: System :: Networking", "Topic :: Utilities", ] dynamic = [ "version", ] dependencies = [ "argcomplete", "prettytable", "pyxdg", "PyYAML", "toolrack>=3", ] [project.optional-dependencies] testing = [ "pytest", "pytest-mock", ] [project.urls] changelog = "https://github.com/albertodonato/sshoot/blob/main/CHANGES.rst" homepage = "https://github.com/albertodonato/sshoot" [project.scripts] sshoot = "sshoot.main:sshoot" [tool.setuptools.dynamic] version = {attr = "sshoot.__version__"} [tool.setuptools.packages.find] include = ["sshoot*"] [tool.black] line-length = 79 [tool.isort] combine_as_imports = true force_grid_wrap = 2 force_sort_within_sections = true from_first = false include_trailing_comma = true multi_line_output = 3 order_by_type = false profile = "black" use_parentheses = true [tool.flake8] ignore = ["E203", "E501", "W503"] max-line-length = 80 select = ["C", "E", "F", "W", "B", "B950"] [tool.coverage.report] fail_under = 100.0 show_missing = true skip_covered = true omit = [ "__main__.py" ] [tool.coverage.run] source = ["sshoot"] [tool.mypy] ignore_missing_imports = true install_types = true non_interactive = true warn_return_any = true warn_unused_configs = true sshoot-1.6.0/snap/000077500000000000000000000000001445642052600140065ustar00rootroot00000000000000sshoot-1.6.0/snap/local/000077500000000000000000000000001445642052600151005ustar00rootroot00000000000000sshoot-1.6.0/snap/local/sshoot-completion000066400000000000000000000014231445642052600205110ustar00rootroot00000000000000# -*- mode: sh -*- _sshoot_argcomplete() { local IFS=$'\013' local SUPPRESS_SPACE=0 if compopt +o nospace 2> /dev/null; then SUPPRESS_SPACE=1 fi COMPREPLY=( $(IFS="$IFS" \ COMP_LINE="$COMP_LINE" \ COMP_POINT="$COMP_POINT" \ COMP_TYPE="$COMP_TYPE" \ _ARGCOMPLETE_COMP_WORDBREAKS="$COMP_WORDBREAKS" \ _ARGCOMPLETE=1 \ _ARGCOMPLETE_SUPPRESS_SPACE=$SUPPRESS_SPACE \ "sshoot" 8>&1 9>&2 1>/dev/null 2>/dev/null) ) if [[ $? != 0 ]]; then unset COMPREPLY elif [[ $SUPPRESS_SPACE == 1 ]] && [[ "$COMPREPLY" =~ [=/:]$ ]]; then compopt -o nospace fi } complete -o nospace -o default -F _sshoot_argcomplete "sshoot" sshoot-1.6.0/snap/snapcraft.yaml000066400000000000000000000015331445642052600166550ustar00rootroot00000000000000name: sshoot version: git summary: Manage sshuttle VPN sessions description: | Command-line interface to manage multiple sshuttle VPN sessions. sshoot allows to define multiple VPN sessions using sshuttle and start/stop them as needed. license: GPL-3.0+ confinement: classic grade: stable base: core22 apps: sshoot: command: bin/sshoot completer: sshoot-completion parts: sshoot: plugin: python source: . source-type: git stage-packages: - libpython3.10-minimal - libpython3.10-stdlib - python3.10-minimal - python3.10-venv python-packages: - . - sshuttle prime: - bin/python* - bin/register-python-argcomplete - bin/sshoot - bin/sshuttle - etc/ - lib*/ - pyvenv.cfg - usr/ completion: plugin: dump source: snap/local sshoot-1.6.0/sshoot/000077500000000000000000000000001445642052600143645ustar00rootroot00000000000000sshoot-1.6.0/sshoot/__init__.py000066400000000000000000000001041445642052600164700ustar00rootroot00000000000000"""Manage multiple sshuttle VPN sessions.""" __version__ = "1.6.0" sshoot-1.6.0/sshoot/__main__.py000066400000000000000000000000431445642052600164530ustar00rootroot00000000000000from .main import sshoot sshoot() sshoot-1.6.0/sshoot/autocomplete.py000066400000000000000000000016251445642052600174430ustar00rootroot00000000000000"""Shell completion helpers.""" from argparse import Namespace from typing import Optional from .manager import Manager def complete_argument(argument, completer): """wrapper for setting up argument completer.""" argument.completer = completer return argument def profile_completer( prefix: str, parsed_args: Namespace, running: Optional[bool] = None, **kwargs, ): """Autocomplete helper for profile names. Parameters: - running: filter profiles that are running or not (by default no filter is applied). """ manager = Manager(config_path=parsed_args.config) manager.load_config() for name in manager.get_profiles(): if not name.startswith(prefix): continue if running is None or manager.is_running(name) == running: # Either no filter is set or it matches the profile status yield name sshoot-1.6.0/sshoot/config.py000066400000000000000000000044541445642052600162120ustar00rootroot00000000000000"""Handle configuration files.""" from pathlib import Path from typing import ( Any, Dict, IO, Optional, ) import yaml from .profile import Profile def yaml_dump(data: Dict, fh: Optional[IO] = None): """Dump data in YAML format with sane defaults for readability.""" return yaml.safe_dump( data, fh, default_flow_style=False, allow_unicode=True ) class Config: """Handle configuration file loading/saving.""" CONFIG_KEYS = frozenset(["executable", "extra-options"]) def __init__(self, path: Path): self._config_file = path / "config.yaml" self._profiles_file = path / "profiles.yaml" self._reset() def load(self): """Load configuration from file.""" self._reset() self._config = self._load_yaml_file(self._config_file) profiles = self._load_yaml_file(self._profiles_file) for name, conf in profiles.items(): self._profiles[name] = Profile.from_config(conf) def save(self): """Save profiles configuration to file.""" config = { name: profile.config() for name, profile in self._profiles.items() } self._profiles_file.write_text(yaml_dump(config)) def add_profile(self, name: str, profile: Profile): """Add a profile to the configuration.""" if name in self._profiles: raise KeyError(name) self._profiles[name] = profile def remove_profile(self, name: str): """Add the given profile to the configuration.""" del self._profiles[name] @property def profiles(self) -> Dict[str, Profile]: """Return a dict with profiles, using names as key.""" return self._profiles.copy() @property def config(self) -> Dict[str, Any]: """Return a dict with the configuration.""" return { key: value for key, value in self._config.items() if key in self.CONFIG_KEYS } def _reset(self) -> None: """Reset default empty config.""" self._profiles: Dict[str, Profile] = {} self._config = {} def _load_yaml_file(self, path: Path) -> Dict[str, Any]: """Load the specified YAML file.""" if not path.exists(): return {} return yaml.safe_load(path.read_text()) or {} sshoot-1.6.0/sshoot/i18n.py000066400000000000000000000010431445642052600155130ustar00rootroot00000000000000"""Internationalization setup.""" import argparse import gettext from pathlib import Path from typing import Callable def _setup_i18n(): """Setup internationalization.""" argparse._ = _get_i18n_func("argparse") return _get_i18n_func("sshoot") # default domain def _get_i18n_func(domain: str): """Return the internationalization function.""" localedir = Path(__file__).parent / "locale" g = gettext.translation(domain, localedir=localedir, fallback=True) return g.gettext _: Callable[[str], str] = _setup_i18n() sshoot-1.6.0/sshoot/listing.py000066400000000000000000000124021445642052600164060ustar00rootroot00000000000000"""Helpers for listing output.""" from collections import OrderedDict from csv import DictWriter from io import StringIO import json from typing import ( cast, Iterable, List, Optional, Protocol, Tuple, ) from prettytable import ( HEADER, PrettyTable, ) from .config import yaml_dump from .i18n import _ from .manager import Manager from .profile import Profile # Map names to profile fields _FIELDS_MAP = OrderedDict( [ (_("Remote host"), "remote"), (_("Subnets"), "subnets"), (_("Auto hosts"), "auto_hosts"), (_("Auto nets"), "auto_nets"), (_("DNS forward"), "dns"), (_("Exclude subnets"), "exclude_subnets"), (_("Seed hosts"), "seed_hosts"), (_("Extra options"), "extra_opts"), ] ) NAME_FIELD = _("Name") STATUS_FIELD = _("Status") class InvalidFormat(Exception): def __init__(self, name: str): super().__init__(_("Invalid output format: {name}").format(name=name)) ProfileIterator = Iterable[Tuple[str, Profile]] class Formatter(Protocol): def __call__( self, profile_iter: ProfileIterator, verbose: bool = False ) -> str: ... # pragma: nocoverage class ProfileListing: """List details for details in the specified format.""" def __init__(self, manager: Manager): self.manager = manager @classmethod def supported_formats(cls) -> List[str]: return sorted( attr[8:] for attr in dir(cls) if attr.startswith("_format_") ) def get_output(self, _format: str, verbose: bool = False) -> str: """Return a string with listing in the specified format.""" formatter: Optional[Formatter] = getattr( self, f"_format_{_format}", None ) if formatter is None: raise InvalidFormat(_format) profiles_iter = self.manager.get_profiles().items() return formatter(profiles_iter, verbose=verbose) def _format_table( self, profiles_iter: ProfileIterator, verbose: bool = False ) -> str: """Format profiles data as a table.""" titles = ["", NAME_FIELD] titles.extend(_FIELDS_MAP) columns = list(_FIELDS_MAP.values()) if not verbose: # Only basic info titles = titles[:4] columns = columns[:2] table = PrettyTable(titles) table.align = "l" table.vertical_char = " " table.junction_char = table.horizontal_char table.padding_width = 0 table.left_padding_width = 0 table.right_padding_width = 1 table.hrules = HEADER for name, profile in profiles_iter: row = ["*" if self.manager.is_running(name) else "", name] row.extend( _format_value(getattr(profile, column)) for column in columns ) table.add_row(row) return cast(str, table.get_string(sortby=NAME_FIELD)) + "\n" def _format_csv( self, profiles_iter: ProfileIterator, verbose: bool = False ) -> str: """Format profiles data as CSV.""" titles = [NAME_FIELD, STATUS_FIELD] titles.extend(_FIELDS_MAP) buf = StringIO() writer = DictWriter(buf, fieldnames=titles) writer.writeheader() for name, profile in profiles_iter: row = { NAME_FIELD: name, STATUS_FIELD: _profile_status(self.manager, name), } row.update( { title: getattr(profile, _FIELDS_MAP[title]) for title in titles[2:] } ) writer.writerow(row) return buf.getvalue() def _format_json( self, profiles_iter: ProfileIterator, verbose: bool = False ) -> str: """Format profiles data as JSON.""" data = {} for name, profile in profiles_iter: config = profile.config() # config['active'] = manager.is_running(name) data[name] = config return json.dumps(data) def _format_yaml( self, profiles_iter: ProfileIterator, verbose: bool = False ) -> str: """Format profiles data as YAML.""" data = {name: profile.config() for name, profile in profiles_iter} return cast(str, yaml_dump(data)) def profile_details(manager: Manager, name: str) -> str: """Return a string with details about a profile, formatted as a table.""" profile = manager.get_profile(name) table = PrettyTable( field_names=["key", "value"], header=False, border=False ) table.align["key"] = table.align["value"] = "l" table.add_row((f"{NAME_FIELD}:", name)) table.add_row((f"{STATUS_FIELD}:", _profile_status(manager, name))) for name, field in _FIELDS_MAP.items(): table.add_row((f"{name}:", _format_value(getattr(profile, field)))) return cast(str, table.get_string()) def _profile_status(manager: Manager, name: str) -> str: """Return a string with the status of a profile.""" return _("ACTIVE") if manager.is_running(name) else _("STOPPED") def _format_value(value) -> str: """Convert value to string, handling special cases.""" if isinstance(value, (list, tuple)): return " ".join(value) if value is None: return "" return str(value) sshoot-1.6.0/sshoot/locale/000077500000000000000000000000001445642052600156235ustar00rootroot00000000000000sshoot-1.6.0/sshoot/locale/it_IT/000077500000000000000000000000001445642052600166335ustar00rootroot00000000000000sshoot-1.6.0/sshoot/locale/it_IT/LC_MESSAGES/000077500000000000000000000000001445642052600204205ustar00rootroot00000000000000sshoot-1.6.0/sshoot/locale/it_IT/LC_MESSAGES/sshoot.mo000066400000000000000000000110541445642052600222750ustar00rootroot00000000000000Þ•9䬭 ´ ¿ ÉÕ åó0N%m“ ˜¹Ô ë# 0BR bn vˆ¨4º/ï33S.‡¶Ë/æ 07#hŒ$¢ÇÛø5R n{#•)¹#ã !" (D m ‹ ¢› > E V g v ˆ '› +à "ï : 'M u (z £ ½ ;Ö # 6 H X l x   –   ¼ ?Ñ (7:Cr6¶í5&(\?…(Åî(.@`~œ¹ Ùæ&*+V!v$˜0½ îACTIVEAuto hostsAuto netsDNS forwardExclude subnetsExtra optionsFailed to kill process {pid}Failed to stop profile: {error}Invalid output format: {name}Invalid profile config '{key}'Manage multiple sshuttle VPN sessionsNameProfile failed to start: {error}Profile is already runningProfile is not runningProfile missing 'subnets' configProfile name already in use: {name}Profile restartedProfile startedProfile stoppedRemote hostSTOPPEDSeed hostsStatusSubnetsUnknown profile: {name}action to performadditional arguments passed to sshuttle command lineautomatically route additional nets from serverautomatically update /etc/hosts with hosts from VPNcomma-separated list of hosts to seed to auto-hostsconfiguration directory (default: %(default)s)define a new profiledelete an existing profiledisable global extra-options set in config.yamlexclude subnets from VPN forwardextra arguments to pass to sshuttle command lineforward DNS queries through the VPNlist defined profileslisting format (default %(default)s)name of the profilename of the profile to queryname of the profile to removename of the profile to restartname of the profile to startname of the profile to stopprofile nameremote host to connect torestart a VPN session for a profilereturn the sshuttle command for a profilereturn whether a profile is runningshow profile configurationstart a VPN session for a profilestop a running VPN session for a profilesubnets to route over the VPNverbose listingProject-Id-Version: sshoot 1.3.2 Report-Msgid-Bugs-To: EMAIL@ADDRESS POT-Creation-Date: 2023-05-10 08:19+0200 PO-Revision-Date: 2020-11-15 11:02+0100 Last-Translator: Alberto Donato Language: it_IT Language-Team: it_IT Plural-Forms: nplurals=2; plural=(n != 1); MIME-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Generated-By: Babel 2.12.1 ATTIVOHosts automaticiReti automaticheInvia req. DNSSottoreti escluseOpzioni aggiuntiveTerminazione del processo {pid} fallitaDisattivazione del profilo fallita: {error}Formato di output invalido: {name}Chiave '{key}' non valida nella configurazione del profiloGestisci sessioni VPN sshuttle multipleNomeAttivazione del profilo fallita: {error}Il profilo è già attivoIl profilo non è attivoOpzione 'subnets' mancante nella configurazione del profiloNome di profilo già in uso: {name}Profilo riavviatoProfilo avviatoProfilo disattivatoHost remotoINATTIVOSpecifica hostStatoSottoretiProfilo sconosciuto: {name}azione da effettuareopzioni aggiuntive da passare alla linea di comando di sshuttleruota automaticamente le reti dal serveraggiorna automaticamente /etc/hosts con hosts dalla VPNlista (separata da virgole) degli host da specificare ad auto-hostsdirectory di configurazione (predefinita: %(default)s)definisci un nuovo profilocancella un profilo esistentedisabilita le opzioni globali presenti in config.yamlescludi sottoreti dall'invio tramite VPNopzioni aggiuntive da passare alla linea di comando di sshuttleinvia le richieste DNS attraverso la VPNlista profili definitiformato lista (predefinito: %(default)s)nomde del profilonome del profilo da interrogarenome del profilo da rimuoverenome del profilo da riavviarenome del profilo da attivarenome del profilo da disattivarenome profilohost remoto a cui connettersiriavvia la sessione VPN per un profiloritorna il comando sshuttle per un profiloritorna se un profilo è attivovisualizza configurazione profiloavvia la sessione VPN per un profilodisattiva una sessione VPN attiva per un profilosottoreti da ruotare tramite VPNvisualizza maggiori dettaglisshoot-1.6.0/sshoot/locale/it_IT/LC_MESSAGES/sshoot.po000066400000000000000000000146241445642052600223060ustar00rootroot00000000000000# Italian (Italy) translations for sshoot. # Copyright (C) 2017 # This file is distributed under the same license as the sshoot project. # Alberto Donato , 2017. # msgid "" msgstr "" "Project-Id-Version: sshoot 1.3.2\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" "POT-Creation-Date: 2023-05-10 08:19+0200\n" "PO-Revision-Date: 2020-11-15 11:02+0100\n" "Last-Translator: Alberto Donato \n" "Language: it_IT\n" "Language-Team: it_IT \n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.12.1\n" #: sshoot/listing.py:29 msgid "Remote host" msgstr "Host remoto" #: sshoot/listing.py:30 msgid "Subnets" msgstr "Sottoreti" #: sshoot/listing.py:31 msgid "Auto hosts" msgstr "Hosts automatici" #: sshoot/listing.py:32 msgid "Auto nets" msgstr "Reti automatiche" #: sshoot/listing.py:33 msgid "DNS forward" msgstr "Invia req. DNS" #: sshoot/listing.py:34 msgid "Exclude subnets" msgstr "Sottoreti escluse" #: sshoot/listing.py:35 msgid "Seed hosts" msgstr "Specifica host" #: sshoot/listing.py:36 msgid "Extra options" msgstr "Opzioni aggiuntive" #: sshoot/listing.py:40 msgid "Name" msgstr "Nome" #: sshoot/listing.py:41 msgid "Status" msgstr "Stato" #: sshoot/listing.py:46 msgid "Invalid output format: {name}" msgstr "Formato di output invalido: {name}" #: sshoot/listing.py:171 msgid "ACTIVE" msgstr "ATTIVO" #: sshoot/listing.py:171 msgid "STOPPED" msgstr "INATTIVO" #: sshoot/main.py:88 msgid "Profile started" msgstr "Profilo avviato" #: sshoot/main.py:93 msgid "Profile stopped" msgstr "Profilo disattivato" #: sshoot/main.py:102 msgid "Profile restarted" msgstr "Profilo riavviato" #: sshoot/main.py:123 msgid "Manage multiple sshuttle VPN sessions" msgstr "Gestisci sessioni VPN sshuttle multiple" #: sshoot/main.py:135 #, python-format msgid "configuration directory (default: %(default)s)" msgstr "directory di configurazione (predefinita: %(default)s)" #: sshoot/main.py:138 msgid "action to perform" msgstr "azione da effettuare" #: sshoot/main.py:144 msgid "list defined profiles" msgstr "lista profili definiti" #: sshoot/main.py:147 msgid "verbose listing" msgstr "visualizza maggiori dettagli" #: sshoot/main.py:154 #, python-format msgid "listing format (default %(default)s)" msgstr "formato lista (predefinito: %(default)s)" #: sshoot/main.py:159 msgid "show profile configuration" msgstr "visualizza configurazione profilo" #: sshoot/main.py:162 sshoot/main.py:170 msgid "profile name" msgstr "nome profilo" #: sshoot/main.py:168 msgid "define a new profile" msgstr "definisci un nuovo profilo" #: sshoot/main.py:172 msgid "subnets to route over the VPN" msgstr "sottoreti da ruotare tramite VPN" #: sshoot/main.py:175 msgid "remote host to connect to" msgstr "host remoto a cui connettersi" #: sshoot/main.py:181 msgid "automatically update /etc/hosts with hosts from VPN" msgstr "aggiorna automaticamente /etc/hosts con hosts dalla VPN" #: sshoot/main.py:187 msgid "automatically route additional nets from server" msgstr "ruota automaticamente le reti dal server" #: sshoot/main.py:193 msgid "forward DNS queries through the VPN" msgstr "invia le richieste DNS attraverso la VPN" #: sshoot/main.py:199 msgid "exclude subnets from VPN forward" msgstr "escludi sottoreti dall'invio tramite VPN" #: sshoot/main.py:205 msgid "comma-separated list of hosts to seed to auto-hosts" msgstr "lista (separata da virgole) degli host da specificare ad auto-hosts" #: sshoot/main.py:210 msgid "extra arguments to pass to sshuttle command line" msgstr "opzioni aggiuntive da passare alla linea di comando di sshuttle" #: sshoot/main.py:215 msgid "delete an existing profile" msgstr "cancella un profilo esistente" #: sshoot/main.py:219 msgid "name of the profile to remove" msgstr "nome del profilo da rimuovere" #: sshoot/main.py:226 msgid "start a VPN session for a profile" msgstr "avvia la sessione VPN per un profilo" #: sshoot/main.py:230 msgid "name of the profile to start" msgstr "nome del profilo da attivare" #: sshoot/main.py:238 sshoot/main.py:271 sshoot/main.py:304 msgid "disable global extra-options set in config.yaml" msgstr "disabilita le opzioni globali presenti in config.yaml" #: sshoot/main.py:243 sshoot/main.py:276 msgid "additional arguments passed to sshuttle command line" msgstr "opzioni aggiuntive da passare alla linea di comando di sshuttle" #: sshoot/main.py:248 msgid "stop a running VPN session for a profile" msgstr "disattiva una sessione VPN attiva per un profilo" #: sshoot/main.py:252 msgid "name of the profile to stop" msgstr "nome del profilo da disattivare" #: sshoot/main.py:259 msgid "restart a VPN session for a profile" msgstr "riavvia la sessione VPN per un profilo" #: sshoot/main.py:263 msgid "name of the profile to restart" msgstr "nome del profilo da riavviare" #: sshoot/main.py:281 msgid "return whether a profile is running" msgstr "ritorna se un profilo è attivo" #: sshoot/main.py:285 msgid "name of the profile to query" msgstr "nome del profilo da interrogare" #: sshoot/main.py:292 msgid "return the sshuttle command for a profile" msgstr "ritorna il comando sshuttle per un profilo" #: sshoot/main.py:296 msgid "name of the profile" msgstr "nomde del profilo" #: sshoot/manager.py:66 msgid "Profile name already in use: {name}" msgstr "Nome di profilo già in uso: {name}" #: sshoot/manager.py:78 sshoot/manager.py:93 msgid "Unknown profile: {name}" msgstr "Profilo sconosciuto: {name}" #: sshoot/manager.py:104 msgid "Profile is already running" msgstr "Il profilo è già attivo" #: sshoot/manager.py:111 msgid "Profile failed to start: {error}" msgstr "Attivazione del profilo fallita: {error}" #: sshoot/manager.py:134 msgid "Profile is not running" msgstr "Il profilo non è attivo" #: sshoot/manager.py:141 msgid "Failed to stop profile: {error}" msgstr "Disattivazione del profilo fallita: {error}" #: sshoot/manager.py:215 msgid "Failed to kill process {pid}" msgstr "Terminazione del processo {pid} fallita" #: sshoot/profile.py:38 msgid "Profile missing 'subnets' config" msgstr "Opzione 'subnets' mancante nella configurazione del profilo" #: sshoot/profile.py:49 msgid "Invalid profile config '{key}'" msgstr "Chiave '{key}' non valida nella configurazione del profilo" #~ msgid "NOTICE: configuration tree moved from {old_path} to {new_path}\n" #~ msgstr "NOTA: la configurazione è stata spostata da {old_path} a {new_path}\n" sshoot-1.6.0/sshoot/locale/sshoot.pot000066400000000000000000000107621445642052600176740ustar00rootroot00000000000000# Translations template for sshoot. # Copyright (C) 2023 ORGANIZATION # This file is distributed under the same license as the sshoot project. # FIRST AUTHOR , 2023. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: sshoot VERSION\n" "Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" "POT-Creation-Date: 2023-05-10 08:19+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Generated-By: Babel 2.12.1\n" #: sshoot/listing.py:29 msgid "Remote host" msgstr "" #: sshoot/listing.py:30 msgid "Subnets" msgstr "" #: sshoot/listing.py:31 msgid "Auto hosts" msgstr "" #: sshoot/listing.py:32 msgid "Auto nets" msgstr "" #: sshoot/listing.py:33 msgid "DNS forward" msgstr "" #: sshoot/listing.py:34 msgid "Exclude subnets" msgstr "" #: sshoot/listing.py:35 msgid "Seed hosts" msgstr "" #: sshoot/listing.py:36 msgid "Extra options" msgstr "" #: sshoot/listing.py:40 msgid "Name" msgstr "" #: sshoot/listing.py:41 msgid "Status" msgstr "" #: sshoot/listing.py:46 msgid "Invalid output format: {name}" msgstr "" #: sshoot/listing.py:171 msgid "ACTIVE" msgstr "" #: sshoot/listing.py:171 msgid "STOPPED" msgstr "" #: sshoot/main.py:88 msgid "Profile started" msgstr "" #: sshoot/main.py:93 msgid "Profile stopped" msgstr "" #: sshoot/main.py:102 msgid "Profile restarted" msgstr "" #: sshoot/main.py:123 msgid "Manage multiple sshuttle VPN sessions" msgstr "" #: sshoot/main.py:135 #, python-format msgid "configuration directory (default: %(default)s)" msgstr "" #: sshoot/main.py:138 msgid "action to perform" msgstr "" #: sshoot/main.py:144 msgid "list defined profiles" msgstr "" #: sshoot/main.py:147 msgid "verbose listing" msgstr "" #: sshoot/main.py:154 #, python-format msgid "listing format (default %(default)s)" msgstr "" #: sshoot/main.py:159 msgid "show profile configuration" msgstr "" #: sshoot/main.py:162 sshoot/main.py:170 msgid "profile name" msgstr "" #: sshoot/main.py:168 msgid "define a new profile" msgstr "" #: sshoot/main.py:172 msgid "subnets to route over the VPN" msgstr "" #: sshoot/main.py:175 msgid "remote host to connect to" msgstr "" #: sshoot/main.py:181 msgid "automatically update /etc/hosts with hosts from VPN" msgstr "" #: sshoot/main.py:187 msgid "automatically route additional nets from server" msgstr "" #: sshoot/main.py:193 msgid "forward DNS queries through the VPN" msgstr "" #: sshoot/main.py:199 msgid "exclude subnets from VPN forward" msgstr "" #: sshoot/main.py:205 msgid "comma-separated list of hosts to seed to auto-hosts" msgstr "" #: sshoot/main.py:210 msgid "extra arguments to pass to sshuttle command line" msgstr "" #: sshoot/main.py:215 msgid "delete an existing profile" msgstr "" #: sshoot/main.py:219 msgid "name of the profile to remove" msgstr "" #: sshoot/main.py:226 msgid "start a VPN session for a profile" msgstr "" #: sshoot/main.py:230 msgid "name of the profile to start" msgstr "" #: sshoot/main.py:238 sshoot/main.py:271 sshoot/main.py:304 msgid "disable global extra-options set in config.yaml" msgstr "" #: sshoot/main.py:243 sshoot/main.py:276 msgid "additional arguments passed to sshuttle command line" msgstr "" #: sshoot/main.py:248 msgid "stop a running VPN session for a profile" msgstr "" #: sshoot/main.py:252 msgid "name of the profile to stop" msgstr "" #: sshoot/main.py:259 msgid "restart a VPN session for a profile" msgstr "" #: sshoot/main.py:263 msgid "name of the profile to restart" msgstr "" #: sshoot/main.py:281 msgid "return whether a profile is running" msgstr "" #: sshoot/main.py:285 msgid "name of the profile to query" msgstr "" #: sshoot/main.py:292 msgid "return the sshuttle command for a profile" msgstr "" #: sshoot/main.py:296 msgid "name of the profile" msgstr "" #: sshoot/manager.py:66 msgid "Profile name already in use: {name}" msgstr "" #: sshoot/manager.py:78 sshoot/manager.py:93 msgid "Unknown profile: {name}" msgstr "" #: sshoot/manager.py:104 msgid "Profile is already running" msgstr "" #: sshoot/manager.py:111 msgid "Profile failed to start: {error}" msgstr "" #: sshoot/manager.py:134 msgid "Profile is not running" msgstr "" #: sshoot/manager.py:141 msgid "Failed to stop profile: {error}" msgstr "" #: sshoot/manager.py:215 msgid "Failed to kill process {pid}" msgstr "" #: sshoot/profile.py:38 msgid "Profile missing 'subnets' config" msgstr "" #: sshoot/profile.py:49 msgid "Invalid profile config '{key}'" msgstr "" sshoot-1.6.0/sshoot/main.py000066400000000000000000000242131445642052600156640ustar00rootroot00000000000000"""Command-line interface to handle sshuttle VPN sessions.""" from argparse import ( ArgumentParser, Namespace, ) from functools import partial from typing import Set from argcomplete import autocomplete from toolrack.script import ( ErrorExitMessage, Script, ) from . import __version__ from .autocomplete import ( complete_argument, profile_completer, ) from .i18n import _ from .listing import ( profile_details, ProfileListing, ) from .manager import ( DEFAULT_CONFIG_PATH, Manager, ManagerProfileError, ) class Sshoot(Script): """Manage multiple sshuttle VPN sessions.""" def main(self, args: Namespace): try: manager = Manager(config_path=args.config) manager.load_config() except OSError as error: raise ErrorExitMessage(error, code=3) action = args.action.replace("-", "_") method = getattr(self, "action_" + action) action_args = Namespace( **{ key: value for key, value in args.__dict__.items() if key not in self.global_args } ) try: return method(manager, action_args) except ManagerProfileError as error: raise ErrorExitMessage(error, code=2) def print(self, *args, **kwargs): """Print out message.""" print(*args, **kwargs, file=self._stdout) def action_list(self, manager: Manager, args: Namespace): """Print out the list of profiles as a table.""" listing = ProfileListing(manager) self.print( listing.get_output(args.format, verbose=args.verbose), end="" ) def action_show(self, manager: Manager, args: Namespace): """Show details on a profile.""" self.print(profile_details(manager, args.name)) def action_create(self, manager: Manager, args: Namespace): """Create a new profile.""" details = args.__dict__.copy() details.pop("name") manager.create_profile(args.name, details) def action_delete(self, manager: Manager, args: Namespace): """Delete profile with the given name.""" manager.remove_profile(args.name) def action_start(self, manager: Manager, args: Namespace): """Start sshuttle for the specified profile.""" manager.start_profile( args.name, extra_args=args.args, disable_global_extra_options=args.disable_global_extra_options, ) self.print(_("Profile started")) def action_stop(self, manager: Manager, args: Namespace): """Stop sshuttle for the specified profile.""" manager.stop_profile(args.name) self.print(_("Profile stopped")) def action_restart(self, manager: Manager, args: Namespace): """Restart sshuttle for the specified profile.""" manager.restart_profile( args.name, extra_args=args.args, disable_global_extra_options=args.disable_global_extra_options, ) self.print(_("Profile restarted")) def action_is_running(self, manager: Manager, args: Namespace): """Return whether the specified profile is running.""" # raise an error if profile is unknown manager.get_profile(args.name) retval = 0 if manager.is_running(args.name) else 1 self.exit(retval) def action_get_command(self, manager: Manager, args: Namespace): """Print the sshuttle command for the specified profile.""" cmdline = manager.get_cmdline( args.name, disable_global_extra_options=args.disable_global_extra_options, ) self.print(" ".join(cmdline)) def get_parser(self) -> ArgumentParser: """Return a configured argparse.ArgumentParse instance.""" parser = ArgumentParser( prog="sshoot", description=_("Manage multiple sshuttle VPN sessions"), ) parser.add_argument( "-V", "--version", action="version", version=f"%(prog)s {__version__}", ) parser.add_argument( "-C", "--config", default=DEFAULT_CONFIG_PATH, help=_("configuration directory (default: %(default)s)"), ) subparsers = parser.add_subparsers( metavar="ACTION", dest="action", help=_("action to perform") ) subparsers.required = True # List profiles list_parser = subparsers.add_parser( "list", help=_("list defined profiles") ) list_parser.add_argument( "-v", "--verbose", action="store_true", help=_("verbose listing") ) list_parser.add_argument( "-f", "--format", choices=ProfileListing.supported_formats(), default="table", help=_("listing format (default %(default)s)"), ) # Show profile show_parser = subparsers.add_parser( "show", help=_("show profile configuration") ) complete_argument( show_parser.add_argument("name", help=_("profile name")), profile_completer, ) # Add profile create_parser = subparsers.add_parser( "create", help=_("define a new profile") ) create_parser.add_argument("name", help=_("profile name")) create_parser.add_argument( "subnets", nargs="+", help=_("subnets to route over the VPN") ) create_parser.add_argument( "-r", "--remote", help=_("remote host to connect to") ) create_parser.add_argument( "-H", "--auto-hosts", action="store_true", help=_("automatically update /etc/hosts with hosts from VPN"), ) create_parser.add_argument( "-N", "--auto-nets", action="store_true", help=_("automatically route additional nets from server"), ) create_parser.add_argument( "-d", "--dns", action="store_true", help=_("forward DNS queries through the VPN"), ) create_parser.add_argument( "-x", "--exclude-subnets", nargs="+", help=_("exclude subnets from VPN forward"), ) create_parser.add_argument( "-S", "--seed-hosts", nargs="+", help=_("comma-separated list of hosts to seed to auto-hosts"), ) create_parser.add_argument( "--extra-opts", type=str.split, help=_("extra arguments to pass to sshuttle command line"), ) # Remove profile delete_parser = subparsers.add_parser( "delete", help=_("delete an existing profile") ) complete_argument( delete_parser.add_argument( "name", help=_("name of the profile to remove") ), profile_completer, ) # Start profile start_parser = subparsers.add_parser( "start", help=_("start a VPN session for a profile") ) complete_argument( start_parser.add_argument( "name", help=_("name of the profile to start") ), partial(profile_completer, running=False), ) start_parser.add_argument( "--no-global-extra-options", dest="disable_global_extra_options", action="store_true", help=_("disable global extra-options set in config.yaml"), ) start_parser.add_argument( "args", nargs="*", help=_("additional arguments passed to sshuttle command line"), ) # Stop profile stop_parser = subparsers.add_parser( "stop", help=_("stop a running VPN session for a profile") ) complete_argument( stop_parser.add_argument( "name", help=_("name of the profile to stop") ), partial(profile_completer, running=True), ) # Restart profile restart_parser = subparsers.add_parser( "restart", help=_("restart a VPN session for a profile") ) complete_argument( restart_parser.add_argument( "name", help=_("name of the profile to restart") ), partial(profile_completer, running=True), ) restart_parser.add_argument( "--no-global-extra-options", dest="disable_global_extra_options", action="store_true", help=_("disable global extra-options set in config.yaml"), ) restart_parser.add_argument( "args", nargs="*", help=_("additional arguments passed to sshuttle command line"), ) # Return whether profile is running is_running_parser = subparsers.add_parser( "is-running", help=_("return whether a profile is running") ) complete_argument( is_running_parser.add_argument( "name", help=_("name of the profile to query") ), profile_completer, ) # Get profile command get_command_parser = subparsers.add_parser( "get-command", help=_("return the sshuttle command for a profile") ) complete_argument( get_command_parser.add_argument( "name", help=_("name of the profile") ), profile_completer, ) get_command_parser.add_argument( "--no-global-extra-options", dest="disable_global_extra_options", action="store_true", help=_("disable global extra-options set in config.yaml"), ) # track global arguments/options so they can be stripped from action namespace self.global_args: Set[str] = set() for group in parser._action_groups: self.global_args.update( action.dest for action in group._group_actions ) # Setup autocompletion autocomplete(parser) return parser sshoot = Sshoot() sshoot-1.6.0/sshoot/manager.py000066400000000000000000000156031445642052600163550ustar00rootroot00000000000000"""Handle sshuttle sessions.""" from getpass import getuser import os from pathlib import Path from signal import ( SIGKILL, SIGTERM, ) from subprocess import ( PIPE, Popen, ) from tempfile import gettempdir import time from typing import ( Any, cast, Dict, IO, List, Optional, ) from xdg.BaseDirectory import xdg_config_home from .config import Config from .i18n import _ from .profile import ( Profile, ProfileError, ) DEFAULT_CONFIG_PATH = Path(xdg_config_home) / "sshoot" class ManagerProfileError(Exception): """Profile operation failed.""" class Manager: """Profile manager.""" def __init__( self, config_path: Optional[str] = None, rundir: Optional[str] = None ): self.config_path = ( Path(config_path) if config_path else DEFAULT_CONFIG_PATH ) self.rundir = Path(rundir) if rundir else get_rundir("sshoot") self.sessions_path = self.rundir / "sessions" self._config = Config(self.config_path) def load_config(self): """Load configuration from file.""" self.config_path.mkdir(parents=True, exist_ok=True) self.sessions_path.mkdir(parents=True, exist_ok=True) self._config.load() def create_profile(self, name: str, details: Dict[str, Any]): """Create a profile with provided details.""" try: self._config.add_profile(name, Profile.from_config(details)) except KeyError: raise ManagerProfileError( _("Profile name already in use: {name}").format(name=name) ) except ProfileError as error: raise ManagerProfileError(str(error)) self._config.save() def remove_profile(self, name: str): """Remove profile with given name.""" try: self._config.remove_profile(name) except KeyError: raise ManagerProfileError( _("Unknown profile: {name}").format(name=name) ) self._config.save() def get_profiles(self) -> Dict[str, Profile]: """Return profiles defined in config.""" return self._config.profiles def get_profile(self, name: str) -> Profile: """Return profile with given name.""" try: return self._config.profiles[name] except KeyError: raise ManagerProfileError( _("Unknown profile: {name}").format(name=name) ) def start_profile( self, name: str, extra_args: Optional[List[str]] = None, disable_global_extra_options: bool = False, ): """Start profile with given name.""" if self.is_running(name): raise ManagerProfileError(_("Profile is already running")) cmdline = self.get_cmdline( name, extra_args=extra_args, disable_global_extra_options=disable_global_extra_options, ) message = _("Profile failed to start: {error}") try: process = Popen(cmdline, stderr=PIPE) # Wait until process is started (it daemonizes) process.wait() except OSError as err: # To catch file not found errors raise ManagerProfileError(message.format(error=str(err))) stderr = cast(IO[bytes], process.stderr) if process.returncode != 0: error = stderr.read().decode() stderr.close() if not error: error = "Please see the log for more details: 'grep sshuttle /var/log/syslog'" raise ManagerProfileError(message.format(error=error)) stderr.close() def stop_profile(self, name: str): """Stop profile with given name.""" self.get_profile(name) if not self.is_running(name): raise ManagerProfileError(_("Profile is not running")) try: pid = int(self._get_pidfile(name).read_text()) kill_and_wait(pid) except (OSError, PermissionError) as error: raise ManagerProfileError( _("Failed to stop profile: {error}").format(error=error) ) def restart_profile( self, name: str, extra_args: Optional[List[str]] = None, disable_global_extra_options: bool = False, ): """Restart profile with given name.""" if self.is_running(name): self.stop_profile(name) self.start_profile( name, extra_args=extra_args, disable_global_extra_options=disable_global_extra_options, ) def is_running(self, name: str) -> bool: """Return whether the specified profile is running.""" pidfile = self._get_pidfile(name) try: pid = int(pidfile.read_text()) except Exception: # If anything fails, a valid PID can't be found, so the profile is # not running return False try: os.kill(pid, 0) except ProcessLookupError: # Delete stale pidfile pidfile.unlink() return False return True def get_cmdline( self, name: str, extra_args: Optional[List[str]] = None, disable_global_extra_options: bool = False, ) -> List[str]: """Return the command line for the specified profile.""" profile = self.get_profile(name) executable = self._get_executable() extra_opts = ["--daemon", "--pidfile", str(self._get_pidfile(name))] global_extra_options = ( self._config.config.get("extra-options", []) if not disable_global_extra_options else [] ) if extra_args: extra_opts.extend(extra_args) return profile.cmdline( executable=executable, extra_opts=extra_opts, global_extra_options=global_extra_options, ) def _get_pidfile(self, name: str) -> Path: """Return the path of the pidfile for the specified profile.""" return self.sessions_path / f"{name}.pid" def _get_executable(self) -> str: """Return the shuttle executable from the config.""" return self._config.config.get("executable", "sshuttle") class ProcessKillFail(Exception): """Failed to kill a process.""" def __init__(self, pid: int): self.pid = pid super().__init__(_("Failed to kill process {pid}").format(pid=pid)) def kill_and_wait(pid: int): """Kill a process and wait for it to terminate.""" for wait, signal in ((2.0, SIGTERM), (1.0, SIGKILL)): while wait > 0: try: os.kill(pid, signal) except ProcessLookupError: return wait -= 0.2 time.sleep(0.2) raise ProcessKillFail(pid) def get_rundir(prefix: str) -> Path: """Return the directory holding runtime data.""" return Path(gettempdir()) / f"{prefix}-{getuser()}" sshoot-1.6.0/sshoot/profile.py000066400000000000000000000054431445642052600164040ustar00rootroot00000000000000"""A sshuttle VPN profile.""" import dataclasses from typing import ( Any, Dict, List, Optional, ) from .i18n import _ class ProfileError(Exception): """Invalid profile configuration.""" @dataclasses.dataclass class Profile: """Hold information about a sshuttle profile.""" subnets: List[str] remote: str = "" auto_hosts: bool = False auto_nets: bool = False dns: bool = False exclude_subnets: Optional[List[str]] = None seed_hosts: Optional[List[str]] = None extra_opts: Optional[List[str]] = None @classmethod def from_config(cls, config: Dict[str, Any]): """Create a profile from a config dict.""" config = config.copy() try: profile = cls(config.pop("subnets")) except KeyError: raise ProfileError(_("Profile missing 'subnets' config")) profile.update(config) return profile def update(self, config: Dict[str, Any]): """Update the profile from the specified config.""" field_names = list(self._fields()) for key, value in config.items(): attr = key.replace("-", "_") if attr not in field_names: raise ProfileError( _("Invalid profile config '{key}'").format(key=key) ) setattr(self, attr, value) def config(self) -> Dict[str, Any]: """Return profile configuration as a dict.""" conf = {} for attr, default_value in self._fields().items(): value = getattr(self, attr) if value != default_value: conf[attr.replace("_", "-")] = value return dict(conf) def cmdline( self, executable: str = "sshuttle", extra_opts: Optional[List[str]] = None, global_extra_options: Optional[List[str]] = None, ) -> List[str]: """Return a sshuttle cmdline based on the profile.""" cmd = [executable] + self.subnets if self.remote: cmd.append(f"--remote={self.remote}") if self.auto_hosts: cmd.append("--auto-hosts") if self.auto_nets: cmd.append("--auto-nets") if self.dns: cmd.append("--dns") if self.exclude_subnets: cmd.extend(f"--exclude={net}" for net in self.exclude_subnets) if self.seed_hosts: seed_hosts = ",".join(self.seed_hosts) cmd.append(f"--seed-hosts={seed_hosts}") if self.extra_opts: cmd.extend(self.extra_opts) if extra_opts: cmd.extend(extra_opts) if global_extra_options: cmd.extend(global_extra_options) return cmd @classmethod def _fields(cls) -> Dict[str, Any]: return {field.name: field.default for field in dataclasses.fields(cls)} sshoot-1.6.0/tests/000077500000000000000000000000001445642052600142075ustar00rootroot00000000000000sshoot-1.6.0/tests/__init__.py000066400000000000000000000000001445642052600163060ustar00rootroot00000000000000sshoot-1.6.0/tests/autocomplete_test.py000066400000000000000000000033531445642052600203250ustar00rootroot00000000000000from argparse import Namespace import pytest from sshoot.autocomplete import ( complete_argument, profile_completer, ) class TestCompleteArgument: def test_complete(self): """complete_arguments attaches a completer to the argument.""" class FakeArgument: completer = None fake_argument = FakeArgument() fake_completer = object() complete_argument(fake_argument, fake_completer) assert fake_argument.completer is fake_completer @pytest.fixture def profiles(profile_manager): yield [ profile_manager.create_profile("foo", {"subnets": ["10.1.0.0/16"]}), profile_manager.create_profile("bar", {"subnets": ["10.2.0.0/16"]}), profile_manager.create_profile("baz", {"subnets": ["10.3.0.0/16"]}), ] @pytest.fixture def parsed_args(config_dir): yield Namespace(config=config_dir) @pytest.mark.usefixtures("profiles") class TestProfileCompleter: def test_complete_filter_prefix(self, parsed_args): """The autocomplete function returns names that match the prefix.""" assert list(profile_completer("b", parsed_args)) == ["bar", "baz"] @pytest.mark.parametrize( "running,completions", [(True, ["baz", "foo"]), (False, ["bar"])] ) def test_complete_filter_running( self, running, completions, mocker, profile_manager, parsed_args ): """The autocomplete function returns names based on running status.""" mock_manager = mocker.patch("sshoot.autocomplete.Manager") mock_manager.return_value = profile_manager profile_manager.is_running = lambda name: name != "bar" returned = list(profile_completer("", parsed_args, running=running)) assert returned == completions sshoot-1.6.0/tests/config_test.py000066400000000000000000000110511445642052600170630ustar00rootroot00000000000000from io import StringIO from textwrap import dedent import pytest import yaml from sshoot.config import yaml_dump from sshoot.profile import Profile class TestYamlDump: def test_dump_to_string(self): """The method returns YAML data as a string by default.""" data = {"foo": "bar", "baz": [1, 2]} result = yaml_dump(data) assert yaml.safe_load(stream=StringIO(result)) == data def test_dump_to_file(self): """The method dumps YAML data to the specified file.""" data = {"foo": "bar", "baz": [1, 2]} fh = StringIO() result = yaml_dump(data, fh=fh) fh.seek(0) assert result is None assert yaml.safe_load(stream=fh) == data class TestConfig: def test_add_profile(self, config): """Profiles can be added to the config.""" profiles = { "profile1": Profile(["10.0.0.0/24"]), "profile2": Profile(["192.168.0.0/16"]), } for name, profile in profiles.items(): config.add_profile(name, profile) assert config.profiles == profiles def test_add_profile_name_present(self, config): """An exception is raised if the profile name is already used.""" config.add_profile("profile", Profile(["10.0.0.0/24"])) with pytest.raises(KeyError): config.add_profile("profile", Profile(["192.168.0.0/16"])) def test_remove_profile(self, config): """Profiles can be removed to the config.""" profiles = { "profile1": Profile(["10.0.0.0/24"]), "profile2": Profile(["192.168.0.0/16"]), } for name, profile in profiles.items(): config.add_profile(name, profile) config.remove_profile("profile1") assert list(config.profiles), ["profile2"] def test_remove_profile_not_present(self, config): """An exception is raised if the profile name is not known.""" with pytest.raises(KeyError): config.remove_profile("profile") def test_load_from_file(self, config, profiles_file): """The config is loaded from file.""" profiles = {"profile": {"subnets": ["10.0.0.0/24"], "auto-nets": True}} profiles_file.write_text(yaml.dump(profiles)) config.load() profile = config.profiles["profile"] assert profile.subnets == ["10.0.0.0/24"] assert profile.auto_nets def test_load_missing_file(self, config): """If no config files are found, config is empty.""" config.load() assert config.profiles == {} assert config.config == {} def test_load_config_options(self, config, config_file): """Only known config options are loaded from config file.""" config_data = { "executable": "/usr/bin/shuttle", "other-conf": "no", "extra-options": ["--no-latency-control", "--disable-ipv6"], } config_file.write_text(yaml.dump(config_data)) config.load() assert config.config == { "executable": "/usr/bin/shuttle", "extra-options": ["--no-latency-control", "--disable-ipv6"], } def test_load_profiles(self, config, profiles_file): """The 'profiles' config field is loaded from the config file.""" profiles = { "profile1": {"subnets": ["10.0.0.0/24"]}, "profile2": {"subnets": ["192.168.0.0/16"]}, } profiles_file.write_text(yaml.dump(profiles)) config.load() expected = { name: Profile(**config) for name, config in profiles.items() } assert config.profiles == expected def test_save_profiles(self, config, profiles_file): """Profiles are saved to file.""" profiles = { "profile1": {"subnets": ["10.0.0.0/24"], "remote": "hostname1"}, "profile2": {"subnets": ["192.168.0.0/16"], "remote": "hostname2"}, } config.load() for name, conf in profiles.items(): config.add_profile(name, Profile(**conf)) config.save() config = yaml.safe_load(profiles_file.read_text()) assert config == profiles def test_save_from_file(self, config, profiles_file): """The config is saved to file.""" config.add_profile("profile", Profile(["10.0.0.0/24"], auto_nets=True)) config.save() config = dedent( """\ profile: auto-nets: true subnets: - 10.0.0.0/24 """ ) content = profiles_file.read_text() assert content == config sshoot-1.6.0/tests/conftest.py000066400000000000000000000017211445642052600164070ustar00rootroot00000000000000from pathlib import Path import pytest from sshoot.config import Config from sshoot.manager import Manager @pytest.fixture def config_dir(tmpdir): """A directory for configuration files.""" path = Path(tmpdir / "config") path.mkdir() yield path @pytest.fixture def config_file(config_dir): """The configuration file.""" yield config_dir / "config.yaml" @pytest.fixture def profiles_file(config_dir): """A Path for profiles configuration file.""" yield config_dir / "profiles.yaml" @pytest.fixture def config(config_dir): """A Config object configured with a temp path.""" yield Config(config_dir) @pytest.fixture def run_dir(tmpdir): path = Path(tmpdir / "run") path.mkdir() yield path @pytest.fixture def sessions_dir(run_dir): path = run_dir / "sessions" path.mkdir() yield path @pytest.fixture def profile_manager(config_dir, run_dir): yield Manager(config_path=config_dir, rundir=run_dir) sshoot-1.6.0/tests/listing_test.py000066400000000000000000000131241445642052600172720ustar00rootroot00000000000000import csv from io import StringIO import json import pytest import yaml from sshoot.listing import ( InvalidFormat, profile_details, ProfileListing, ) @pytest.fixture def active_profiles(profile_manager): active_profiles = [] profile_manager.is_running = lambda name: name in active_profiles yield active_profiles class TestProfileListing: def test_supported_formats(self): """supported_formats returns a list with supported formats.""" assert ProfileListing.supported_formats() == [ "csv", "json", "table", "yaml", ] def test_get_output_unsupported_format(self, profile_manager): """get_output raises an error if an unsupported format is passed.""" with pytest.raises(InvalidFormat): ProfileListing(profile_manager).get_output("unknown") def test_get_output_table(self, profile_manager, active_profiles): """Profiles can be listed as a table.""" profile_manager.create_profile( "profile1", {"subnets": ["10.0.0.0/24"]} ) profile_manager.create_profile( "profile2", {"subnets": ["192.168.0.0/16"]} ) active_profiles.append("profile2") output = ProfileListing(profile_manager).get_output("table") assert " profile1 10.0.0.0/24" in output assert "* profile2 192.168.0.0/16" in output def test_get_output_table_verbose(self, profile_manager, active_profiles): """Tabular output can be verbose.""" profile_manager.create_profile( "profile1", {"subnets": ["10.0.0.0/24"], "auto_hosts": True} ) active_profiles.append("profile2") output = ProfileListing(profile_manager).get_output( "table", verbose=True ) assert ( "Name Remote host Subnets Auto hosts Auto nets" " DNS forward Exclude subnets Seed hosts Extra options" in output ) assert ( "profile1 10.0.0.0/24 True False False" in output ) def test_get_output_csv(self, profile_manager, active_profiles): """Profiles can be listed as CSV.""" profile_manager.create_profile( "profile1", {"subnets": ["10.0.0.0/24"]} ) profile_manager.create_profile( "profile2", {"subnets": ["192.168.0.0/16"]} ) active_profiles.append("profile2") output = ProfileListing(profile_manager).get_output("csv") reader = csv.reader(StringIO(output)) assert sorted(reader) == [ [ "Name", "Status", "Remote host", "Subnets", "Auto hosts", "Auto nets", "DNS forward", "Exclude subnets", "Seed hosts", "Extra options", ], [ "profile1", "STOPPED", "", "['10.0.0.0/24']", "False", "False", "False", "", "", "", ], [ "profile2", "ACTIVE", "", "['192.168.0.0/16']", "False", "False", "False", "", "", "", ], ] def test_get_output_json(self, profile_manager, active_profiles): """Profiles can be listed as JSON.""" profile_manager.create_profile( "profile1", {"subnets": ["10.0.0.0/24"]} ) profile_manager.create_profile( "profile2", {"subnets": ["192.168.0.0/16"], "auto-hosts": True} ) active_profiles.append("profile2") output = ProfileListing(profile_manager).get_output("json") data = json.loads(output) assert data == { "profile1": {"subnets": ["10.0.0.0/24"]}, "profile2": {"subnets": ["192.168.0.0/16"], "auto-hosts": True}, } def test_get_output_yaml(self, profile_manager, active_profiles): """Profiles can be listed as YAML.""" profile_manager.create_profile( "profile1", {"subnets": ["10.0.0.0/24"]} ) profile_manager.create_profile( "profile2", {"subnets": ["192.168.0.0/16"], "auto-hosts": True} ) active_profiles.append("profile2") output = ProfileListing(profile_manager).get_output("yaml") data = yaml.safe_load(output) assert data == { "profile1": {"subnets": ["10.0.0.0/24"]}, "profile2": {"subnets": ["192.168.0.0/16"], "auto-hosts": True}, } class TestProfileDetails: def test_details(self, profile_manager): """profile_details returns a string with profile details.""" profile_manager.create_profile("profile", {"subnets": ["10.0.0.0/24"]}) output = profile_details(profile_manager, "profile") assert "Name: profile" in output assert "Subnets: 10.0.0.0/24" in output assert "Status: STOPPED" in output def test_active(self, profile_manager, active_profiles): """profile_details shows if the profile is active.""" profile_manager.create_profile("profile", {"subnets": ["10.0.0.0/24"]}) active_profiles.append("profile") output = profile_details(profile_manager, "profile") print(output) assert "Status: ACTIVE" in output sshoot-1.6.0/tests/main_test.py000066400000000000000000000107321445642052600165470ustar00rootroot00000000000000from io import StringIO import pytest from sshoot import main from sshoot.manager import ManagerProfileError @pytest.fixture def stdout(): yield StringIO() @pytest.fixture def stderr(): yield StringIO() @pytest.fixture def manager(mocker): yield mocker.MagicMock() @pytest.fixture def script(mocker, stdout, stderr, manager): mocker.patch.object(main, "Manager").return_value = manager script = main.Sshoot(stdout=stdout, stderr=stderr) yield script @pytest.fixture def sys_exit(mocker): return mocker.patch("sys.exit") class TestSshoot: def test_load_error(self, script, manager, stderr, sys_exit): """If config load fails, an error is returned.""" manager.load_config.side_effect = IOError("fail!") script(["start", "profile1"]) sys_exit.assert_called_once_with(3) assert stderr.getvalue() == "fail!\n" def test_profile_error(self, script, manager, stderr, sys_exit): """If profile load fails, an error is returned.""" manager.get_profile.side_effect = ManagerProfileError("not found") script(["show", "profile1"]) sys_exit.assert_called_once_with(2) assert stderr.getvalue() == "not found\n" def test_create(self, script, manager): """A profile can be added.""" script( [ "create", "profile1", "-r", "example.net", "10.10.0.0/16", "192.168.1.0/24", ] ) manager.create_profile.assert_called_once_with( "profile1", { "subnets": ["10.10.0.0/16", "192.168.1.0/24"], "remote": "example.net", "auto_hosts": False, "auto_nets": False, "dns": False, "exclude_subnets": None, "seed_hosts": None, "extra_opts": None, }, ) def test_show(self, script, manager, stdout): """Profile details can be viewed.""" script(["show", "profile1"]) manager.get_profile.assert_called_once_with("profile1") assert "Name: profile1" in stdout.getvalue() def test_list(self, script, stdout): """Profile list can be viewed.""" script(["list", "--format", "json"]) assert stdout.getvalue() == "{}" def test_remove(self, script, manager): """A profile can be removed.""" script(["delete", "profile1"]) manager.remove_profile.assert_called_once_with("profile1") def test_start(self, stdout, script, manager): """A profile can be started.""" script( [ "start", "--no-global-extra-options", "profile1", "--", "--syslog", ] ) manager.start_profile.assert_called_once_with( "profile1", extra_args=["--syslog"], disable_global_extra_options=True, ) assert stdout.getvalue() == "Profile started\n" def test_stop(self, stdout, script, manager): """A profile can be stopped.""" script(["stop", "profile1"]) manager.stop_profile.assert_called_once_with("profile1") assert stdout.getvalue() == "Profile stopped\n" def test_restart(self, stdout, script, manager): """A profile can be restarted.""" script(["restart", "profile1", "--", "--syslog"]) manager.restart_profile.assert_called_once_with( "profile1", extra_args=["--syslog"], disable_global_extra_options=False, ) assert stdout.getvalue() == "Profile restarted\n" @pytest.mark.parametrize("running,exit_value", [(True, 0), (False, 1)]) def test_is_running( self, mocker, sys_exit, script, manager, running, exit_value ): """It's possible to check if a profile is running.""" manager.is_running.return_value = running script(["is-running", "profile1"]) sys_exit.assert_called_once_with(exit_value) def test_get_command(self, stdout, script, manager): """It's possible to get the sshuttle commandline.""" manager.get_cmdline.return_value = ["sshuttle", "-r", "example.net"] script(["get-command", "profile1"]) manager.get_cmdline.assert_called_once_with( "profile1", disable_global_extra_options=False ) assert stdout.getvalue() == "sshuttle -r example.net\n" sshoot-1.6.0/tests/manager_test.py000066400000000000000000000360531445642052600172410ustar00rootroot00000000000000from getpass import getuser import os from pathlib import Path import signal from tempfile import gettempdir from textwrap import dedent import pytest import yaml from sshoot.manager import ( DEFAULT_CONFIG_PATH, get_rundir, kill_and_wait, Manager, ManagerProfileError, ProcessKillFail, ) from sshoot.profile import Profile def fake_executable(base_path, exit_code, error_message="stderr message"): """Create a fake executable logging command line parameters.""" executable = Path(base_path) / "executable" executable.write_text( dedent( f"""\ #!/bin/sh echo $@ > {base_path}/cmdline echo -n {error_message} >&2 exit {exit_code} """ ) ) executable.chmod(0o755) return executable @pytest.fixture def bin_succeed(tmpdir): yield fake_executable(tmpdir, 0) @pytest.fixture def bin_fail(tmpdir): yield fake_executable(tmpdir, 1) @pytest.fixture def bin_fail_silent(tmpdir): yield fake_executable(tmpdir, 1, error_message="") @pytest.fixture def profile(profile_manager): yield profile_manager.create_profile( "profile", {"subnets": ["10.0.0.0/24"]} ) @pytest.fixture def pid_file(profile, sessions_dir): yield sessions_dir / "profile.pid" class TestManager: def test_default_paths(self): """A default config path is set if not specified.""" assert Manager().config_path == DEFAULT_CONFIG_PATH def test_paths(self, profile_manager, config_dir, sessions_dir): """The config and sessions are set in the Manager.""" assert profile_manager.config_path == config_dir assert profile_manager.sessions_path == sessions_dir def test_load_config_create_dirs( self, profile_manager, config_dir, sessions_dir ): """Manager.load_config creates config directories.""" config_dir.rmdir() sessions_dir.rmdir() profile_manager.load_config() assert config_dir.is_dir() assert sessions_dir.is_dir() def test_load_profiles(self, profile_manager, profiles_file): """Manager.load_config loads the profiles.""" profiles = {"profile": {"subnets": ["10.0.0.0/16"]}} profiles_file.write_text(yaml.dump(profiles)) profile_manager.load_config() assert list(profile_manager.get_profiles()) == ["profile"] def test_create_profile(self, profile_manager, profiles_file): """Manager.create_profile adds a profile with specified details.""" profile_manager.create_profile("profile", {"subnets": ["10.0.0.0/24"]}) profiles = yaml.safe_load(profiles_file.read_text()) assert profiles == {"profile": {"subnets": ["10.0.0.0/24"]}} def test_create_profile_in_use(self, profile_manager): """Manager.create_profile raises an error if profile name is in use.""" profile_manager.create_profile("profile", {"subnets": ["10.0.0.0/24"]}) with pytest.raises(ManagerProfileError): profile_manager.create_profile( "profile", {"subnets": ["10.0.0.0/16"]} ) @pytest.mark.parametrize( "details,message", [ ( {"subnets": ["1.2.3.0/24"], "wrong": "params"}, "Invalid profile config 'wrong'", ), ({"dns": True}, "Profile missing 'subnets' config"), ], ) def test_create_profile_invalid_details( self, profile_manager, details, message ): """Manager.create_profile raises an error on invalid profile info.""" with pytest.raises(ManagerProfileError) as error: profile_manager.create_profile("profile", details) assert str(error.value) == message def test_remove_profile(self, profile_manager, profile, profiles_file): """Manager.remove_profile removes the specified profile.""" profile_manager.remove_profile("profile") config = yaml.safe_load(profiles_file.read_text()) assert config == {} def test_remove_profile_unknown(self, profile_manager): """Manager.remove_profile raises an error if name is unknown.""" with pytest.raises(ManagerProfileError): profile_manager.remove_profile("unknown") def test_get_profiles(self, profile_manager): """Manager.get_profiles returns defined profiles.""" profile_manager.create_profile( "profile1", {"subnets": ["10.0.0.0/24"]} ) profile_manager.create_profile( "profile2", {"subnets": ["192.168.0.0/16"]} ) assert profile_manager.get_profiles() == { "profile1": Profile(["10.0.0.0/24"]), "profile2": Profile(["192.168.0.0/16"]), } def test_get_profile(self, profile_manager): """Manager.get_profile returns a profile.""" config = {"subnets": ["10.0.0.0/24"]} profile_manager.create_profile("profile", config) profile = profile_manager.get_profile("profile") assert profile == Profile(**config) def test_get_profile_unknown(self, profile_manager): """Manager.get_profile raises an error if the name is unknown.""" with pytest.raises(ManagerProfileError): profile_manager.get_profile("unknown") def test_start_profile( self, profile_manager, profile, sessions_dir, bin_succeed ): """Manager.start_profile starts a profile.""" profile_manager._get_executable = lambda: str(bin_succeed) profile_manager.start_profile("profile") cmdline = (bin_succeed.parent / "cmdline").read_text() assert cmdline == ( f"10.0.0.0/24 --daemon --pidfile {sessions_dir}/profile.pid\n" ) def test_start_profile_extra_args( self, profile_manager, profile, sessions_dir, bin_succeed ): """Manager.start_profile can add extra arguments to command line.""" profile_manager._get_executable = lambda: str(bin_succeed) profile_manager.start_profile( "profile", extra_args=["--extra1", "--extra2"] ) cmdline = (bin_succeed.parent / "cmdline").read_text() assert cmdline == ( f"10.0.0.0/24 --daemon --pidfile {sessions_dir}/profile.pid --extra1 --extra2\n" ) def test_start_profile_fail(self, profile_manager, profile, bin_fail): """An error is raised if starting a profile fails.""" profile_manager._get_executable = lambda: str(bin_fail) with pytest.raises(ManagerProfileError) as err: profile_manager.start_profile("profile") assert str(err.value) == "Profile failed to start: stderr message" def test_start_profile_fail_no_error_message( self, profile_manager, profile, bin_fail_silent ): """An error is raised if starting a profile fails and no stdout is reported.""" profile_manager._get_executable = lambda: str(bin_fail_silent) with pytest.raises(ManagerProfileError) as err: profile_manager.start_profile("profile") assert ( str(err.value) == "Profile failed to start: Please see the log for more details: 'grep sshuttle /var/log/syslog'" ) def test_start_profile_executable_not_found( self, profile_manager, profile ): """Profile start raises an error if executable is not found.""" profile_manager._get_executable = lambda: "/not/here" with pytest.raises(ManagerProfileError): profile_manager.start_profile("profile") def test_start_profile_unknown(self, profile_manager): """Trying to start an unknown profile raises an error.""" with pytest.raises(ManagerProfileError): profile_manager.start_profile("unknown") def test_start_profile_running(self, profile_manager, profile): """Trying to start a running profile raises an error.""" profile_manager.is_running = lambda name: True with pytest.raises(ManagerProfileError): profile_manager.start_profile("profile") def test_stop_profile(self, mocker, profile_manager, pid_file): """Manager.stop_profile stops a running profile.""" mock_kill_and_wait = mocker.patch("sshoot.manager.kill_and_wait") pid_file.write_text("100\n") profile_manager.is_running = lambda name: True profile_manager.stop_profile("profile") mock_kill_and_wait.assert_called_once_with(100) def test_stop_profile_unknown(self, profile_manager): """Trying to stop an unknown profile raises an error.""" with pytest.raises(ManagerProfileError): profile_manager.stop_profile("unknown") def test_stop_profile_invalid_pidfile(self, profile_manager, pid_file): """If pidfile contains invalid data, stopping raises an error.""" pid_file.write_text("garbage") with pytest.raises(ManagerProfileError): profile_manager.stop_profile("profile") def test_stop_profile_process_not_found( self, mocker, profile_manager, pid_file ): """If the process fails to stop an error is raised.""" pid_file.write_text("100\n") mock_kill_and_wait = mocker.patch("sshoot.manager.kill_and_wait") mock_kill_and_wait.side_effect = ProcessLookupError profile_manager.is_running = lambda name: True with pytest.raises(ManagerProfileError) as err: profile_manager.stop_profile("profile") assert "Failed to stop profile" in str(err.value) mock_kill_and_wait.assert_called_once_with(100) def test_restart_profile( self, mocker, profile_manager, pid_file, profile, sessions_dir, bin_succeed, ): """Manage.restart_profile restarts a running profile.""" profile_manager._get_executable = lambda: str(bin_succeed) mocker.patch.object(profile_manager, "is_running").side_effect = [ True, True, False, ] mock_kill_and_wait = mocker.patch("sshoot.manager.kill_and_wait") pid_file.write_text("100\n") profile_manager.restart_profile("profile") mock_kill_and_wait.assert_called_once_with(100) cmdline = (bin_succeed.parent / "cmdline").read_text() assert cmdline == ( f"10.0.0.0/24 --daemon --pidfile {sessions_dir}/profile.pid\n" ) def test_get_pidfile(self, profile_manager, pid_file): """Manager._get_pidfile returns the pidfile path for a session.""" assert profile_manager._get_pidfile("profile") == pid_file def test_is_running(self, profile_manager, pid_file): """If the process is present, the profile is running.""" pid_file.write_text(f"{os.getpid()}\n") assert profile_manager.is_running("profile") def test_is_running_no_pidfile(self, profile_manager): """If the pidfile is not found, the profile is not running.""" assert not profile_manager.is_running("not-here") def test_is_running_pidfile_empty(self, profile_manager, pid_file): """If the pidfile is empty, the profile is not running.""" pid_file.write_text("") assert not profile_manager.is_running("profile") def test_is_running_pidfile_no_integer(self, profile_manager, pid_file): """If the pid is not an integer, the profile is not running.""" pid_file.write_text("foo\n") assert not profile_manager.is_running("profile") def test_is_running_pidfile_no_process(self, profile_manager, pid_file): """If no process is present, the profile is not running.""" pid_file.write_text("-100\n") assert not profile_manager.is_running("profile") # The stale pidfile is deleted. assert not pid_file.exists() def test_get_cmdline(self, profile_manager, pid_file): """Manager.get_cmdline returns the command line for the profile.""" assert profile_manager.get_cmdline("profile") == [ "sshuttle", "10.0.0.0/24", "--daemon", "--pidfile", str(pid_file), ] def test_get_cmdline_extra_args(self, profile_manager, pid_file): """Manager.get_cmdline adds passed extra arguments to command line.""" cmdline = profile_manager.get_cmdline( "profile", extra_args=["--extra1", "--extra2"] ) assert cmdline == [ "sshuttle", "10.0.0.0/24", "--daemon", "--pidfile", str(pid_file), "--extra1", "--extra2", ] def test_get_cmdline_executable(self, profile_manager, pid_file): """Manager.get_cmdline uses the configured executable.""" profile_manager._get_executable = lambda: "/foo/sshuttle" assert profile_manager.get_cmdline("profile") == [ "/foo/sshuttle", "10.0.0.0/24", "--daemon", "--pidfile", str(pid_file), ] @pytest.fixture def mock_kill(mocker): yield mocker.patch("sshoot.manager.os.kill") @pytest.fixture def mock_sleep(mocker): yield mocker.patch("sshoot.manager.time.sleep") class TestKillAndWait: def test_return_if_process_dead(self, mock_kill, mock_sleep): """No error is reported if the process is not found.""" mock_kill.side_effect = ProcessLookupError kill_and_wait(123) mock_kill.assert_called_once_with(123, signal.SIGTERM) mock_sleep.assert_not_called() def test_retry(self, mocker, mock_kill, mock_sleep): """The kill call is retried if process isn't dead yet.""" mock_kill.side_effect = [None, None, ProcessLookupError] kill_and_wait(123) assert mock_kill.mock_calls == [mocker.call(123, signal.SIGTERM)] * 3 assert mock_sleep.mock_calls == [mocker.call(0.2)] * 2 def test_retry_term_and_killl(self, mocker, mock_kill, mock_sleep): """The kill is performed with SIGKILL after SIGTERM.""" mock_kill.side_effect = [None] * 12 + [ProcessLookupError] kill_and_wait(123) mock_kill assert ( mock_kill.mock_calls == [mocker.call(123, signal.SIGTERM)] * 11 + [mocker.call(123, signal.SIGKILL)] * 2 ) def test_raises_eventually(self, mocker, mock_kill, mock_sleep): """If the process doesn't die, an error is raised.""" with pytest.raises(ProcessKillFail) as error: kill_and_wait(123) assert error.value.pid == 123 assert ( mock_kill.mock_calls == [mocker.call(123, signal.SIGTERM)] * 11 + [mocker.call(123, signal.SIGKILL)] * 6 ) def test_no_retry_on_error(self, mock_kill, mock_sleep): """If the kill call fails, the error is raised.""" mock_kill.side_effect = PermissionError with pytest.raises(PermissionError): kill_and_wait(123) mock_kill.assert_called_once_with(123, signal.SIGTERM) mock_sleep.assert_not_called() class TestGetRundir: def test_rundir_path(self): """get_rundir returns a user-specific tempdir path.""" rundir_path = Path(gettempdir()) / f"foo-{getuser()}" assert get_rundir("foo") == rundir_path sshoot-1.6.0/tests/profile_test.py000066400000000000000000000102251445642052600172600ustar00rootroot00000000000000import pytest from sshoot.profile import ( Profile, ProfileError, ) @pytest.fixture def profile(): yield Profile(["1.1.1.0/24", "10.10.0.0/16"]) class TestProfile: def test_cmdline(self, profile): """Profile.cmdline() return the sshuttle cmdline for the config.""" assert profile.cmdline() == ["sshuttle", "1.1.1.0/24", "10.10.0.0/16"] def test_cmdline_with_options(self, profile): """Profile.cmdline() return the sshuttle cmdline for the config.""" profile.remote = "1.2.3.4" profile.auto_hosts = True profile.auto_nets = True profile.dns = True profile.cmdline() == [ "sshuttle", "1.1.1.0/24", "10.10.0.0/16", "--remote=1.2.3.4", "--auto-hosts", "--auto-nets", "--dns", ] def test_cmdline_exclude_subnets(self, profile): """Profile.cmdline() includes excluded subnets in the cmdline.""" profile.exclude_subnets = ["10.20.0.0/16", "10.30.0.0/16"] profile.cmdline() == [ "sshuttle", "1.1.1.0/24", "10.10.0.0/16", "--exclude=10.20.0.0/16", "--exclude=10.30.0.0/16", ] def test_cmdline_seed_hosts(self, profile): """Profile.cmdline() includes seeded hosts in the cmdline.""" profile.seed_hosts = ["10.1.2.3", "10.4.5.6"] profile.cmdline(), [ "sshuttle", "1.1.1.0/24", "10.10.0.0/16", "--seed-hosts=10.1.2.3,10.4.5.6", ] def test_cmdline_with_profile_extra_opts(self, profile): """Profile.cmdline() return the sshuttle cmdline with extra options.""" profile.extra_opts = ["--verbose", "--daemon"] assert profile.cmdline() == [ "sshuttle", "1.1.1.0/24", "10.10.0.0/16", "--verbose", "--daemon", ] def test_cmdline_with_extra_opts(self, profile): """Profile.cmdline() includes extra options.""" profile.cmdline(extra_opts=["--verbose", "--daemon"]), [ "sshuttle", "1.1.1.0/24", "10.10.0.0/16", "--verbose", "--daemon", ] def test_cmdline_with_executable(self, profile): """Profile.cmdline() uses the specified executable.""" assert profile.cmdline(executable="/bin/foo") == [ "/bin/foo", "1.1.1.0/24", "10.10.0.0/16", ] def test_cmdline_with_global_extra_options(self, profile): """Profile.cmdline() includes global extra options.""" profile.cmdline(global_extra_options=["--verbose", "--daemon"]), [ "sshuttle", "1.1.1.0/24", "10.10.0.0/16", "--verbose", "--daemon", ] def test_config(self, profile): """Profile.config() returns a dict with the profile config.""" profile.remote = "1.2.3.4" profile.dns = True profile.auto_hosts = True assert profile.config() == { "auto-hosts": True, "remote": "1.2.3.4", "dns": True, "subnets": ["1.1.1.0/24", "10.10.0.0/16"], } def test_from_config(self, profile): """Profile.from-config builds a profile from a config.""" assert Profile.from_config(profile.config()) == profile def test_from_config_missing_subnets(self): """An error is raised if config is missing the 'subnets' key.""" with pytest.raises(ProfileError) as error: Profile.from_config({}) assert str(error.value) == "Profile missing 'subnets' config" def test_update(self, profile): """A Profile can be updated.""" profile.update({"auto-nets": True, "subnets": ["1.2.3.0/24"]}) assert profile.auto_nets assert profile.subnets == ["1.2.3.0/24"] def test_update_invalid_config(self, profile): """An error is raised if invalid key is passed to Profile.update().""" with pytest.raises(ProfileError) as error: profile.update({"unknown": "key"}) assert str(error.value) == "Invalid profile config 'unknown'" sshoot-1.6.0/tox.ini000066400000000000000000000024151445642052600143620ustar00rootroot00000000000000[tox] requires = tox>=4.2 no_package = true [testenv] deps = .[testing] commands = pytest {posargs} [testenv:check] deps = mypy commands = mypy -p sshoot {posargs} [testenv:coverage] deps = .[testing] pytest-cov commands = pytest --cov sshoot/ {posargs} [testenv:docs] deps = . sphinx sphinx-autodoc-typehints commands = sphinx-build -b html docs html {posargs} [testenv:format] deps = black isort pyproject-fmt tox-ini-fmt commands = isort {[base]lint_files} black -q {[base]lint_files} - pyproject-fmt pyproject.toml - tox-ini-fmt tox.ini [testenv:i18n] deps = Babel commands = pybabel extract --project sshoot --sort-by-file --output sshoot/locale/sshoot.pot sshoot pybabel update --domain sshoot --input-file sshoot/locale/sshoot.pot --output-dir sshoot/locale pybabel compile --domain sshoot --directory sshoot/locale [testenv:lint] deps = black flake8 flake8-pyproject isort pyproject-fmt commands = isort --check-only --diff {[base]lint_files} black --check {[base]lint_files} flake8 {[base]lint_files} pyproject-fmt --check pyproject.toml [testenv:run] deps = -e . commands = sshoot {posargs} [base] lint_files = sshoot \ tests