pax_global_header00006660000000000000000000000064134243640020014510gustar00rootroot0000000000000052 comment=333ef1ed1d7c7c17264fcf7629e5c2f78ab4112c networkd-dispatcher-2.0.1/000077500000000000000000000000001342436400200154715ustar00rootroot00000000000000networkd-dispatcher-2.0.1/.gitignore000066400000000000000000000000701342436400200174560ustar00rootroot00000000000000etc *.8 *__pycache__ tags *.cache *.coverage .tox *.pyc networkd-dispatcher-2.0.1/.gitlab-ci.yml000066400000000000000000000022611342436400200201260ustar00rootroot00000000000000# This is used by the python containers, which run Debian before_script: - apt update - apt install -y gobject-introspection tox dbus libdbus-1-dev libgirepository1.0-dev python3-cairo-dev pylint3 flake8 python3-dbus - python -V cache: paths: - .tox/ stages: - linters - tests test-archlinux-py3.7: stage: tests image: base/archlinux before_script: - pacman -Sy - pacman -S --noconfirm python-tox gobject-introspection base-devel cairo - python -V script: - TOXENV=py37 tox test-py3.4: stage: tests image: python:3.4 script: - TOXENV=py34 tox test-py3.5: stage: tests image: python:3.5 script: - TOXENV=py35 tox test-py3.6: stage: tests image: python:3.6 script: - TOXENV=py36 tox test-no-gi: stage: tests image: python:3.7 before_script: - apt update - apt install -y tox dbus libdbus-1-dev libgirepository1.0-dev python3-cairo-dev pylint3 flake8 python3-dbus - python -V script: - TOXENV=py37 tox pylint: stage: linters image: python:3.7 script: - pylint3 -d C0111,C0103 networkd_dispatcher.py flake8: stage: linters image: python:3.7 script: - flake8 networkd_dispatcher.py networkd-dispatcher-2.0.1/LICENSE000066400000000000000000001045051342436400200165030ustar00rootroot00000000000000 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. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} 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: {project} Copyright (C) {year} {fullname} 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 . networkd-dispatcher-2.0.1/Makefile000066400000000000000000000002561342436400200171340ustar00rootroot00000000000000A2X = a2x RM = rm -f MAN_SRCs = networkd-dispatcher.txt MAN_OUT = $(MAN_SRCs:%.txt=%.8) all: $(MAN_OUT) clean: $(RM) $(MAN_OUT) %.8: %.txt @$(A2X) --format manpage $< networkd-dispatcher-2.0.1/README.md000066400000000000000000000132461342436400200167560ustar00rootroot00000000000000# networkd-dispatcher Networkd-dispatcher is a dispatcher daemon for systemd-networkd connection status changes. This daemon is similar to [NetworkManager-dispatcher](https://developer.gnome.org/NetworkManager/unstable/NetworkManager.html), but is much more limited in the types of events it supports due to the limited nature of systemd-networkd. Desired actions (scripts) are placed into directories that reflect [systemd-networkd operational states](https://www.freedesktop.org/software/systemd/man/networkctl.html), and are executed when the daemon receives the relevant event from systemd-networkd. The daemon listens for signals from systemd-networkd over dbus, so it should be very light on resources (e.g. no polling). It is meant to be run as a system-wide daemon (as root). This allows it to be used for tasks such as starting a VPN after a connection is established. ## Usage The daemon expects that scripts are 1) executable and 2) owned by root (gid = uid = 0), and will not execute scripts that are otherwise. Scripts can be installed into these directories under ```/usr/lib/networkd-dispatcher``` for system packages, and ```/etc/networkd-dispatcher``` for local overrides: ``` routable.d/ dormant.d/ no-carrier.d/ off.d/ carrier.d/ degraded.d/ ``` networkd-dispatcher will execute any valid scripts in the directory that reflects the new state. Scripts are executed in the alpha-numeric order in which they are named, starting with 0 and ending with z. For example, a script named ```50runme``` would run before ```99runmenext```. Scripts are executed with some environment variables set. Some of these variables may not be set or may be set to an empty value, dependent upon the type of event. These can be used by scripts to conditionally take action based on a specific interface, state, etc. - ```IFACE``` - interface that triggered the event - ```STATE``` - The destination state change for which a script is currently being invoked. May be any of the values listed as valid for `AdministrativeState` or `OperationalState`. - ```ESSID``` - for wlan connections, the ESSID the device is connected to - ```ADDR``` - the ipv4 address of the device - ```IP_ADDRS``` - space-delimited string of ipv4 address(es) assigned to the device (see note below) - ```IP6_ADDRS``` - space-delimited string of ipv6 address(es) assigned to the device (see note below) - ```AdministrativeState``` - One of `pending`, `configuring`, `configured`, `unmanaged`, `failed` or `linger`. - ```OperationalState``` - One of `off`, `no-carrier`, `dormant`, `carrier`, `degraded` or `routable`. For more information about the network operational states exposed by systemd, see the `networkctl` manpage (`man networkctl`). - ```json``` - A JSON encoding of this program's interpretation of `networkctl status "$IFACE"`, when the event is one for which such information is available; for debug logs or inspection with JSON-aware tools such as `jq`. Exact structure details are implementation-defined and liable to change. *Note: For `IP_ADDRS` and `IP6_ADDRS`, the space-delimited string can be read into a BASH array like this: ```read -r -a ip_addrs <<<"$IP_ADDRS"``` ### Command-Line Options ``` usage: networkd-dispatcher [-h] [-S SCRIPT_DIR] [-T] [-v] [-q] networkd dispatcher daemon optional arguments: -h, --help show this help message and exit -S SCRIPT_DIR, --script-dir SCRIPT_DIR Location under which to look for scripts [default: /etc/networkd-dispatcher:/usr/lib/networkd-dispatcher] -T, --run-startup-triggers Generate events reflecting preexisting state and behavior on startup [default: False] -v, --verbose Increment verbosity level once per call -q, --quiet Decrement verbosity level once per call ``` Some further notes: - The intended use case of `--run-startup-triggers` is race-condition avoidance: Ensuring that triggers are belatedly run even if networkd-dispatcher is invoked after systemd-networkd has already started an interface. - The default log level is `WARNING`. Each use of `-v` will increment the log level (towards `INFO` or `DEBUG`), and each use of `-q` will decrement it (towards `ERROR` or `CRITICAL`). ### Systemd Service There is an included systemd service file, `networkd-dispatcher.service`, which can be used to run networkd-dispatcher as a service. To specify command line options for the service, add them to a variable `networkd_dispatcher_args` in `/etc/conf.d/networkd-dispatcher.conf`. A template conf file is included. ## Installation ### Arch Linux This package can be [installed from AUR](https://aur.archlinux.org/packages/networkd-dispatcher/). ### Other Linux Folks Requirements: - \>= python 3.4 - python-gobject - python-dbus - Handling of wireless interfaces requires one of the following tools to be installed: - wireless_tools (providing iwconfig) - iw Copy networkd-dispatcher to /usr/bin. Create the appropriate directory structure: ```$ sudo mkdir -p /etc/networkd-dispatcher/{routable,dormant,no-carrier,off,carrier,degraded}.d``` Install networkd-dispatcher.conf to /etc/conf.d. Install networkd-dispatcher.service and start it. If networkd-dispatcher was not copied to /usr/bin, then edit service file to reflect the appropriate path. ## Contributors - [craftyguy](https://github.com/craftyguy) (Clayton Craft) - [charles-dyfis-net](https://github.com/charles-dyfis-net) (Charles Duffy) - [ryu0](https://github.com/ryu0) (James Buren) - [raharper](https://github.com/raharper) (Ryan Harper) A large portion of the code was leveraged from [networkd-notify](https://github.com/wavexx/networkd-notify), which was written by wavexx (Yuri D'Elia) networkd-dispatcher-2.0.1/__init__.py000066400000000000000000000000421342436400200175760ustar00rootroot00000000000000from networkd_dispatcher import * networkd-dispatcher-2.0.1/networkd-dispatcher000077500000000000000000000433721342436400200214110ustar00rootroot00000000000000#!/usr/bin/env python3 # networkd-dispatcher # Dispatcher service for systemd-networkd # Copyright(c) 2016 by wave++ "Yuri D'Elia" # Distributed under GPLv3+ (see COPYING) WITHOUT ANY WARRANTY. # Copyright(c) 2018 by craftyguy "Clayton Craft" # Distributed under GPLv3+ (see COPYING) WITHOUT ANY WARRANTY. from __future__ import print_function, division, generators, unicode_literals import argparse import collections import errno import json import logging import os import socket import stat import subprocess import sys # Try to import the dynamic glib, or try to fall back to static try: from gi.repository import GLib as glib # pragma: no cover except ImportError: # pragma: no cover import glib # pragma: no cover import dbus import dbus.mainloop.glib logger = logging.getLogger('networkd-dispatcher') # Detect up-front which commands we use exist def resolve_path(cmdname): for dirname in os.environ['PATH'].split(':'): path = os.path.join(dirname, cmdname) if os.path.exists(path): return path logger.warning('No valid path found for %s', cmdname) return None # Constants NETWORKCTL = resolve_path('networkctl') DEFAULT_SCRIPT_DIR = '/etc/networkd-dispatcher:/usr/lib/networkd-dispatcher' # Supported wireless tools IWCONFIG = resolve_path('iwconfig') IW = resolve_path('iw') LOG_FORMAT = '%(levelname)s:%(message)s' SINGLETONS = {'Type', 'ESSID', 'OperationalState'} AddressList = collections.namedtuple('AddressList', ['ipv4', 'ipv6']) NetworkctlListState = collections.namedtuple('NetworkctlListState', ['idx', 'name', 'type', 'operational', 'administrative']) def unquote(buf, char='\\'): """Remove escape characters from iwconfig ESSID output""" idx = 0 while True: idx = buf.find(char, idx) if idx < 0: break buf = buf[:idx] + buf[idx+1:] idx += 1 return buf def get_networkctl_list(): """Update the mapping from interface index numbers to state""" try: out = subprocess.check_output([NETWORKCTL, 'list', '--no-pager', '--no-legend']) except subprocess.CalledProcessError as e: logger.error('networkctl list failed: %s', e) return [] result = [] for line in out.split(b'\n')[:-1]: fields = line.decode('utf-8', errors='replace').split() idx_s = fields.pop(0) result.append(NetworkctlListState(int(idx_s), *fields)) return result def get_networkctl_status(iface_name): """Return a dictionary mapping keys to lists (or strings if in SINGLETONS)""" data = collections.defaultdict(list) try: out = subprocess.check_output([NETWORKCTL, 'status', '--no-pager', '--no-legend', '--', iface_name]) except subprocess.CalledProcessError as e: logger.error('Failed to get interface "%s" status: %s', iface_name, e) return data oldk = None for line in out.split(b'\n')[1:-1]: line = line.decode('utf-8', errors='replace') k = line[:16].strip() or oldk oldk = k v = line[18:].strip() if k in SINGLETONS: data[k] = v else: data[k].append(v) return data def get_wlan_essid(iface_name): """Given an interface name, return its ESSID""" if IWCONFIG is None: if IW is None: logger.error('Unable to retrieve ESSID for wireless interface %s: ' 'no supported wireless tool installed', iface_name) return '' return iw_get_ssid(iface_name) return iwconfig_get_ssid(iface_name) def iw_get_ssid(iface_name): out = subprocess.check_output([IW, iface_name, 'link']) lines = out.decode('utf-8', errors='replace').split('\n') line = [s for s in lines if 'SSID' in s] if not line: logger.warning('Unable to retrieve ESSID for wireless interface %s.', iface_name) return '' essid = line[0].rsplit(" ")[1] return unquote(essid) def iwconfig_get_ssid(iface_name): out = subprocess.check_output([IWCONFIG, '--', iface_name]) line = out.split(b'\n')[0].decode('utf-8', errors='replace') essid = line[line.find('ESSID:')+7:-3] return unquote(essid) def scripts_in_path(path, subdir): """Given directory names in PATH notation (separated by :), and a subdirectory name, return a sorted list of executables contained in that subdirectory, such that executables in earlier path components override those with the same name in later path components.""" script_list = [] base_filenames = set() for one_path in path.split(":"): one_path = os.path.join(one_path, subdir) if not os.path.exists(one_path): logger.debug("Path %r does not exist; skipping", one_path) continue base_filenames.update(os.listdir(one_path)) for filename in sorted(base_filenames): for one_path in path.split(":"): pathname = os.path.join(one_path, subdir, filename) logger.debug("Checking if %s exists as %s", filename, pathname) if os.path.isfile(pathname): entry = os.stat(pathname) # Make sure script can be executed if not stat.S_IXUSR & entry.st_mode: logger.error("Unable to execute script, check file mode: " "%s", pathname) # Make sure script is owned by root elif entry.st_uid != 0 or entry.st_gid != 0: logger.error("Unable to execute script, check file perms: " "%s", pathname) else: script_list.append(pathname) break return script_list def parse_address_strings(addrs): """Given a list of addresses, discard uninteresting ones, and sort the rest into IPv4 vs IPv6""" ip4addrs = [] ip6addrs = [] for addr in addrs: if addr.startswith('127.') or \ addr.startswith('fe80:'): continue if ':' in addr: ip6addrs.append(addr) elif '.' in addr: ip4addrs.append(addr) return AddressList(ip4addrs, ip6addrs) def get_interface_data(iface): """Return JSON-serializable data representing all state needed to run hooks for the given interface""" data = {'Type': iface.type, 'OperationalState': iface.operational, 'AdministrativeState': iface.administrative, "InterfaceName": iface.name} # Always collect what data we can. data.update(get_networkctl_status(iface.name)) # The returned state may be different than what was read from # 'networkctl list', so construct state based on th iface data. # See Issue #24. data['State'] = (data.get('OperationalState', '') + " (" + data.get('AdministrativeState', '') + ")") if data.get('Type') == 'wlan': data['ESSID'] = get_wlan_essid(iface.name) return data class Dispatcher(): iface_names_by_idx = {} # only changed on rescan ifaces_by_name = {} # updated on every state change def __init__(self, script_dir=DEFAULT_SCRIPT_DIR): self.script_dir = script_dir self._interface_scan() def __repr__(self): return '' % (self.__dict__,) def _interface_scan(self): iface_list = get_networkctl_list() # Append new interfaces, keeping old ones around to avoid hotplug race # condition (issue #20) for i in iface_list: if i not in self.iface_names_by_idx: self.iface_names_by_idx[i.idx] = i.name self.ifaces_by_name[i.name] = i logger.debug('Performed interface scan; state: %r', self) def register(self, bus=None): """Register this dispatcher to handle events from the given bus""" if bus is None: bus = dbus.SystemBus() bus.add_signal_receiver(self._receive_signal, bus_name='org.freedesktop.network1', signal_name='PropertiesChanged', path_keyword='path') def trigger_all(self): """Immediately invoke all scripts for the last known (or initial) states for each interface""" logger.info('Triggering scripts for last-known state for all' 'interfaces') for iface_name, iface in self.ifaces_by_name.items(): logger.debug('Running immediate triggers for %r', iface) try: self.handle_state(iface_name, administrative_state=iface.administrative, operational_state=iface.operational, force=True) # pylint: disable=broad-except except Exception: logger.exception('Error handling initial for interface %r', iface) def get_scripts_list(self, state): """Return scripts for the given state""" return scripts_in_path(self.script_dir, state + ".d") def _handle_one_state(self, iface_name, state, state_type, force=False): """Process a single state change""" try: if state is None: return prior_iface = self.ifaces_by_name.get(iface_name) if prior_iface is None: logger.error('Attempting to handle state for unknown interface' ' %r', iface_name) return prior_state = getattr(prior_iface, state_type) if force is False and state == prior_state: logger.debug('No change represented by %s state %r for ' 'interface %r', state_type, state, iface_name) return new_iface = prior_iface._replace(**{state_type: state}) self.ifaces_by_name[new_iface.name] = new_iface self.run_hooks_for_state(new_iface, state) # pylint: disable=broad-except except Exception: logger.exception('Error handling notification for interface %r ' 'entering %s state %s', iface_name, state_type, state) def handle_state(self, iface_name, administrative_state=None, operational_state=None, force=False): self._handle_one_state(iface_name, administrative_state, 'administrative', force=force) self._handle_one_state(iface_name, operational_state, 'operational', force=force) def run_hooks_for_state(self, iface, state): """Run all hooks associated with a given state""" # No actions to take? Do nothing. script_list = self.get_scripts_list(state) if not script_list: logger.debug('Ignoring notification for interface %r entering ' 'state %r: no triggers', iface, state) return # Collect data data = get_interface_data(iface) (v4addrs, v6addrs) = parse_address_strings(data.get('Address', ())) # Set script env. variables script_env = dict(os.environ) script_env.update({ 'ADDR': (data.get('Address', ['']) + [''])[0], 'ESSID': data.get('ESSID', ''), 'IP_ADDRS': ' '.join(v4addrs), 'IP6_ADDRS': ' '.join(v6addrs), 'IFACE': iface.name, 'STATE': str(state), 'AdministrativeState': data.get('AdministrativeState', ''), 'OperationalState': data.get('OperationalState', ''), 'json': json.dumps(data, sort_keys=True), }) # run all valid scripts in the list logger.debug('Running triggers for interface %r entering state %r ' 'with environment %r', iface, state, script_env) for script in script_list: logger.info('Invoking %r for interface %s', script, iface.name) ret = subprocess.Popen(script, env=script_env).wait() if ret != 0: logger.warning('Exit status %r from script %r invoked with ' 'environment %r', ret, script, script_env) def _receive_signal(self, typ, data, _, path): logger.debug('Signal: typ=%r, data=%r, path=%r', typ, data, path) if typ != 'org.freedesktop.network1.Link': logger.debug('Ignoring signal received with unexpected typ %r', typ) return if not path.startswith('/org/freedesktop/network1/link/_'): logger.warning('Ignoring signal received with unexpected path %r', path) return # Detect necessity of reloading map *before* filtering ignored states # http://thread.gmane.org/gmane.comp.sysutils.systemd.devel/36460 idx = path[32:] idx = int(chr(int(idx[:2], 16)) + idx[2:]) if idx not in self.iface_names_by_idx: # Try to reload configuration if even an ignored message is seen logger.warning('Unknown index %r seen, reloading interface list', idx) self._interface_scan() try: iface_name = self.iface_names_by_idx[idx] except KeyError: # Presumptive race condition: We reloaded, but the index is # still invalid logger.error('Unknown interface index %r seen even after reload', idx) return operational_state = data.get('OperationalState', None) administrative_state = data.get('AdministrativeState', None) if ((operational_state is not None) or (administrative_state is not None)): self.handle_state(iface_name, administrative_state=str(administrative_state) if administrative_state else None, operational_state=str(operational_state) if operational_state else None,) # Handle interfaces that have been removed if administrative_state == 'linger': try: self.iface_names_by_idx.pop(idx) self.ifaces_by_name.pop(iface_name) except KeyError: logger.error('Unable to remove interface at index %r.', idx) def sd_notify(**kwargs): """Systemd sd_notify implementation for Python. Note: kwargs should contain the state to send to systemd""" if not kwargs: logger.error("sd_notify called with no state specified!") return -errno.EINVAL sock = None try: # Turn state, a dictionary, into a properly formatted string where # each 'key=val' combo in the dictionary is separated by a \n state_str = '\n'.join(['{0}={1}'.format(key, val) for (key, val) in kwargs.items()]) env = os.environ.get('NOTIFY_SOCKET', None) if not env: # Process was not invoked with systemd return -errno.EINVAL if env[0] not in ('/', '@'): logger.warning("NOTIFY_SOCKET is set, but does not contain a " "legitimate value") return -errno.EINVAL if env[0] == '@': env = '\0' + env[1:] sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) if sock.sendto(bytearray(state_str, 'utf-8'), env) > 0: return 1 # pylint: disable=broad-except except Exception: logger.exception("Ignoring unexpected error during sd_notify() " "invocation") if sock: sock.close() return 0 def parse_args(args): """Parses arguments from command line""" ap = argparse.ArgumentParser(description='networkd dispatcher daemon') ap.add_argument('-S', '--script-dir', action='store', default=DEFAULT_SCRIPT_DIR, help='Location under which to look for scripts [default: ' '%(default)s]') ap.add_argument('-T', '--run-startup-triggers', action='store_true', help='Generate events reflecting preexisting state and ' 'behavior on startup [default: %(default)s]') ap.add_argument('-v', '--verbose', action='count', default=0, help='Increment verbosity level once per call') ap.add_argument('-q', '--quiet', action='count', default=0, help='Decrement verbosity level once per call') return ap.parse_args(args) def main(): args = parse_args(sys.argv[1:]) verbosity_num = (args.verbose - args.quiet) if verbosity_num <= -2: log_level = logging.CRITICAL elif verbosity_num <= -1: log_level = logging.ERROR elif verbosity_num == 0: log_level = logging.WARNING elif verbosity_num == 1: log_level = logging.INFO else: log_level = logging.DEBUG logging.basicConfig(level=log_level, format=LOG_FORMAT) dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) if NETWORKCTL is None: logger.critical('Unable to find networkctl command; cannot continue') sd_notify(ERRNO=errno.ENOENT) sys.exit(1) dispatcher = Dispatcher(script_dir=args.script_dir) dispatcher.register() # After configuring the receiver, run initial operations if args.run_startup_triggers: dispatcher.trigger_all() # main loop mainloop = glib.MainLoop() # Signal to systemd that service is runnning sd_notify(READY=1) logger.info('Startup complete') mainloop.run() def init(): if __name__ == '__main__': main() init() # vim: ai et sts=4 sw=4 ts=4 networkd-dispatcher-2.0.1/networkd-dispatcher.conf000066400000000000000000000002021342436400200223130ustar00rootroot00000000000000# Specify command line options here. This config file is used # by the included systemd service file. networkd_dispatcher_args="" networkd-dispatcher-2.0.1/networkd-dispatcher.service000066400000000000000000000004121342436400200230310ustar00rootroot00000000000000[Unit] Description=Dispatcher daemon for systemd-networkd [Service] Type=notify ExecStart=/usr/bin/networkd-dispatcher $networkd_dispatcher_args # Load /etc/conf.d/networkd-dispatcher.conf EnvironmentFile=-/etc/conf.d/%p.conf [Install] WantedBy=multi-user.target networkd-dispatcher-2.0.1/networkd-dispatcher.txt000066400000000000000000000050751342436400200222220ustar00rootroot00000000000000networkd-dispatcher(8) ====================== :doctype: manpage NAME ---- networkd-dispatcher - Dispatcher service for systemd-networkd connection status changes SYNOPSIS -------- *networkd-dispatcher* [-h] [-S 'SCRIPT_DIR'] [-T] [-v] [-q] DESCRIPTION ----------- Dispatcher daemon for systemd-networkd connection status changes. This daemon is similar to NetworkManager-dispatcher, but is much more limited in the types of events it supports due to the limited nature of 'systemd-networkd(8)'. Desired actions (scripts) are placed into directories that reflect systemd-networkd operational states under 'SCRIPT_DIR' and are executed when the daemon receives the relevant event from systemd-networkd. The daemon listens for signals from systemd-networkd over dbus, so it should be very light on resources (e.g. no polling). It is meant to be run as a system-wide daemon (as root). This allows it to be used for tasks such as starting a VPN after a connection is established. OPTIONS ------- *-h, --help*:: Print command-line syntax and program options to stdout. *-S, --script-dir='SCRIPT_DIR'*:: Location under which to look for scripts. Like the 'PATH' environment variable, this may contain multiple directories separated by : and in case multiple directories have scripts with the same name, the earliest directory wins. Defaults to /etc/networkd-dispatcher:/usr/lib/networkd-dispatcher. *-T, --run-startup-triggers*:: Generate events reflecting preexisting state and behavior on startup. This can be used to ensure that triggers are belatedly run even if networkd-dispatcher is invoked after systemd-networkd has already started an interface. *-v, --verbose*:: Increase verbosity by one level. The default level is 'WARNING'. Each use of '-v' will increment the log level (towards 'INFO' or 'DEBUG'), and each use of '-q' will decrement it (towards 'ERROR' or 'CRITICAL'). *-q, --quiet*:: Decrease verbosity by one level. CONFIGURATION FILES ------------------- The systemd service reads '/etc/conf.d/networkd-dispatcher.conf' as an environment file for additional daemon arguments. The scripts to be run on network changes are in subdirectories 'routable.d/', 'dormant.d/', 'no-carrier.d/', 'off.d/', 'carrier.d/', 'degraded.d/' inside 'SCRIPT_DIR'. The default value for 'SCRIPT_DIR' is '/etc/networkd-dispatcher:/usr/lib/networkd-dispatcher'. For information about the network operational states exposed by systemd, see networkctl(1). RESOURCES --------- GitHub: https://github.com/craftyguy/networkd-dispatcher SEE ALSO -------- systemd-networkd(8), networkctl(1) networkd-dispatcher-2.0.1/networkd_dispatcher.py000077700000000000000000000000001342436400200260052networkd-dispatcherustar00rootroot00000000000000networkd-dispatcher-2.0.1/tests/000077500000000000000000000000001342436400200166335ustar00rootroot00000000000000networkd-dispatcher-2.0.1/tests/conftest.py000066400000000000000000000206201342436400200210320ustar00rootroot00000000000000import os import pytest import sys myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../') import networkd_dispatcher @pytest.fixture() def scripts_etc(): return { 'dormant.d': [ "/etc/networkd-dispatcher/dormant.d/92-mount-netdrive.sh", "/etc/networkd-dispatcher/dormant.d/80-show-status-notify.sh", "/etc/networkd-dispatcher/dormant.d/80-stop-vpn", "/etc/networkd-dispatcher/dormant.d/90-blah.sh", "/etc/networkd-dispatcher/dormant.d/20-stop-vpn.sh", ], 'no-carrier.d': [ "/etc/networkd-dispatcher/no-carrier.d/display-notification", ], 'off.d': [ "/etc/networkd-dispatcher/off.d/00-stop-net-services.sh", ], 'routable.d': [ "/etc/networkd-dispatcher/routable.d/enable-tracking-service.sh", "/etc/networkd-dispatcher/routable.d/19-whatever.sh", "/etc/networkd-dispatcher/routable.d/99-not-important.sh", "/etc/networkd-dispatcher/routable.d/50-start-netdrive", ], 'carrier.d': [ "/etc/networkd-dispatcher/carrier.d/01-set-ip.sh", ], 'degraded.d': [ "/etc/networkd-dispatcher/degraded.d/39-catch-fire.sh", ], } @pytest.fixture() def scripts_usr(): return { 'dormant.d': [ "/usr/lib/networkd-dispatcher/dormant.d/92-mount-netdrive.sh", ], 'no-carrier.d': [ "/usr/lib/networkd-dispatcher/no-carrier.d/50-script", "/usr/lib/networkd-dispatcher/no-carrier.d/10-script-important.sh", ], 'off.d': [ "/usr/lib/networkd-dispatcher/off.d/20-stop-vpn.sh", ], 'routable.d': [ "/usr/lib/networkd-dispatcher/routable.d/40-enable-ntp.sh", "/usr/lib/networkd-dispatcher/routable.d/enable-tracking-service.sh", ], 'carrier.d': [ "/usr/lib/networkd-dispatcher/carrier.d/99-so-stuff.sh", "/usr/lib/networkd-dispatcher/carrier.d/01-set-ip.sh", ], 'degraded.d': [ "/usr/lib/networkd-dispatcher/degraded.d/39-catch-fire.sh", ], } @pytest.fixture() def scripts_etc_filenames(): return { 'dormant.d': [ "92-mount-netdrive.sh", "80-show-status-notify.sh", "80-stop-vpn", "90-blah.sh", "20-stop-vpn.sh", ], 'no-carrier.d': [ "display-notification", ], 'off.d': [ "00-stop-net-services.sh", ], 'routable.d': [ "enable-tracking-service.sh", "19-whatever.sh", "50-start-netdrive", "99-not-important.sh", ], 'carrier.d': [ "01-set-ip.sh", ], 'degraded.d': [ "39-catch-fire.sh", ], } @pytest.fixture() def scripts_usr_filenames(): return { 'dormant.d': [ "92-mount-netdrive.sh", ], 'no-carrier.d': [ "50-script", "10-script-important.sh", ], 'off.d': [ "20-stop-vpn.sh", ], 'routable.d': [ "40-enable-ntp.sh", "enable-tracking-service.sh", ], 'carrier.d': [ "99-so-stuff.sh", "01-set-ip.sh", ], 'degraded.d': [ "39-catch-fire.sh", ], } @pytest.fixture() def scripts_sorted(): return { 'dormant.d': [ "/etc/networkd-dispatcher/dormant.d/20-stop-vpn.sh", "/etc/networkd-dispatcher/dormant.d/80-show-status-notify.sh", "/etc/networkd-dispatcher/dormant.d/80-stop-vpn", "/etc/networkd-dispatcher/dormant.d/90-blah.sh", "/etc/networkd-dispatcher/dormant.d/92-mount-netdrive.sh", ], 'no-carrier.d': [ "/usr/lib/networkd-dispatcher/no-carrier.d/10-script-important.sh", "/usr/lib/networkd-dispatcher/no-carrier.d/50-script", "/etc/networkd-dispatcher/no-carrier.d/display-notification", ], 'off.d': [ "/etc/networkd-dispatcher/off.d/00-stop-net-services.sh", "/usr/lib/networkd-dispatcher/off.d/20-stop-vpn.sh", ], 'routable.d': [ "/etc/networkd-dispatcher/routable.d/19-whatever.sh", "/usr/lib/networkd-dispatcher/routable.d/40-enable-ntp.sh", "/etc/networkd-dispatcher/routable.d/50-start-netdrive", "/etc/networkd-dispatcher/routable.d/99-not-important.sh", "/etc/networkd-dispatcher/routable.d/enable-tracking-service.sh", ], 'carrier.d': [ "/etc/networkd-dispatcher/carrier.d/01-set-ip.sh", "/usr/lib/networkd-dispatcher/carrier.d/99-so-stuff.sh", ], 'degraded.d': [ "/etc/networkd-dispatcher/degraded.d/39-catch-fire.sh", ], } @pytest.fixture() def get_networkctl_status_out(): """ Returns some expected output from networkd-dispatcher.get_networkctl_status """ return {'Link File': ['/etc/systemd/network/10-wifi.link'], 'Network File': ['/etc/systemd/network/20-wifi.network'], 'Type': 'wlan', 'State': ['routable (configured)'], 'Path': ['pci-0000:3a:00.0'], 'Driver': ['iwlwifi'], 'Vendor': ['Intel Corporation'], 'Model': ['Wireless 8265 / 8275 (Dual Band Wireless-AC 8265)'], 'HW Address': ['dd:ee:aa:dd:12:34 (Intel Corporate)'], 'Address': ['1.1.1.100'], 'Gateway': ['1.1.1.1'], 'DNS': ['10.10.10.1']} @pytest.fixture() def get_interface_data_out(): return {'Type': 'wlan', 'OperationalState': 'routable', 'AdministrativeState': 'configured', 'Link File': ['/etc/systemd/network/10-wifi.link'], 'Network File': ['/etc/systemd/network/20-wifi.network'], 'State': 'routable (configured)', 'Path': ['pci-0000:3a:00.0'], 'Driver': ['iwlwifi'], 'Vendor': ['Intel Corporation'], 'Model': ['Wireless 8265 / 8275 (Dual Band Wireless-AC 8265)'], 'HW Address': ['dd:ee:aa:dd:12:34 (Intel Corporate)'], 'ESSID': 'whatever'} @pytest.fixture() def get_networkctl_list_out(): """Returns some expected output from networkd_dispatcher.get_networkctl_list """ return [ networkd_dispatcher.NetworkctlListState(idx=1, name='lo', type='loopback', operational='carrier', administrative='unmanaged'), networkd_dispatcher.NetworkctlListState(idx=2, name='wlan0', type='wlan', operational='routable', administrative='configured'), networkd_dispatcher.NetworkctlListState(idx=3, name='eth0', type='eth', operational='dormant', administrative='configured') ] @pytest.fixture() def Dispatcher_ifaces_by_name(): return { 'lo': networkd_dispatcher.NetworkctlListState(idx=1, name='lo', type='loopback', operational='carrier', administrative='unmanaged'), 'wlan0': networkd_dispatcher.NetworkctlListState(idx=2, name='wlan0', type='wlan', operational='routable', administrative='configured'), 'eth0': networkd_dispatcher.NetworkctlListState(idx=3, name='eth0', type='eth', operational='dormant', administrative='configured') } @pytest.fixture() def Dispatcher_iface_names_by_idx(): return {1: 'lo', 2: 'wlan0', 3: 'eth0'} networkd-dispatcher-2.0.1/tests/inputs/000077500000000000000000000000001342436400200201555ustar00rootroot00000000000000networkd-dispatcher-2.0.1/tests/inputs/iw000066400000000000000000000004031342436400200205140ustar00rootroot00000000000000Connected to ff:aa:3e:09:78:bc (on wlan0) SSID: ssid123 freq: 5320 RX: 114686 bytes (387 packets) TX: 89047 bytes (408 packets) signal: -71 dBm tx bitrate: 999.0 MBit/s MCS 12 40MHz short GI bss flags: short-slot-time dtim period: 1 beacon int: 100 networkd-dispatcher-2.0.1/tests/inputs/iwconfig000066400000000000000000000007051342436400200217070ustar00rootroot00000000000000wlan0 IEEE 802.11 ESSID:"OMG_ssid" Mode:Managed Frequency:5.32 GHz Access Point: F8:99:99:E1:81:5C Bit Rate=300 Mb/s Tx-Power=22 dBm Retry short limit:7 RTS thr:off Fragment thr:off Power Management:off Link Quality=42/70 Signal level=-68 dBm Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0 Tx excessive retries:0 Invalid misc:32 Missed beacon:0 networkd-dispatcher-2.0.1/tests/inputs/networkctl_list000066400000000000000000000002741342436400200233320ustar00rootroot00000000000000 1 lo loopback carrier unmanaged 2 wlan0 wlan routable configured 3 eth0 eth dormant configured networkd-dispatcher-2.0.1/tests/inputs/networkctl_status000066400000000000000000000007451342436400200237050ustar00rootroot00000000000000● 2: wlan0 Link File: /etc/systemd/network/10-wifi.link Network File: /etc/systemd/network/20-wifi.network Type: wlan State: routable (configured) Path: pci-0000:3a:00.0 Driver: iwlwifi Vendor: Intel Corporation Model: Wireless 8265 / 8275 (Dual Band Wireless-AC 8265) HW Address: dd:ee:aa:dd:12:34 (Intel Corporate) Address: 1.1.1.100 Gateway: 1.1.1.1 DNS: 10.10.10.1 networkd-dispatcher-2.0.1/tests/inputs/parse_address_strings000066400000000000000000000001761342436400200244740ustar00rootroot00000000000000123.321.132.312 127.0.0.1 1.0.1.1 fe80::b2c0:90ff:fe60:861d feed::82c9:7bbf:ae39:8ff0 192.168.1.254 deeb::7bb8:f2c9:8ff0:ae39 networkd-dispatcher-2.0.1/tests/inputs/test_get_interface_data000066400000000000000000000007451342436400200247350ustar00rootroot00000000000000● 2: wlan0 Link File: /etc/systemd/network/10-wifi.link Network File: /etc/systemd/network/20-wifi.network Type: wlan State: routable (configured) Path: pci-0000:3a:00.0 Driver: iwlwifi Vendor: Intel Corporation Model: Wireless 8265 / 8275 (Dual Band Wireless-AC 8265) HW Address: dd:ee:aa:dd:12:34 (Intel Corporate) Address: 1.1.1.100 Gateway: 1.1.1.1 DNS: 10.10.10.1 networkd-dispatcher-2.0.1/tests/inputs/test_get_networkctl_list000066400000000000000000000002741342436400200252300ustar00rootroot00000000000000 1 lo loopback carrier unmanaged 2 wlan0 wlan routable configured 3 eth0 eth dormant configured networkd-dispatcher-2.0.1/tests/inputs/test_get_networkctl_status000066400000000000000000000007451342436400200256030ustar00rootroot00000000000000● 2: wlan0 Link File: /etc/systemd/network/10-wifi.link Network File: /etc/systemd/network/20-wifi.network Type: wlan State: routable (configured) Path: pci-0000:3a:00.0 Driver: iwlwifi Vendor: Intel Corporation Model: Wireless 8265 / 8275 (Dual Band Wireless-AC 8265) HW Address: dd:ee:aa:dd:12:34 (Intel Corporate) Address: 1.1.1.100 Gateway: 1.1.1.1 DNS: 10.10.10.1 networkd-dispatcher-2.0.1/tests/inputs/test_get_wlan_ssid_iw000066400000000000000000000004031342436400200244550ustar00rootroot00000000000000Connected to ff:aa:3e:09:78:bc (on wlan0) SSID: ssid123 freq: 5320 RX: 114686 bytes (387 packets) TX: 89047 bytes (408 packets) signal: -71 dBm tx bitrate: 999.0 MBit/s MCS 12 40MHz short GI bss flags: short-slot-time dtim period: 1 beacon int: 100 networkd-dispatcher-2.0.1/tests/inputs/test_get_wlan_ssid_iwconfig000066400000000000000000000007051342436400200256500ustar00rootroot00000000000000wlan0 IEEE 802.11 ESSID:"OMG_ssid" Mode:Managed Frequency:5.32 GHz Access Point: F8:99:99:E1:81:5C Bit Rate=300 Mb/s Tx-Power=22 dBm Retry short limit:7 RTS thr:off Fragment thr:off Power Management:off Link Quality=42/70 Signal level=-68 dBm Rx invalid nwid:0 Rx invalid crypt:0 Rx invalid frag:0 Tx excessive retries:0 Invalid misc:32 Missed beacon:0 networkd-dispatcher-2.0.1/tests/run.sh000077500000000000000000000005441342436400200200010ustar00rootroot00000000000000#!/bin/bash function error() { echo "ERROR: $1" exit 1 } # Required binaries/apps reqs=('pytest') for req in ${reqs[*]}; do [[ -z "$(command -v $req)" ]] && error "$req not found" done # Check for pytest-cov module python3 -c "import pytest_cov" 2>/dev/null || error "pytest-cov module not found" python3 -m pytest --cov=networkd_dispatcher -q tests networkd-dispatcher-2.0.1/tests/test_networkd-dispatcher.py000066400000000000000000001005571342436400200242350ustar00rootroot00000000000000import collections from collections import namedtuple import dbus import errno import logging import mock import os import socket import subprocess import sys import pytest from mock import patch myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../') import networkd_dispatcher from networkd_dispatcher import (Dispatcher, NetworkctlListState, LOG_FORMAT) try: from gi.repository import GLib as glib except ImportError: import glib def get_datafile(datafile): assert datafile is not None in_file = os.path.join('tests', 'inputs', datafile) assert os.path.exists(in_file) with open(in_file, 'rb') as fh: in_txt = fh.read() assert in_txt is not None return in_txt def test_resolve_path(monkeypatch): monkeypatch.setattr(os, 'environ', {'PATH': '/bin:/usr/bin:/sbin:/usr/sbin'}) # exists monkeypatch.setattr(os.path, 'exists', lambda x: (True if x == '/sbin/vpn' else False)) assert networkd_dispatcher.resolve_path('vpn') == '/sbin/vpn' # doesn't exist monkeypatch.setattr(os.path, 'exists', lambda x: False) assert networkd_dispatcher.resolve_path('vpn') is None @patch('subprocess.check_output') def test_get_networkctl_status(mock_subprocess, monkeypatch, get_networkctl_status_out, caplog): # CalledProcessError caplog.clear() mock_subprocess.side_effect = ( subprocess.CalledProcessError(-1, '/usr/bin/networkctl')) assert (networkd_dispatcher.get_networkctl_status('wlan0') == collections.defaultdict(list)) _, _, err = caplog.record_tuples[0] # Python Issue #27167 ('fixed' in 3.6) changes output of CalledProcessError if int(''.join(sys.version.split()[0].split('.')[0:2])) < 36: assert err == ('Failed to get interface "wlan0" status: Command ' '\'/usr/bin/networkctl\' returned non-zero exit ' 'status -1') else: assert err == ('Failed to get interface "wlan0" status: Command ' '\'/usr/bin/networkctl\' died with .') # check output mock_subprocess.side_effect = None mock_subprocess.return_value = get_datafile('networkctl_status') assert (networkd_dispatcher.get_networkctl_status('wlan0') == get_networkctl_status_out) def test_unquote(): str = '\\ssid\\awesome' assert networkd_dispatcher.unquote(str) == 'ssidawesome' @patch('subprocess.check_output') def test_get_networkctl_list(mock_subprocess, monkeypatch, get_networkctl_list_out, caplog): mock_subprocess.return_value = get_datafile('networkctl_list') assert networkd_dispatcher.get_networkctl_list() == get_networkctl_list_out # CalledProcessError caplog.clear() mock_subprocess.side_effect = ( subprocess.CalledProcessError(-1, '/usr/bin/networkctl')) assert networkd_dispatcher.get_networkctl_list() == [] _, _, err = caplog.record_tuples[0] # Python Issue #27167 ('fixed' in 3.6) changes output of CalledProcessError if int(''.join(sys.version.split()[0].split('.')[0:2])) < 36: assert err == ('networkctl list failed: Command \'/usr/bin/' 'networkctl\' returned non-zero exit status -1') else: assert err == ('networkctl list failed: Command \'/usr/bin/' 'networkctl\' died with .') @patch('networkd_dispatcher.iwconfig_get_ssid') @patch('networkd_dispatcher.iw_get_ssid') def test_get_wlan_ssid(mock_iw_get_ssid, mock_iwconfig_get_ssid, monkeypatch, caplog): iface = 'wlp0s1' monkeypatch.setattr('networkd_dispatcher.IWCONFIG', None) monkeypatch.setattr('networkd_dispatcher.IW', None) assert networkd_dispatcher.get_wlan_essid(iface) == '' _, _, err = caplog.record_tuples[0] assert err == ("Unable to retrieve ESSID for wireless " "interface " + iface + ": no supported wireless tool " "installed") # iw exists monkeypatch.setattr('networkd_dispatcher.IWCONFIG', None) monkeypatch.setattr('networkd_dispatcher.IW', '/usr/bin/iw') networkd_dispatcher.get_wlan_essid(iface) mock_iw_get_ssid.assert_called_with(iface) # iwconfig exists monkeypatch.setattr('networkd_dispatcher.IW', None) monkeypatch.setattr('networkd_dispatcher.IWCONFIG', '/usr/bin/iwconfig') networkd_dispatcher.get_wlan_essid(iface) mock_iwconfig_get_ssid.assert_called_with(iface) def test_iwconfig_get_ssid(monkeypatch): expected = 'OMG_ssid' monkeypatch.setattr('networkd_dispatcher.IW', None) monkeypatch.setattr('networkd_dispatcher.IWCONFIG', '/usr/bin/iwconfig') monkeypatch.setattr(subprocess, 'check_output', lambda cmd: get_datafile('iwconfig')) assert networkd_dispatcher.get_wlan_essid('wlan0') == expected def test_iw_get_ssid(monkeypatch, caplog): expected = 'ssid123' monkeypatch.setattr('networkd_dispatcher.IW', '/usr/bin/iw') monkeypatch.setattr('networkd_dispatcher.IWCONFIG', None) monkeypatch.setattr(subprocess, 'check_output', lambda cmd: get_datafile('iw')) assert networkd_dispatcher.get_wlan_essid('wlan0') == expected # Invalid data from iw expected = '' monkeypatch.setattr(subprocess, 'check_output', lambda cmd: b'') caplog.set_level(logging.WARNING) assert networkd_dispatcher.get_wlan_essid('wlan0') == expected _, _, warn = caplog.record_tuples[0] assert warn == 'Unable to retrieve ESSID for wireless interface wlan0.' def test_scripts_in_path(monkeypatch, scripts_etc, scripts_usr, scripts_etc_filenames, scripts_usr_filenames, scripts_sorted, caplog): path = '/etc/networkd-dispatcher:/usr/lib/networkd-dispatcher' for subdir in ['dormant.d', 'no-carrier.d', 'off.d', 'routable.d']: monkeypatch.setattr(os, 'listdir', lambda p: scripts_usr_filenames[subdir] if p.startswith('/usr') else scripts_etc_filenames[subdir]) stat = namedtuple('stat', ('st_mode st_uid st_gid st_size st_mtime ' 'st_atime st_ctime')) # file exists monkeypatch.setattr(os, 'stat', lambda x: stat(st_mode=33261, st_uid=0, st_gid=0, st_size=99, st_atime=1540220480, st_mtime=1539272713, st_ctime=1539272713)) # make sure isfile returns true for files in fixtures monkeypatch.setattr(os.path, 'isfile', lambda x: True if x in scripts_usr[subdir] or x in scripts_etc[subdir] else False) scripts_returned = networkd_dispatcher.scripts_in_path(path, subdir) assert scripts_returned == scripts_sorted[subdir] # path does not exist caplog.clear() caplog.set_level(logging.DEBUG) monkeypatch.setattr(os.path, 'exists', lambda x: False) scripts_returned = networkd_dispatcher.scripts_in_path(path, subdir) assert scripts_returned == [] _, _, debug = caplog.record_tuples[0] assert debug.endswith('does not exist; skipping') # file not executable caplog.clear() caplog.set_level(logging.ERROR) monkeypatch.setattr(os.path, 'exists', lambda x: True) monkeypatch.setattr(os, 'stat', lambda x: stat(st_mode=33152, st_uid=0, st_gid=0, st_size=99, st_atime=1540220480, st_mtime=1539272713, st_ctime=1539272713)) scripts_returned = networkd_dispatcher.scripts_in_path(path, subdir) assert scripts_returned == [] _, _, err = caplog.record_tuples[0] assert err.startswith('Unable to execute script, check file mode: ') # file not owned by root caplog.clear() caplog.set_level(logging.ERROR) monkeypatch.setattr(os.path, 'exists', lambda x: True) monkeypatch.setattr(os, 'stat', lambda x: stat(st_mode=33261, st_uid=1000, st_gid=1000, st_size=99, st_atime=1540220480, st_mtime=1539272713, st_ctime=1539272713)) scripts_returned = networkd_dispatcher.scripts_in_path(path, subdir) assert scripts_returned == [] _, _, err = caplog.record_tuples[0] assert err.startswith('Unable to execute script, check file perms: ') def test_parse_address_strings(): addrs = ['123.321.132.312', '127.0.0.1', '1.0.1.1', 'fe80::b2c0:90ff:fe60:861d', 'feed::82c9:7bbf:ae39:8ff0', '192.168.1.254', 'deeb::7bb8:f2c9:8ff0:ae39'] ipv4addrs, ipv6addrs = networkd_dispatcher.parse_address_strings(addrs) assert ipv4addrs is not None or ipv6addrs is not None for addr in ipv4addrs: assert not addr.startswith('127.') assert ':' not in addr assert '.' in addr for addr in ipv6addrs: assert not addr.startswith('fe80:') assert '.' not in addr assert ':' in addr def test_get_interface_data(monkeypatch, get_networkctl_status_out, get_interface_data_out): iface = NetworkctlListState(idx='1', name='wlan0', type='wlan', operational='routable', administrative='configured') monkeypatch.setattr('networkd_dispatcher.get_networkctl_status', lambda x: get_networkctl_status_out) monkeypatch.setattr(subprocess, 'check_output', lambda cmd: get_datafile('iwconfig')) out = networkd_dispatcher.get_interface_data(iface) assert out != get_interface_data_out @patch('socket.socket') def test_sd_notify(mock_socket, monkeypatch, caplog): # no state specified assert networkd_dispatcher.sd_notify() == -errno.EINVAL # not invoked with systemd monkeypatch.setattr('os.environ.get', lambda x, y: '') assert networkd_dispatcher.sd_notify(READY=1) == -errno.EINVAL # invalid NOTIFY_SOCKET monkeypatch.setattr('os.environ.get', lambda x, y: 'whatever') assert networkd_dispatcher.sd_notify(READY=1) == -errno.EINVAL # invoked with systemd and valid state (NOTIFY_SOCKET starts with /) monkeypatch.setattr('os.environ.get', lambda x, y: '/var/run/dbus/system_bus_socket') mock_socket.return_value = socket.socket mock_socket.sendto.return_value = 0 assert networkd_dispatcher.sd_notify(READY=1) == 0 mock_socket.assert_called_with(socket.AF_UNIX, socket.SOCK_DGRAM) mock_socket.sendto.assert_called_with(bytearray(b'READY=1'), '/var/run/dbus/system_bus_socket') mock_socket.close.assert_called_with() # invoked with systemd and valid state (NOTIFY_SOCKET starts with @) monkeypatch.setattr('os.environ.get', lambda x, y: '@systemd-networkd') assert networkd_dispatcher.sd_notify(READY=1) == 0 mock_socket.assert_called_with(socket.AF_UNIX, socket.SOCK_DGRAM) mock_socket.sendto.assert_called_with(bytearray(b'READY=1'), '\x00systemd-networkd') mock_socket.close.assert_called_with() # socket.sendto error monkeypatch.setattr('os.environ.get', lambda x, y: '@systemd-networkd') mock_socket.sendto.return_value = 1 assert networkd_dispatcher.sd_notify(READY=1) == 1 # Exceptions mock_socket.side_effect = Exception() monkeypatch.setattr('os.environ.get', lambda x, y: '@systemd-networkd') caplog.clear() networkd_dispatcher.sd_notify(READY=1) _, _, ex = caplog.record_tuples[0] assert ex == 'Ignoring unexpected error during sd_notify() invocation' # In order to test Dispatcher, the call to _interface_scan should be mocked # since this runs in __init__ with patch.object(networkd_dispatcher.Dispatcher, "_interface_scan", lambda x: None): class TestDispatcher(): dp = Dispatcher() def test__interface_scan(self, monkeypatch, get_networkctl_list_out, Dispatcher_ifaces_by_name, Dispatcher_iface_names_by_idx, caplog): monkeypatch.setattr('networkd_dispatcher.get_networkctl_list', lambda: get_networkctl_list_out) caplog.set_level(logging.DEBUG) self.dp._interface_scan() assert self.dp.ifaces_by_name == Dispatcher_ifaces_by_name assert self.dp.iface_names_by_idx == Dispatcher_iface_names_by_idx _, _, debug = caplog.record_tuples[0] assert debug == ('Performed interface scan; state: ') @patch('dbus.SystemBus') @patch('dbus.bus.BusConnection') def test_register(self, mock_dbus_bus, mock_dbus_SystemBus): mock_dbus_SystemBus.return_value = mock.MagicMock() self.dp.register(bus=None) mock_dbus_SystemBus.assert_called_with() @patch('networkd_dispatcher.Dispatcher.handle_state') def test_trigger_all(self, mock_hs, monkeypatch, caplog): iface = NetworkctlListState(idx='1', name='wlan0', type='wlan', operational='routable', administrative='configured') monkeypatch.setattr(('networkd_dispatcher.Dispatcher' '.ifaces_by_name'), {'wlan0': iface}) mock_hs.return_value = None self.dp.trigger_all() mock_hs.assert_called_with('wlan0', administrative_state='configured', operational_state='routable', force=True) # invalid iface monkeypatch.setattr(('networkd_dispatcher.Dispatcher' '.ifaces_by_name'), {'eth0': 1}) caplog.clear() self.dp.trigger_all() _, _, ex = caplog.record_tuples[0] assert ex == 'Error handling initial for interface 1' @patch('networkd_dispatcher.Dispatcher.run_hooks_for_state') def test__handle_one_state(self, mock_run_hooks_for_state, monkeypatch, caplog): monkeypatch.setattr(('networkd_dispatcher.Dispatcher' '.ifaces_by_name'), {}) # None state assert self.dp._handle_one_state(self, None, None, None) is None # None for prior iface assert (self.dp._handle_one_state('wlan0', 'routable', None, None) is None) _, _, err = caplog.record_tuples[0] assert err == ('Attempting to handle state for unknown interface ' '\'wlan0\'') # No state change caplog.clear() caplog.set_level(logging.DEBUG) iface = NetworkctlListState(idx='1', name='wlan0', type='wlan', operational='routable', administrative='configured') monkeypatch.setattr(('networkd_dispatcher.Dispatcher' '.ifaces_by_name'), {'wlan0': iface}) assert (self.dp._handle_one_state('wlan0', 'routable', 'operational', force=False) is None) _, _, debug = caplog.record_tuples[0] assert debug == (('No change represented by operational state ' '\'routable\' for interface \'wlan0\'')) # Force update caplog.clear() mock_run_hooks_for_state.return_value = True assert (self.dp._handle_one_state('wlan0', 'routable', 'operational', force=True) is None) mock_run_hooks_for_state.assert_called_with(iface, 'routable') assert len(caplog.record_tuples) == 0 # New iface state caplog.clear() mock_run_hooks_for_state.return_value = True assert (self.dp._handle_one_state('wlan0', 'dormant', 'operational') is None) new_iface = NetworkctlListState(idx='1', name='wlan0', type='wlan', operational='dormant', administrative='configured') mock_run_hooks_for_state.assert_called_with(new_iface, 'dormant') assert (self.dp.ifaces_by_name[new_iface.name].operational == 'dormant') # Exceptions caplog.clear() mock_run_hooks_for_state.side_effect = Exception() assert (self.dp._handle_one_state('wlan0', 'routable', 'operational') is None) _, _, ex = caplog.record_tuples[0] assert ex == ('Error handling notification for interface ' '\'wlan0\' entering operational state routable') @patch('networkd_dispatcher.Dispatcher._handle_one_state') def test_handle_state(self, mock__handle_one_state, monkeypatch, caplog): self.dp.handle_state('wlan0', 'configured', 'routable', False) calls = [mock.call('wlan0', 'configured', 'administrative', force=False), mock.call('wlan0', 'routable', 'operational', force=False)] mock__handle_one_state.assert_has_calls(calls, any_order=False) @patch.object(networkd_dispatcher, 'scripts_in_path') def test_get_scripts_list(self, mock_scripts_in_path): for basedir in ['/etc/networkd-dispatcher', '/usr/lib/networkd-dispatcher']: for subdir in ['dormant', 'no-carrier', 'off', 'routable']: expected = basedir + '/' + subdir + '.d/10-blah.sh' mock_scripts_in_path.return_value = expected assert (self.dp.get_scripts_list(state=subdir) == expected) @patch('subprocess.Popen') def test_run_hooks_for_state(self, mock_subprocess, monkeypatch, get_interface_data_out, caplog): e_env = {'ADDR': '', 'ESSID': 'whatever', 'IP_ADDRS': '123.321.132.312 1.0.1.1 192.168.1.254', 'IP6_ADDRS': ('feed::82c9:7bbf:ae39:8ff0 ' 'deeb::7bb8:f2c9:8ff0:ae39'), 'IFACE': 'wlan0', 'STATE': 'routable', 'AdministrativeState': 'configured', 'OperationalState': 'routable', 'json': ('{"AdministrativeState": "configured", ' '"Driver": ["iwlwifi"], "ESSID": "whatever", ' '"HW Address": ["dd:ee:aa:dd:12:34 (Intel ' 'Corporate)"], "Link File": ' '["/etc/systemd/network/10-wifi.link"], ' '"Model": ["Wireless 8265 / 8275 (Dual Band ' 'Wireless-AC 8265)"], "Network File": ' '["/etc/systemd/network/20-wifi.network"], ' '"OperationalState": "routable", "Path": ' '["pci-0000:3a:00.0"], "State": "routable ' '(configured)", "Type": "wlan", "Vendor": ' '["Intel Corporation"]}')} ipv4 = ['123.321.132.312', '1.0.1.1', '192.168.1.254'] ipv6 = ['feed::82c9:7bbf:ae39:8ff0', 'deeb::7bb8:f2c9:8ff0:ae39'] addrs = networkd_dispatcher.AddressList(ipv4, ipv6) monkeypatch.setattr('networkd_dispatcher.get_interface_data', lambda x: get_interface_data_out) monkeypatch.setattr('networkd_dispatcher.Dispatcher.' 'get_scripts_list', lambda x, y: (['/etc/networkd-dispatcher/' 'routable.d/10openvpn'])) monkeypatch.setattr('networkd_dispatcher.parse_address_strings', lambda x: addrs) old_environ = os.environ os.environ.clear() self.dp.run_hooks_for_state(self.dp.ifaces_by_name['wlan0'], 'routable') mock_subprocess.assert_called_with(('/etc/networkd-dispatcher/' 'routable.d/10openvpn'), env=e_env) # bad exit status from script mock_subprocess.wait.return_value = -1 os.environ = old_environ caplog.clear() self.dp.run_hooks_for_state(self.dp.ifaces_by_name['wlan0'], 'routable') caplog.set_level(logging.WARNING) _, _, warn = caplog.record_tuples[0] assert not warn.startswith('Exist status') # no scripts monkeypatch.setattr(Dispatcher, 'get_scripts_list', lambda x, y: None) caplog.clear() caplog.set_level(logging.DEBUG) assert self.dp.run_hooks_for_state(self.dp.ifaces_by_name['wlan0'], 'routable') is None _, _, debug = caplog.record_tuples[0] assert debug == ('Ignoring notification for interface ' 'NetworkctlListState(idx=2, name=\'wlan0\', ' 'type=\'wlan\', operational=\'routable\', ' 'administrative=\'configured\') entering state ' '\'routable\': no triggers') @patch.object(networkd_dispatcher.Dispatcher, 'handle_state') @patch.object(networkd_dispatcher.Dispatcher, '_interface_scan') def test__receive_signal(self, mock_interface_scan, mock_handle_state, caplog): self.dp.ifaces_by_name = {'lo': NetworkctlListState(idx=1, name='lo', type='loopback', operational='carrier', administrative='unmanaged'), 'eth0': NetworkctlListState(idx=3, name='eth0', type='eth', operational='dormant', administrative='configured')} # invalid typ caplog.clear() caplog.set_level(logging.DEBUG) assert (self.dp._receive_signal('org.freedesktop.' 'whatever', '', '', '') is None) _, _, debug = caplog.record_tuples[1] assert 'Ignoring signal received with unexpected typ' in debug # invalid path caplog.clear() caplog.set_level(logging.DEBUG) assert (self.dp._receive_signal('org.freedesktop.' 'network1.Link', '', None, '/org/freedesktop/whatever') is None) _, _, debug = caplog.record_tuples[1] assert 'Ignoring signal received with unexpected path' in debug # unknown iface idx seen caplog.clear() caplog.set_level(logging.DEBUG) self.dp.iface_names_by_idx = {} mock_interface_scan.return_value = {1: 'lo', 2: 'eth0', 3: 'wlan0'} assert (self.dp._receive_signal('org.freedesktop.' 'network1.Link', '', None, '/org/freedesktop/network1/' 'link/_33') is None) _, _, warn = caplog.record_tuples[1] assert warn == 'Unknown index 3 seen, reloading interface list' mock_interface_scan.assert_called_with() # unknown iface idx even after reload caplog.clear() mock_interface_scan.return_value = {1: 'lo', 2: 'eth0'} assert (self.dp._receive_signal('org.freedesktop.' 'network1.Link', '', None, '/org/freedesktop/network1/' 'link/_33') is None) _, _, warn = caplog.record_tuples[2] mock_interface_scan.assert_called_with() assert warn == 'Unknown interface index 3 seen even after reload' # handle_state called with right things self.dp.iface_names_by_idx = {1: 'lo', 2: 'eth0', 3: 'wlan0'} data = dbus.Dictionary( {dbus.String('OperationalState'): dbus.String('routable', variant_level=1)}, signature=dbus.Signature('sv')) assert (self.dp._receive_signal('org.freedesktop.' 'network1.Link', data, None, '/org/freedesktop/network1/' 'link/_33') is None) mock_handle_state.assert_called_with('wlan0', administrative_state=None, operational_state='routable') # remove ifaces (ifaces_by_name and iface_names_by_idx pop'd) self.dp.iface_names_by_idx = {1: 'lo', 2: 'eth0', 3: 'wlan0'} data = dbus.Dictionary( {dbus.String('AdministrativeState'): dbus.String('linger', variant_level=1)}, signature=dbus.Signature('sv')) assert (self.dp._receive_signal('org.freedesktop.' 'network1.Link', data, None, '/org/freedesktop/network1/' 'link/_33') is None) mock_handle_state.assert_called_with('wlan0', administrative_state='linger', operational_state=None) _, _, warn = caplog.record_tuples[1] assert warn == 'Unknown index 3 seen, reloading interface list' assert 3 not in self.dp.iface_names_by_idx.keys() assert 'wlan0' not in self.dp.ifaces_by_name.keys() # keyerror when removing iface caplog.clear() self.dp.iface_names_by_idx = {1: 'lo', 2: 'eth0', 3: 'wlan0'} data = dbus.Dictionary( {dbus.String('AdministrativeState'): dbus.String('linger', variant_level=1)}, signature=dbus.Signature('sv')) self.dp.ifaces_by_name = {} assert (self.dp._receive_signal('org.freedesktop.' 'network1.Link', data, None, '/org/freedesktop/network1/' 'link/_33') is None) mock_handle_state.assert_called_with('wlan0', administrative_state='linger', operational_state=None) _, _, err = caplog.record_tuples[1] assert err == 'Unable to remove interface at index 3.' @patch('networkd_dispatcher.main') def test___main__(mock_main, monkeypatch): monkeypatch.setattr(networkd_dispatcher, '__name__', '__main__') networkd_dispatcher.init() mock_main.assert_called_with() def test_parse_args(monkeypatch): # script_dir parser = networkd_dispatcher.parse_args(['-S', '/etc/custom']) assert parser.script_dir == '/etc/custom' # trigger-all parser = networkd_dispatcher.parse_args(['-T']) assert parser.run_startup_triggers # verbosity parser = networkd_dispatcher.parse_args(['-vvvv']) assert parser.verbose == 4 # quiet parser = networkd_dispatcher.parse_args(['-qqqqq']) assert parser.quiet == 5 @patch.object(networkd_dispatcher, 'sd_notify') @patch.object(glib, 'MainLoop') @patch.object(logging, 'basicConfig') @patch.object(Dispatcher, 'trigger_all') @patch.object(Dispatcher, 'register') @patch.object(Dispatcher, '_interface_scan') def test_main(mock_iface_scan, mock_register, mock_trigger_all, mock_logging_basicconfig, mock_glib_mainloop, mock_sd_notify, monkeypatch, caplog): # networkctl is None monkeypatch.setattr(sys, 'argv', ['networkd-dispatcher']) monkeypatch.setattr(networkd_dispatcher, 'NETWORKCTL', None) with pytest.raises(SystemExit) as e: networkd_dispatcher.main() assert e.type == SystemExit mock_sd_notify.assert_called_with(ERRNO=errno.ENOENT) _, _, crit = caplog.record_tuples[1] assert crit == 'Unable to find networkctl command; cannot continue' monkeypatch.setattr(networkd_dispatcher, 'NETWORKCTL', '/usr/bin/networkctl') # test verbosity config monkeypatch.setattr(sys, 'argv', ['networkd-dispatcher', '-v']) networkd_dispatcher.main() mock_logging_basicconfig.assert_called_with(level=logging.INFO, format=LOG_FORMAT) monkeypatch.setattr(sys, 'argv', ['networkd-dispatcher', '-vv']) networkd_dispatcher.main() mock_logging_basicconfig.assert_called_with(level=logging.DEBUG, format=LOG_FORMAT) monkeypatch.setattr(sys, 'argv', ['networkd-dispatcher', '-qqv']) networkd_dispatcher.main() mock_logging_basicconfig.assert_called_with(level=logging.ERROR, format=LOG_FORMAT) monkeypatch.setattr(sys, 'argv', ['networkd-dispatcher', '-vvqqqq']) networkd_dispatcher.main() mock_logging_basicconfig.assert_called_with(level=logging.CRITICAL, format=LOG_FORMAT) monkeypatch.setattr(sys, 'argv', ['networkd-dispatcher', '-vvqq']) networkd_dispatcher.main() mock_logging_basicconfig.assert_called_with(level=logging.WARNING, format=LOG_FORMAT) # run_startup_triggers monkeypatch.setattr(sys, 'argv', ['networkd-dispatcher', '-T']) networkd_dispatcher.main() mock_sd_notify.assert_called_with(READY=1) mock_trigger_all.assert_called_with() networkd-dispatcher-2.0.1/tox.ini000066400000000000000000000010001342436400200167730ustar00rootroot00000000000000# tox (https://tox.readthedocs.io/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported python versions. To use it, "pip install tox" # and then run "tox" from this directory. [tox] envlist = py34, py35, py36, py37 skipsdist=True [testenv] deps = coverage dbus-python pytest PyGObject pytest-cov mock commands = python3 -m pytest --cov=networkd_dispatcher --cov-report term-missing --cov-fail-under 100 -q tests