commit 2181927a60e5f99d76a6c6782453387ac9a896c6 Author: Cantibra Date: Mon May 4 21:22:11 2026 +0200 Initialize Git Repository: 'WSDD' diff --git a/.env b/.env new file mode 100644 index 0000000..4a139fc --- /dev/null +++ b/.env @@ -0,0 +1 @@ +VERSION='0.9' \ No newline at end of file diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..9dd6030 --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,81 @@ +name: WSDD +on: + push: + branches: + - release +jobs: + workflow: + name: WSDD + strategy: + matrix: + include: + - architecture: amd64 + cicd: cicd.any + codename: bookworm trixie noble + component: main + - architecture: arm64 + cicd: cicd.any + codename: bookworm trixie noble + component: main + runs-on: ${{ matrix.cicd }} + steps: + - name: Repository [Clone] + uses: actions/checkout@v6 + - name: Environment + id: environment + run: | + source './.env' + /usr/bin/echo "VERSION=${VERSION}" >> "${GITHUB_OUTPUT}" + /usr/bin/echo "Set Variable 'VERSION' to '${VERSION}'" + - name: Debian Package [Prepare] + env: + ARCHITECTURE: ${{ matrix.architecture }} + VERSION: ${{ steps.environment.outputs.version }} + run: | + /usr/bin/sed --in-place --expression="s/Architecture:.*/Architecture: ${ARCHITECTURE}/" './wsdd/DEBIAN/control' + /usr/bin/sed --in-place --expression="s/Version:.*/Version: ${VERSION}/" './wsdd/DEBIAN/control' + /usr/bin/chmod --verbose '0755' './wsdd/DEBIAN/postinst' + /usr/bin/chmod --verbose '0755' './wsdd/DEBIAN/postrm' + /usr/bin/chmod --verbose '0755' './wsdd/DEBIAN/preinst' + /usr/bin/chmod --verbose '0755' './wsdd/DEBIAN/prerm' + /usr/bin/chmod --verbose '0755' './wsdd/etc/init.d/wsdd' + /usr/bin/chmod --verbose '0755' './wsdd/usr/sbin/wsdd' + /usr/bin/gzip --best --verbose './wsdd/usr/share/man/man8/wsdd.8' + - name: Debian Package [Build] + env: + ARCHITECTURE: ${{ matrix.architecture }} + VERSION: ${{ steps.environment.outputs.version }} + run: | + /usr/bin/dpkg-gen './wsdd' + /usr/bin/mv --verbose './wsdd.deb' "./wsdd_${VERSION}_${ARCHITECTURE}.deb" + - name: Debian Repository [Prepare] + env: + ARCHITECTURE: ${{ matrix.architecture }} + CODENAME: ${{ matrix.codename }} + COMPONENT: ${{ matrix.component }} + REPOSITORY_SSH_PRIVATE_KEY: ${{ secrets.REPOSITORY_SSH_PRIVATE_KEY }} + VERSION: ${{ steps.environment.outputs.version }} + run: | + /usr/bin/echo "${REPOSITORY_SSH_PRIVATE_KEY}" > './id_ed25519' + /usr/bin/chmod --quiet '0400' './id_ed25519' + /usr/bin/echo "REPOSITORY_CODENAME='${CODENAME}'" > "./wsdd_${VERSION}_${ARCHITECTURE}.cfg" + /usr/bin/echo "Set Configuration 'REPOSITORY_CODENAME' to '${CODENAME}'" + /usr/bin/echo "REPOSITORY_COMPONENT='${COMPONENT}'" >> "./wsdd_${VERSION}_${ARCHITECTURE}.cfg" + /usr/bin/echo "Set Configuration 'REPOSITORY_COMPONENT' to '${COMPONENT}'" + - name: Publish Package [Release] + uses: https://gitea.com/actions/gitea-release-action@v1 + with: + name: WSDD v${{ steps.environment.outputs.version }} + tag_name: v${{ steps.environment.outputs.version }} + files: | + wsdd_${{ steps.environment.outputs.version }}_${{ matrix.architecture }}.deb + - name: Debian Package [Debian Repository Publish] + env: + ARCHITECTURE: ${{ matrix.architecture }} + REPOSITORY_SSH_HOSTNAME: ${{ secrets.REPOSITORY_SSH_HOSTNAME }} + REPOSITORY_SSH_USER: ${{ secrets.REPOSITORY_SSH_USER }} + REPOSITORY_DESTINATION: ${{ secrets.REPOSITORY_DESTINATION }} + VERSION: ${{ steps.environment.outputs.version }} + run: | + /usr/bin/scp -4 -B -C -i './id_ed25519' -o 'LogLevel QUIET' -o 'StrictHostKeyChecking no' -o "UserKnownHostsFile '/dev/null'" "./wsdd_${VERSION}_${ARCHITECTURE}.deb" "${REPOSITORY_SSH_USER}"@"${REPOSITORY_SSH_HOSTNAME}":"${REPOSITORY_DESTINATION}/wsdd_${VERSION}_${ARCHITECTURE}.deb" + /usr/bin/scp -4 -B -C -i './id_ed25519' -o 'LogLevel QUIET' -o 'StrictHostKeyChecking no' -o "UserKnownHostsFile '/dev/null'" "./wsdd_${VERSION}_${ARCHITECTURE}.cfg" "${REPOSITORY_SSH_USER}"@"${REPOSITORY_SSH_HOSTNAME}":"${REPOSITORY_DESTINATION}/wsdd_${VERSION}_${ARCHITECTURE}.cfg" diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6f9c8a0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# ---> macOS +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ebfceb2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,232 @@ +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 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. + + Repository + Copyright (C) 2025 Repository + + 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: + + Repository Copyright (C) 2025 Repository + 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 . diff --git a/README.md b/README.md new file mode 100644 index 0000000..3adfd4b --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# WSDD + +[Forked: Github (christgau/wsdd)](https://github.com/christgau/wsdd) + diff --git a/wsdd/DEBIAN/conffiles b/wsdd/DEBIAN/conffiles new file mode 100644 index 0000000..112f8f2 --- /dev/null +++ b/wsdd/DEBIAN/conffiles @@ -0,0 +1 @@ +/etc/default/wsdd diff --git a/wsdd/DEBIAN/control b/wsdd/DEBIAN/control new file mode 100644 index 0000000..40120bd --- /dev/null +++ b/wsdd/DEBIAN/control @@ -0,0 +1,10 @@ +Package: wsdd +Version: +Architecture: +Installed-Size: +Depends: python3 +Priority: optional +Section: misc +Homepage: http://www.privlab.it +Maintainer: PrivLab +Description: Python Web Services Discovery Daemon, Windows Net Browsing diff --git a/wsdd/DEBIAN/postinst b/wsdd/DEBIAN/postinst new file mode 100644 index 0000000..d996fcc --- /dev/null +++ b/wsdd/DEBIAN/postinst @@ -0,0 +1,37 @@ +#!/usr/bin/sh + +set -e +set -u + +if [ -d '/run/systemd/system' ]; then + /usr/bin/systemctl --system daemon-reload > '/dev/null' || true +fi + +case "${1}" in + configure) + if [ -x '/usr/bin/deb-systemd-helper' ]; then + /usr/bin/deb-systemd-helper unmask 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + fi + if /usr/bin/deb-systemd-helper --quiet was-enabled 'wsdd.service'; then + /usr/bin/deb-systemd-helper enable 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + else + /usr/bin/deb-systemd-helper update-state 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + fi + if [ -x '/etc/init.d/wsdd' ]; then + /usr/sbin/update-rc.d 'wsdd' defaults > '/dev/null' || true + fi + if [ -x '/usr/bin/deb-systemd-invoke' ]; then + /usr/bin/systemctl --system daemon-reload > '/dev/null' || true + if [ -n "${2}" ]; then + _dh_action='restart' + else + _dh_action='start' + fi + /usr/bin/deb-systemd-invoke "${_dh_action}" 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + fi + ;; +esac diff --git a/wsdd/DEBIAN/postrm b/wsdd/DEBIAN/postrm new file mode 100644 index 0000000..91e7b2f --- /dev/null +++ b/wsdd/DEBIAN/postrm @@ -0,0 +1,32 @@ +#!/usr/bin/sh + +set -e +set -u + +if [ -d '/run/systemd/system' ]; then + /usr/bin/systemctl --system daemon-reload > '/dev/null' 2>&1 || \ + /usr/bin/true +fi + +case "${1}" in + remove) + if [ -x '/usr/bin/deb-systemd-helper' ]; then + /usr/bin/deb-systemd-helper mask 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + fi + ;; + purge) + if [ -x '/usr/bin/deb-systemd-helper' ]; then + /usr/bin/deb-systemd-helper purge 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + /usr/bin/deb-systemd-helper unmask 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + fi + if /usr/bin/getent passwd 'wsdd' > '/dev/null' 2>&1; then + /usr/sbin/deluser 'wsdd' > '/dev/null' 2>&1 + fi + if /usr/bin/getent group 'wsdd' > '/dev/null' 2>&1; then + /usr/sbin/deluser --group 'wsdd' > '/dev/null' 2>&1 + fi + ;; +esac diff --git a/wsdd/DEBIAN/preinst b/wsdd/DEBIAN/preinst new file mode 100644 index 0000000..d6e72f8 --- /dev/null +++ b/wsdd/DEBIAN/preinst @@ -0,0 +1,20 @@ +#!/usr/bin/sh + +set -e +set -u + +case "${1}" in + install) + if ! /usr/bin/getent passwd 'wsdd' > '/dev/null' 2>&1; then + /usr/sbin/adduser --quiet \ + --system \ + --home '/run/wsdd' \ + --shell '/usr/sbin/nologin' \ + --no-create-home \ + --group \ + --disabled-password \ + --disabled-login \ + 'wsdd' > '/dev/null' 2>&1 + fi + ;; +esac diff --git a/wsdd/DEBIAN/prerm b/wsdd/DEBIAN/prerm new file mode 100644 index 0000000..e12f0ae --- /dev/null +++ b/wsdd/DEBIAN/prerm @@ -0,0 +1,22 @@ +#!/usr/bin/sh + +set -e +set -u + +case "${1}" in + remove) + if [ -x '/usr/bin/deb-systemd-invoke' ]; then + /usr/bin/deb-systemd-invoke stop 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + /usr/bin/deb-systemd-invoke disable 'wsdd.service' > '/dev/null' 2>&1 || \ + /usr/bin/true + fi + if [ -x '/etc/init.d/traefik' ]; then + /usr/sbin/update-rc.d 'wsdd' remove > '/dev/null' 2>&1 || \ + /usr/bin/true + fi + ;; +esac + +/usr/bin/rm --force --recursive '/var/log/wsdd' +/usr/bin/rm --force --recursive '/var/logrotate/wsdd' \ No newline at end of file diff --git a/wsdd/etc/default/wsdd b/wsdd/etc/default/wsdd new file mode 100644 index 0000000..66efe5a --- /dev/null +++ b/wsdd/etc/default/wsdd @@ -0,0 +1,6 @@ +# Additional arguments for wsdd can be provided here. +# Use, e.g., "-i eth0" to restrict operations to a specific interface +# Refer to the wsdd(8) man page for details + +WSDD_PARAMS="--shortlog --chroot='/run/wsdd'" +WSDD_DISCOVERY_PARAMS="--shortlog --chroot='/run/wsdd' --source-port='37020' --no-host --discovery" diff --git a/wsdd/etc/init.d/wsdd b/wsdd/etc/init.d/wsdd new file mode 100644 index 0000000..8f27c5b --- /dev/null +++ b/wsdd/etc/init.d/wsdd @@ -0,0 +1,81 @@ +#!/usr/bin/sh + +### BEGIN INIT INFO +# Provides: wsdd +# Required-Start: $local_fs $network $remote_fs +# Required-Stop: $local_fs $network $remote_fs +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Web Services Dynamic Discovery host daemon +# Description: Web Services Dynamic Discovery (WSDD) host daemon +### END INIT INFO + + +NAME='wsdd' +DESC='Web Services Dynamic Discovery host daemon' +USER='wsdd' +GROUP='wsdd' +PIDFOLDER="/run/${NAME}" +PIDFILE="${PIDFOLDER}/${NAME}.pid" +DAEMON='/usr/sbin/wsdd' +DAEMON_CONFIG='/etc/default/wsdd' + +set -e + +[ -f "${DAEMON_CONFIG}" ] + +. /etc/default/${NAME} +. /lib/lsb/init-functions + +[ -x "${DAEMON}" ] + +case "${1}" in + start) + /usr/bin/install --directory --group="${GROUP}" ---mode='0755' --owner="${USER}" "${PIDFOLDER}" + log_daemon_msg "Starting ${DESC}" "${NAME}" + if /usr/sbin/start-stop-daemon --quiet \ + --start \ + --background \ + --make-pidfile \ + --pidfile "${PIDFILE}" \ + --user "${USER}" \ + --group "${GROUP}" \ + --exec "${DAEMON}" -- "${WSDD_PARAMS}"; then + log_end_msg 0 + else + log_end_msg 1 + /usr/bin/test -f "${PIDFILE}" && \ + /usr/bin/rm --force "${PIDFILE}" + fi + ;; + stop) + log_daemon_msg "Stopping ${DESC}" "${NAME}" + if /usr/sbin/start-stop-daemon --quiet \ + --stop \ + --retry 30 \ + --remove-pidfile \ + --pidfile "${PIDFILE}" \ + --user "${USER}" \ + --group "${GROUP}" \ + --exec "${DAEMON}"; then + /usr/bin/test -f "${PIDFILE}" && \ + /usr/bin/rm --force "${PIDFILE}" + log_end_msg 0 + else + log_end_msg 1 + fi + ;; + restart) + "${0}" stop + "${0}" start + ;; + status) + status_of_proc -p "${PIDFILE}" "${DAEMON}" "${NAME}" && \ + exit 0 || \ + exit "${?}" + ;; + *) + echo "Usage: /etc/init.d/${NAME} {start|stop|restart|status}" >&2 + exit 1 + ;; +esac diff --git a/wsdd/lib/systemd/system/wsdd-discovery.service b/wsdd/lib/systemd/system/wsdd-discovery.service new file mode 100644 index 0000000..f92d3b4 --- /dev/null +++ b/wsdd/lib/systemd/system/wsdd-discovery.service @@ -0,0 +1,14 @@ +[Unit] +Description=Web Services Dynamic Discovery service +Documentation=man:wsdd(8) +Requires=wsdd-discovery.socket + +[Service] +Type=simple +AmbientCapabilities=CAP_SYS_CHROOT +EnvironmentFile=-/etc/default/wsdd +ExecStart=/usr/sbin/wsdd $WSDD_DISCOVERY_PARAMS +DynamicUser=yes +User=wsdd +Group=wsdd +RuntimeDirectory=wsdd diff --git a/wsdd/lib/systemd/system/wsdd-discovery.socket b/wsdd/lib/systemd/system/wsdd-discovery.socket new file mode 100644 index 0000000..dce8ea8 --- /dev/null +++ b/wsdd/lib/systemd/system/wsdd-discovery.socket @@ -0,0 +1,9 @@ +[Unit] +Description=Web Services Dynamic Discovery API socket +Documentation=man:wsdd(8) + +[Socket] +ListenStream=%t/wsdd.socket + +[Install] +WantedBy=sockets.target diff --git a/wsdd/lib/systemd/system/wsdd.service b/wsdd/lib/systemd/system/wsdd.service new file mode 100644 index 0000000..7729e78 --- /dev/null +++ b/wsdd/lib/systemd/system/wsdd.service @@ -0,0 +1,18 @@ +[Unit] +Description=Web Services Dynamic Discovery host daemon +Documentation=man:wsdd(8) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +AmbientCapabilities=CAP_SYS_CHROOT +EnvironmentFile=-/etc/default/wsdd +ExecStart=/usr/sbin/wsdd $WSDD_PARAMS +DynamicUser=yes +User=wsdd +Group=wsdd +RuntimeDirectory=wsdd + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/wsdd/usr/lib/sysusers.d/wsdd.conf b/wsdd/usr/lib/sysusers.d/wsdd.conf new file mode 100644 index 0000000..c12f75c --- /dev/null +++ b/wsdd/usr/lib/sysusers.d/wsdd.conf @@ -0,0 +1,2 @@ +g wsdd - - +u wsdd - "wsdd" /run/wsdd /usr/sbin/nologin diff --git a/wsdd/usr/sbin/wsdd b/wsdd/usr/sbin/wsdd new file mode 100644 index 0000000..61caef8 --- /dev/null +++ b/wsdd/usr/sbin/wsdd @@ -0,0 +1,2154 @@ +#!/usr/bin/env python3 + +# Implements a target service according to the Web Service Discovery +# specification. +# +# The purpose is to enable non-Windows devices to be found by the 'Network +# (Neighborhood)' from Windows machines. +# +# see http://specs.xmlsoap.org/ws/2005/04/discovery/ws-discovery.pdf and +# related documents for details (look at README for more references) +# +# (c) Steffen Christgau, 2017-2025 + +import sys +import signal +import socket +import asyncio +import struct +import argparse +import uuid +import time +import random +import logging +import platform +import ctypes.util +import collections +import xml.etree.ElementTree as ElementTree +import http +import http.server +import urllib.request +import urllib.parse +import os +import pwd +import grp +import datetime + +from typing import Any, Callable, ClassVar, Deque, Dict, List, Optional, Set, Union, Tuple + +# try to load more secure XML module first, fallback to default if not present +try: + from defusedxml.ElementTree import fromstring as ETfromString +except ModuleNotFoundError: + from xml.etree.ElementTree import fromstring as ETfromString + +try: + import systemd.daemon # type: ignore +except ModuleNotFoundError: + # Non-systemd host + pass + +WSDD_VERSION: str = '0.9' + + +args: argparse.Namespace +logger: logging.Logger + + +class NetworkInterface: + + _name: str + _index: int + _scope: int + + def __init__(self, name: str, scope: int, index: int) -> None: + self._name = name + self._scope = scope + if index is not None: + self._index = index + else: + self._index = socket.if_nametoindex(self._name) + + @property + def name(self) -> str: + return self._name + + @property + def scope(self) -> int: + return self._scope + + @property + def index(self) -> int: + return self._index + + def __str__(self) -> str: + return self._name + + def __eq__(self, other) -> bool: + return self._name == other.name + + +class NetworkAddress: + + _family: int + _raw_address: bytes + _address_str: str + _interface: NetworkInterface + + def __init__(self, family: int, raw: Union[bytes, str], interface: NetworkInterface) -> None: + self._family = family + self._raw_address = raw if isinstance(raw, bytes) else socket.inet_pton(family, raw.partition('%')[0]) + self._interface = interface + + self._address_str = socket.inet_ntop(self._family, self._raw_address) + + @property + def address_str(self): + return self._address_str + + @property + def family(self): + return self._family + + @property + def interface(self): + return self._interface + + @property + def is_multicastable(self): + """ return true if the (interface) address can be used for creating (link-local) multicasting sockets """ + # Nah, this check is not optimal but there are no local flags for + # addresses, but it should be safe for IPv4 anyways + # (https://tools.ietf.org/html/rfc5735#page-3) + return ((self._family == socket.AF_INET) and (self._raw_address[0] != 127) + or (self._family == socket.AF_INET6) and (self._raw_address[0:2] == b'\xfe\x80')) + + @property + def raw(self): + return self._raw_address + + @property + def transport_str(self): + """the string representation of the local address overridden in network setup (for IPv6)""" + return self._address_str if self._family == socket.AF_INET else '[{}]'.format(self._address_str) + + def __str__(self) -> str: + return '{}%{}'.format(self._address_str, self._interface.name) + + def __eq__(self, other) -> bool: + return (self._family == other.family and self.raw == other.raw and self.interface == other.interface) + + +class UdpAddress(NetworkAddress): + + _transport_address: Tuple + _port: int + + def __init__(self, family, transport_address: Tuple, interface: NetworkInterface) -> None: + + if not (family == socket.AF_INET or family == socket.AF_INET6): + raise RuntimeError('Unsupport address address family: {}.'.format(family)) + + self._transport_address = transport_address + self._port = transport_address[1] + + super().__init__(family, transport_address[0], interface) + + @property + def transport_address(self): + return self._transport_address + + @property + def port(self): + return self._port + + def __eq__(self, other) -> bool: + return self.transport_address == other.transport_address + + +class INetworkPacketHandler: + + def handle_packet(self, msg: str, udp_src_address: UdpAddress) -> None: + pass + + +class MulticastHandler: + """ + A class for handling multicast traffic on a given interface for a + given address family. It provides multicast sender and receiver sockets + """ + + # base interface addressing information + address: NetworkAddress + + # individual interface-bound sockets for: + # - receiving multicast traffic + # - sending multicast from a socket bound to WSD port + # - sending unicast messages from a random port + recv_socket: socket.socket + mc_send_socket: socket.socket + uc_send_socket: socket.socket + + # addresses used for communication and data + multicast_address: UdpAddress + listen_address: Tuple + aio_loop: asyncio.AbstractEventLoop + + # dictionary that holds INetworkPacketHandlers instances for sockets created above + message_handlers: Dict[socket.socket, List[INetworkPacketHandler]] + + def __init__(self, address: NetworkAddress, aio_loop: asyncio.AbstractEventLoop) -> None: + self.address = address + + self.recv_socket = socket.socket(self.address.family, socket.SOCK_DGRAM) + self.recv_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.mc_send_socket = socket.socket(self.address.family, socket.SOCK_DGRAM) + self.uc_send_socket = socket.socket(self.address.family, socket.SOCK_DGRAM) + self.uc_send_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + + self.message_handlers = {} + self.aio_loop = aio_loop + + if self.address.family == socket.AF_INET: + self.init_v4() + elif self.address.family == socket.AF_INET6: + self.init_v6() + + logger.info('joined multicast group {0} on {1}'.format(self.multicast_address.transport_str, self.address)) + logger.debug('transport address on {0} is {1}'.format(self.address.interface.name, self.address.transport_str)) + logger.debug('will listen for HTTP traffic on address {0}'.format(self.listen_address)) + + # register calbacks for incoming data (also for mc) + self.aio_loop.add_reader(self.recv_socket.fileno(), self.read_socket, self.recv_socket) + self.aio_loop.add_reader(self.mc_send_socket.fileno(), self.read_socket, self.mc_send_socket) + self.aio_loop.add_reader(self.uc_send_socket.fileno(), self.read_socket, self.uc_send_socket) + + def cleanup(self) -> None: + self.aio_loop.remove_reader(self.recv_socket) + self.aio_loop.remove_reader(self.mc_send_socket) + self.aio_loop.remove_reader(self.uc_send_socket) + + self.recv_socket.close() + self.mc_send_socket.close() + self.uc_send_socket.close() + + def handles_address(self, address: NetworkAddress) -> bool: + return self.address == address + + def init_v6(self) -> None: + idx = self.address.interface.index + raw_mc_addr = (WSD_MCAST_GRP_V6, WSD_UDP_PORT, 0x575C, idx) + self.multicast_address = UdpAddress(self.address.family, raw_mc_addr, self.address.interface) + + # v6: member_request = { multicast_addr, intf_idx } + mreq = (socket.inet_pton(self.address.family, WSD_MCAST_GRP_V6) + struct.pack('@I', idx)) + self.recv_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, mreq) + self.recv_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) + + # Could anyone ask the Linux folks for the rationale for this!? + if platform.system() == 'Linux': + try: + # supported starting from Linux 4.20 + IPV6_MULTICAST_ALL = 29 + self.recv_socket.setsockopt(socket.IPPROTO_IPV6, IPV6_MULTICAST_ALL, 0) + except OSError as e: + logger.warning('cannot unset all_multicast: {}'.format(e)) + + # bind to network interface, i.e. scope and handle OS differences, + # see Stevens: Unix Network Programming, Section 21.6, last paragraph + try: + self.recv_socket.bind((WSD_MCAST_GRP_V6, WSD_UDP_PORT, 0, idx)) + except OSError: + self.recv_socket.bind(('::', 0, 0, idx)) + + # bind unicast socket to interface address and WSD's udp port + self.uc_send_socket.bind((str(self.address), WSD_UDP_PORT, 0, idx)) + + self.mc_send_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_LOOP, 0) + self.mc_send_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, args.hoplimit) + self.mc_send_socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, idx) + + # bind multicast socket to interface address and a user-provided port (or random if unspecified) + # this allows not-so-smart firewalls to whitelist another port to allow incoming replies + try: + self.mc_send_socket.bind((str(self.address), args.source_port, 0, idx)) + except OSError: + logger.error('specified port {} already in use for {}'.format(args.source_port, str(self.address))) + + self.listen_address = (self.address.address_str, WSD_HTTP_PORT, 0, idx) + + def init_v4(self) -> None: + idx = self.address.interface.index + raw_mc_addr = (WSD_MCAST_GRP_V4, WSD_UDP_PORT) + self.multicast_address = UdpAddress(self.address.family, raw_mc_addr, self.address.interface) + + # v4: member_request (ip_mreqn) = { multicast_addr, intf_addr, idx } + if platform.system() == 'SunOS': + mreq = (socket.inet_pton(self.address.family, WSD_MCAST_GRP_V4) + self.address.raw) + else: + mreq = (socket.inet_pton(self.address.family, WSD_MCAST_GRP_V4) + self.address.raw + struct.pack('@I', idx)) + self.recv_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) + + if platform.system() == 'Linux': + IP_MULTICAST_ALL = 49 + self.recv_socket.setsockopt(socket.IPPROTO_IP, IP_MULTICAST_ALL, 0) + + try: + self.recv_socket.bind((WSD_MCAST_GRP_V4, WSD_UDP_PORT)) + except OSError: + self.recv_socket.bind(('', WSD_UDP_PORT)) + + # bind unicast socket to interface address and WSD's udp port + self.uc_send_socket.bind((self.address.address_str, WSD_UDP_PORT)) + + if platform.system() == 'SunOS': + self.mc_send_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, self.address.raw) + else: + self.mc_send_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, mreq) + # OpenBSD requires the optlen to be sizeof(char) for LOOP and TTL options + # (see also https://github.com/python/cpython/issues/67316) + self.mc_send_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, struct.pack('B', 0)) + self.mc_send_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, struct.pack('B', args.hoplimit)) + + # bind multicast socket to interface address and a user-provided port (or random if unspecified) + # this allows not-so-smart firewalls to whitelist another port to allow incoming replies + try: + self.mc_send_socket.bind((self.address.address_str, args.source_port)) + except OSError: + logger.error('specified port {} already in use for {}'.format(args.source_port, self.address.address_str)) + + self.listen_address = (self.address.address_str, WSD_HTTP_PORT) + + def add_handler(self, socket: socket.socket, handler: INetworkPacketHandler) -> None: + # try: + # self.selector.register(socket, selectors.EVENT_READ, self) + # except KeyError: + # # accept attempts of multiple registrations + # pass + + if socket in self.message_handlers: + self.message_handlers[socket].append(handler) + else: + self.message_handlers[socket] = [handler] + + def remove_handler(self, socket: socket.socket, handler) -> None: + if socket in self.message_handlers: + if handler in self.message_handlers[socket]: + self.message_handlers[socket].remove(handler) + + def read_socket(self, key: socket.socket) -> None: + # TODO: refactor this + s = None + if key == self.uc_send_socket: + s = self.uc_send_socket + elif key == self.mc_send_socket: + s = self.mc_send_socket + elif key == self.recv_socket: + s = self.recv_socket + else: + raise ValueError("Unknown socket passed as key.") + + msg, raw_address = s.recvfrom(WSD_MAX_LEN) + address = UdpAddress(self.address.family, raw_address, self.address.interface) + if s in self.message_handlers: + for handler in self.message_handlers[s]: + handler.handle_packet(msg.decode('utf-8'), address) + + def send(self, msg: bytes, addr: UdpAddress): + # Request from a client must be answered from a socket that is bound + # to the WSD port, i.e. the recv_socket. Messages to multicast + # addresses are sent over the dedicated send socket. + if addr == self.multicast_address: + self.mc_send_socket.sendto(msg, addr.transport_address) + else: + self.uc_send_socket.sendto(msg, addr.transport_address) + + +# constants for WSD XML/SOAP parsing +WSA_URI: str = 'http://schemas.xmlsoap.org/ws/2004/08/addressing' +WSD_URI: str = 'http://schemas.xmlsoap.org/ws/2005/04/discovery' +WSDP_URI: str = 'http://schemas.xmlsoap.org/ws/2006/02/devprof' + +namespaces: Dict[str, str] = { + 'soap': 'http://www.w3.org/2003/05/soap-envelope', + 'wsa': WSA_URI, + 'wsd': WSD_URI, + 'wsx': 'http://schemas.xmlsoap.org/ws/2004/09/mex', + 'wsdp': WSDP_URI, + 'pnpx': 'http://schemas.microsoft.com/windows/pnpx/2005/10', + 'pub': 'http://schemas.microsoft.com/windows/pub/2005/07' +} + +WSD_MAX_KNOWN_MESSAGES: int = 10 + +WSD_PROBE: str = WSD_URI + '/Probe' +WSD_PROBE_MATCH: str = WSD_URI + '/ProbeMatches' +WSD_RESOLVE: str = WSD_URI + '/Resolve' +WSD_RESOLVE_MATCH: str = WSD_URI + '/ResolveMatches' +WSD_HELLO: str = WSD_URI + '/Hello' +WSD_BYE: str = WSD_URI + '/Bye' +WSD_GET: str = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Get' +WSD_GET_RESPONSE: str = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse' + +WSD_TYPE_DEVICE: str = 'wsdp:Device' +PUB_COMPUTER: str = 'pub:Computer' +WSD_TYPE_DEVICE_COMPUTER: str = '{0} {1}'.format(WSD_TYPE_DEVICE, PUB_COMPUTER) + +WSD_MCAST_GRP_V4: str = '239.255.255.250' +WSD_MCAST_GRP_V6: str = 'ff02::c' # link-local + +WSA_ANON: str = WSA_URI + '/role/anonymous' +WSA_DISCOVERY: str = 'urn:schemas-xmlsoap-org:ws:2005:04:discovery' + +MIME_TYPE_SOAP_XML: str = 'application/soap+xml' + +# protocol assignments (WSD spec/Section 2.4) +WSD_UDP_PORT: int = 3702 +WSD_HTTP_PORT: int = 5357 +WSD_MAX_LEN: int = 32767 + +WSDD_LISTEN_PORT = 5359 + +# SOAP/UDP transmission constants +MULTICAST_UDP_REPEAT: int = 4 +UNICAST_UDP_REPEAT: int = 2 +UDP_MIN_DELAY: int = 50 +UDP_MAX_DELAY: int = 250 +UDP_UPPER_DELAY: int = 500 + +# servers must recond in 4 seconds after probe arrives +PROBE_TIMEOUT: int = 4 +MAX_STARTUP_PROBE_DELAY: int = 3 + +# some globals +wsd_instance_id: int = int(time.time()) + +WSDMessage = Tuple[ElementTree.Element, str] +MessageTypeHandler = Callable[[ElementTree.Element, ElementTree.Element], Optional[WSDMessage]] + + +class WSDMessageHandler(INetworkPacketHandler): + known_messages: Deque[str] = collections.deque([], WSD_MAX_KNOWN_MESSAGES) + + handlers: Dict[str, MessageTypeHandler] + pending_tasks: List[asyncio.Task] + + def __init__(self) -> None: + self.handlers = {} + self.pending_tasks = [] + + def cleanup(self): + pass + + # shortcuts for building WSD responses + def add_endpoint_reference(self, parent: ElementTree.Element, endpoint: Optional[str] = None) -> None: + epr = ElementTree.SubElement(parent, 'wsa:EndpointReference') + address = ElementTree.SubElement(epr, 'wsa:Address') + if endpoint is None: + address.text = args.uuid.urn + else: + address.text = endpoint + + def add_metadata_version(self, parent: ElementTree.Element) -> None: + meta_data = ElementTree.SubElement(parent, 'wsd:MetadataVersion') + meta_data.text = '1' + + def add_types(self, parent: ElementTree.Element) -> None: + dev_type = ElementTree.SubElement(parent, 'wsd:Types') + dev_type.text = WSD_TYPE_DEVICE_COMPUTER + + def add_xaddr(self, parent: ElementTree.Element, transport_addr: str) -> None: + if transport_addr: + item = ElementTree.SubElement(parent, 'wsd:XAddrs') + item.text = 'http://{0}:{1}/{2}'.format(transport_addr, WSD_HTTP_PORT, args.uuid) + + def build_message(self, to_addr: str, action_str: str, request_header: Optional[ElementTree.Element], + response: ElementTree.Element) -> str: + retval = self.xml_to_str(self.build_message_tree(to_addr, action_str, request_header, response)[0]) + + logger.debug('constructed xml for WSD message: {0}'.format(retval)) + + return retval + + def build_message_tree(self, to_addr: str, action_str: str, request_header: Optional[ElementTree.Element], + body: Optional[ElementTree.Element]) -> Tuple[ElementTree.Element, str]: + """ + Build a WSD message with a given action string including SOAP header. + + The message can be constructed based on a response to another + message (given by its header) and with a optional response that + serves as the message's body + """ + root = ElementTree.Element('soap:Envelope') + header = ElementTree.SubElement(root, 'soap:Header') + + to = ElementTree.SubElement(header, 'wsa:To') + to.text = to_addr + + action = ElementTree.SubElement(header, 'wsa:Action') + action.text = action_str + + msg_id = ElementTree.SubElement(header, 'wsa:MessageID') + msg_id.text = uuid.uuid1().urn + + if request_header is not None: + req_msg_id = request_header.find('./wsa:MessageID', namespaces) + if req_msg_id is not None: + relates_to = ElementTree.SubElement(header, 'wsa:RelatesTo') + relates_to.text = req_msg_id.text + + self.add_header_elements(header, action_str) + + body_root = ElementTree.SubElement(root, 'soap:Body') + if body is not None: + body_root.append(body) + + for prefix, uri in namespaces.items(): + root.attrib['xmlns:' + prefix] = uri + + return root, msg_id.text + + def add_header_elements(self, header: ElementTree.Element, extra: Any) -> None: + pass + + def handle_message(self, msg: str, src: Optional[UdpAddress] = None) -> Optional[str]: + """ + handle a WSD message + """ + try: + tree = ETfromString(msg) + except ElementTree.ParseError: + return None + + header = tree.find('./soap:Header', namespaces) + if header is None: + return None + + msg_id_tag = header.find('./wsa:MessageID', namespaces) + if msg_id_tag is None: + return None + + msg_id = str(msg_id_tag.text) + + # check for duplicates + if self.is_duplicated_msg(msg_id): + logger.debug('known message ({0}): dropping it'.format(msg_id)) + return None + + action_tag = header.find('./wsa:Action', namespaces) + if action_tag is None: + return None + + action: str = str(action_tag.text) + _, _, action_method = action.rpartition('/') + + if src: + logger.info('{}:{}({}) - - "{} {} UDP" - -'.format( + src.transport_str, src.port, src.interface, action_method, msg_id)) + else: + # http logging is already done by according server + logger.debug('processing WSD {} message ({})'.format(action_method, msg_id)) + + body = tree.find('./soap:Body', namespaces) + if body is None: + return None + + logger.debug('incoming message content is {0}'.format(msg)) + if action in self.handlers: + handler = self.handlers[action] + retval = handler(header, body) + if retval is not None: + response, response_type = retval + return self.build_message(WSA_ANON, response_type, header, response) + else: + logger.debug('unhandled action {0}/{1}'.format(action, msg_id)) + + return None + + def is_duplicated_msg(self, msg_id: str) -> bool: + """ + Check for a duplicated message. + + Implements SOAP-over-UDP Appendix II Item 2 + """ + if msg_id in type(self).known_messages: + return True + + type(self).known_messages.append(msg_id) + + return False + + def xml_to_str(self, xml: ElementTree.Element) -> str: + retval = '' + retval = retval + ElementTree.tostring(xml, encoding='utf-8').decode('utf-8') + + return retval + + +class WSDUDPMessageHandler(WSDMessageHandler): + """ + A message handler that handles traffic received via MutlicastHandler. + """ + + mch: MulticastHandler + tearing_down: bool + + def __init__(self, mch: MulticastHandler) -> None: + super().__init__() + + self.mch = mch + self.tearing_down = False + + def teardown(self): + self.tearing_down = True + + def send_datagram(self, msg: str, dst: UdpAddress) -> None: + try: + self.mch.send(msg.encode('utf-8'), dst) + except Exception as e: + logger.error('error while sending packet on {}: {}'.format(self.mch.address.interface, e)) + + def enqueue_datagram(self, msg: str, address: UdpAddress, msg_type: Optional[str] = None) -> None: + if msg_type: + logger.info('scheduling {0} message via {1} to {2}'.format(msg_type, address.interface, address)) + + schedule_task = self.mch.aio_loop.create_task(self.schedule_datagram(msg, address)) + # Add this task to the pending list during teardown to wait during shutdown + if self.tearing_down: + self.pending_tasks.append(schedule_task) + + async def schedule_datagram(self, msg: str, address: UdpAddress) -> None: + """ + Schedule to send the given message to the given address. + + Implements SOAP over UDP, Appendix I. + """ + + self.send_datagram(msg, address) + + delta = 0 + msg_count = MULTICAST_UDP_REPEAT if address == self.mch.multicast_address else UNICAST_UDP_REPEAT + delta = random.randint(UDP_MIN_DELAY, UDP_MAX_DELAY) + for i in range(msg_count - 1): + await asyncio.sleep(delta / 1000.0) + self.send_datagram(msg, address) + delta = min(delta * 2, UDP_UPPER_DELAY) + + +class WSDDiscoveredDevice: + + # a dict of discovered devices with their UUID as key + instances: Dict[str, 'WSDDiscoveredDevice'] = {} + + addresses: Dict[str, Set[str]] + props: Dict[str, str] + display_name: str + last_seen: float + types: Set[str] + + def __init__(self, xml_str: str, xaddr: str, interface: NetworkInterface) -> None: + self.last_seen = 0.0 + self.addresses = {} + self.props = {} + self.display_name = '' + self.types = set() + + self.update(xml_str, xaddr, interface) + + def update(self, xml_str: str, xaddr: str, interface: NetworkInterface) -> None: + try: + tree = ETfromString(xml_str) + except ElementTree.ParseError: + return None + mds_path = 'soap:Body/wsx:Metadata/wsx:MetadataSection' + sections = tree.findall(mds_path, namespaces) + for section in sections: + dialect = section.attrib['Dialect'] + if dialect == WSDP_URI + '/ThisDevice': + self.extract_wsdp_props(section, dialect) + elif dialect == WSDP_URI + '/ThisModel': + self.extract_wsdp_props(section, dialect) + elif dialect == WSDP_URI + '/Relationship': + host_xpath = 'wsdp:Relationship[@Type="{}/host"]/wsdp:Host'.format(WSDP_URI) + host_sec = section.find(host_xpath, namespaces) + if (host_sec is not None): + self.extract_host_props(host_sec) + else: + logger.debug('unknown metadata dialect ({})'.format(dialect)) + + url = urllib.parse.urlparse(xaddr) + addr, _, _ = url.netloc.rpartition(':') + report = True + if interface.name not in self.addresses: + self.addresses[interface.name] = set([addr]) + else: + if addr not in self.addresses[interface.name]: + self.addresses[interface.name].add(addr) + else: + report = False + + self.last_seen = time.time() + if ('DisplayName' in self.props) and ('BelongsTo' in self.props) and (report): + self.display_name = self.props['DisplayName'] + logger.info('discovered {} in {} on {}'.format(self.display_name, self.props['BelongsTo'], addr)) + elif ('FriendlyName' in self.props) and (report): + self.display_name = self.props['FriendlyName'] + logger.info('discovered {} on {}'.format(self.display_name, addr)) + + logger.debug(str(self.props)) + + def extract_wsdp_props(self, root: ElementTree.Element, dialect: str) -> None: + _, _, propsRoot = dialect.rpartition('/') + # XPath support is limited, so filter by namespace on our own + nodes = root.findall('./wsdp:{0}/*'.format(propsRoot), namespaces) + ns_prefix = '{{{}}}'.format(WSDP_URI) + prop_nodes = [n for n in nodes if n.tag.startswith(ns_prefix)] + for node in prop_nodes: + tag_name = node.tag[len(ns_prefix):] + self.props[tag_name] = str(node.text) + + def extract_host_props(self, root: ElementTree.Element) -> None: + self.types = set(root.findtext('wsdp:Types', '', namespaces).split(' ')) + if PUB_COMPUTER not in self.types: + return + + comp = root.findtext(PUB_COMPUTER, '', namespaces) + self.props['DisplayName'], _, self.props['BelongsTo'] = ( + comp.partition('/')) + + +class WSDClient(WSDUDPMessageHandler): + + instances: ClassVar[List['WSDClient']] = [] + probes: Dict[str, float] + + def __init__(self, mch: MulticastHandler) -> None: + super().__init__(mch) + + WSDClient.instances.append(self) + + self.mch.add_handler(self.mch.mc_send_socket, self) + self.mch.add_handler(self.mch.recv_socket, self) + + self.probes = {} + + self.handlers[WSD_HELLO] = self.handle_hello + self.handlers[WSD_BYE] = self.handle_bye + self.handlers[WSD_PROBE_MATCH] = self.handle_probe_match + self.handlers[WSD_RESOLVE_MATCH] = self.handle_resolve_match + + # avoid packet storm when hosts come up by delaying initial probe + time.sleep(random.randint(0, MAX_STARTUP_PROBE_DELAY)) + self.send_probe() + + def cleanup(self) -> None: + super().cleanup() + WSDClient.instances.remove(self) + + self.mch.remove_handler(self.mch.mc_send_socket, self) + self.mch.remove_handler(self.mch.recv_socket, self) + + def send_probe(self) -> None: + """WS-Discovery, Section 4.3, Probe message""" + self.remove_outdated_probes() + + probe = ElementTree.Element('wsd:Probe') + ElementTree.SubElement(probe, 'wsd:Types').text = WSD_TYPE_DEVICE + + xml, i = self.build_message_tree(WSA_DISCOVERY, WSD_PROBE, None, probe) + self.enqueue_datagram(self.xml_to_str(xml), self.mch.multicast_address, msg_type='Probe') + self.probes[i] = time.time() + + def teardown(self) -> None: + super().teardown() + self.remove_outdated_probes() + + def handle_packet(self, msg: str, src: Optional[UdpAddress] = None) -> None: + self.handle_message(msg, src) + + def __extract_xaddr(self, xaddrs: str) -> Optional[str]: + for addr in xaddrs.strip().split(): + if (self.mch.address.family == socket.AF_INET6) and ('//[fe80::' in addr): + # use first link-local address for IPv6 + return addr + elif self.mch.address.family == socket.AF_INET: + # use first (and very likely the only) IPv4 address + return addr + + return None + + def handle_hello(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]: + pm_path = 'wsd:Hello' + endpoint, xaddrs = self.extract_endpoint_metadata(body, pm_path) + if not xaddrs: + logger.info('Hello without XAddrs, sending resolve') + msg = self.build_resolve_message(str(endpoint)) + self.enqueue_datagram(msg, self.mch.multicast_address) + return None + + xaddr = self.__extract_xaddr(xaddrs) + if xaddr is None: + return None + + logger.info('Hello from {} on {}'.format(endpoint, xaddr)) + self.perform_metadata_exchange(endpoint, xaddr) + return None + + def handle_bye(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]: + bye_path = 'wsd:Bye' + endpoint, _ = self.extract_endpoint_metadata(body, bye_path) + device_uri = str(urllib.parse.urlparse(endpoint).geturl()) + if device_uri in WSDDiscoveredDevice.instances: + del WSDDiscoveredDevice.instances[device_uri] + + return None + + def handle_probe_match(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]: + # do not handle to probematches issued not sent by ourself + rel_msg = header.findtext('wsa:RelatesTo', None, namespaces) + if rel_msg not in self.probes: + logger.debug("unknown probe {}".format(rel_msg)) + return None + + # if XAddrs are missing, issue resolve request + pm_path = 'wsd:ProbeMatches/wsd:ProbeMatch' + endpoint, xaddrs = self.extract_endpoint_metadata(body, pm_path) + if not xaddrs: + logger.debug('probe match without XAddrs, sending resolve') + msg = self.build_resolve_message(str(endpoint)) + self.enqueue_datagram(msg, self.mch.multicast_address) + return None + + xaddr = self.__extract_xaddr(xaddrs) + if xaddr is None: + return None + + logger.debug('probe match for {} on {}'.format(endpoint, xaddr)) + self.perform_metadata_exchange(endpoint, xaddr) + + return None + + def build_resolve_message(self, endpoint: str) -> str: + resolve = ElementTree.Element('wsd:Resolve') + self.add_endpoint_reference(resolve, endpoint) + + return self.build_message(WSA_DISCOVERY, WSD_RESOLVE, None, resolve) + + def handle_resolve_match(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]: + rm_path = 'wsd:ResolveMatches/wsd:ResolveMatch' + endpoint, xaddrs = self.extract_endpoint_metadata(body, rm_path) + if not endpoint or not xaddrs: + logger.debug('resolve match without endpoint/xaddr') + return None + + xaddr = self.__extract_xaddr(xaddrs) + if xaddr is None: + return None + + logger.debug('resolve match for {} on {}'.format(endpoint, xaddr)) + self.perform_metadata_exchange(endpoint, xaddr) + + return None + + def extract_endpoint_metadata(self, body: ElementTree.Element, prefix: str) -> Tuple[Optional[str], Optional[str]]: + prefix = prefix + '/' + addr_path = 'wsa:EndpointReference/wsa:Address' + + endpoint = body.findtext(prefix + addr_path, namespaces=namespaces) + xaddrs = body.findtext(prefix + 'wsd:XAddrs', namespaces=namespaces) + + return endpoint, xaddrs + + def perform_metadata_exchange(self, endpoint, xaddr: str): + if not (xaddr.startswith('http://') or xaddr.startswith('https://')): + logger.debug('invalid XAddr: {}'.format(xaddr)) + return + + host = None + url = xaddr + if self.mch.address.family == socket.AF_INET6: + host = '[{}]'.format(url.partition('[')[2].partition(']')[0]) + url = url.replace(']', '%{}]'.format(self.mch.address.interface)) + + body = self.build_getmetadata_message(endpoint) + request = urllib.request.Request(url, data=body.encode('utf-8'), method='POST') + request.add_header('Content-Type', 'application/soap+xml') + request.add_header('User-Agent', 'wsdd') + if host is not None: + request.add_header('Host', host) + + try: + with urllib.request.urlopen(request, None, args.metadata_timeout) as stream: + self.handle_metadata(stream.read(), endpoint, xaddr) + except urllib.error.URLError as e: + logger.warning('could not fetch metadata from: {} {}'.format(url, e)) + except TimeoutError: + logger.warning('metadata exchange with {} timed out'.format(url)) + + def build_getmetadata_message(self, endpoint) -> str: + tree, _ = self.build_message_tree(endpoint, WSD_GET, None, None) + return self.xml_to_str(tree) + + def handle_metadata(self, meta: str, endpoint: str, xaddr: str) -> None: + device_uri = urllib.parse.urlparse(endpoint).geturl() + if device_uri in WSDDiscoveredDevice.instances: + WSDDiscoveredDevice.instances[device_uri].update(meta, xaddr, self.mch.address.interface) + else: + WSDDiscoveredDevice.instances[device_uri] = WSDDiscoveredDevice(meta, xaddr, self.mch.address.interface) + + def remove_outdated_probes(self) -> None: + cut = time.time() - PROBE_TIMEOUT * 2 + self.probes = dict(filter(lambda x: x[1] > cut, self.probes.items())) + + def add_header_elements(self, header: ElementTree.Element, extra: Any) -> None: + action_str = extra + if action_str == WSD_GET: + reply_to = ElementTree.SubElement(header, 'wsa:ReplyTo') + addr = ElementTree.SubElement(reply_to, 'wsa:Address') + addr.text = WSA_ANON + + wsa_from = ElementTree.SubElement(header, 'wsa:From') + addr = ElementTree.SubElement(wsa_from, 'wsa:Address') + addr.text = args.uuid.urn + + +class WSDHost(WSDUDPMessageHandler): + """Class for handling WSD requests coming from UDP datagrams.""" + + message_number: ClassVar[int] = 0 + instances: ClassVar[List['WSDHost']] = [] + + def __init__(self, mch: MulticastHandler) -> None: + super().__init__(mch) + + WSDHost.instances.append(self) + + self.mch.add_handler(self.mch.recv_socket, self) + + self.handlers[WSD_PROBE] = self.handle_probe + self.handlers[WSD_RESOLVE] = self.handle_resolve + + self.send_hello() + + def cleanup(self) -> None: + super().cleanup() + WSDHost.instances.remove(self) + + def teardown(self) -> None: + super().teardown() + self.send_bye() + + def handle_packet(self, msg: str, src: UdpAddress) -> None: + reply = self.handle_message(msg, src) + if reply: + self.enqueue_datagram(reply, src) + + def send_hello(self) -> None: + """WS-Discovery, Section 4.1, Hello message""" + hello = ElementTree.Element('wsd:Hello') + self.add_endpoint_reference(hello) + # THINK: Microsoft does not send the transport address here due to privacy reasons. Could make this optional. + self.add_xaddr(hello, self.mch.address.transport_str) + self.add_metadata_version(hello) + + msg = self.build_message(WSA_DISCOVERY, WSD_HELLO, None, hello) + self.enqueue_datagram(msg, self.mch.multicast_address, msg_type='Hello') + + def send_bye(self) -> None: + """WS-Discovery, Section 4.2, Bye message""" + bye = ElementTree.Element('wsd:Bye') + self.add_endpoint_reference(bye) + + msg = self.build_message(WSA_DISCOVERY, WSD_BYE, None, bye) + self.enqueue_datagram(msg, self.mch.multicast_address, msg_type='Bye') + + def handle_probe(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]: + probe = body.find('./wsd:Probe', namespaces) + if probe is None: + return None + + scopes = probe.find('./wsd:Scopes', namespaces) + + if scopes: + # THINK: send fault message (see p. 21 in WSD) + logger.debug('scopes ({}) unsupported but probed'.format(scopes)) + return None + + types_elem = probe.find('./wsd:Types', namespaces) + if types_elem is None: + logger.debug('Probe message lacks wsd:Types element. Ignored.') + return None + + types = types_elem.text + if not types == WSD_TYPE_DEVICE: + logger.debug('unknown discovery type ({}) for probe'.format(types)) + return None + + matches = ElementTree.Element('wsd:ProbeMatches') + match = ElementTree.SubElement(matches, 'wsd:ProbeMatch') + self.add_endpoint_reference(match) + self.add_types(match) + self.add_metadata_version(match) + + return matches, WSD_PROBE_MATCH + + def handle_resolve(self, header: ElementTree.Element, body: ElementTree.Element) -> Optional[WSDMessage]: + resolve = body.find('./wsd:Resolve', namespaces) + if resolve is None: + return None + + addr = resolve.find('./wsa:EndpointReference/wsa:Address', namespaces) + if addr is None: + logger.debug('invalid resolve request: missing endpoint address') + return None + + if not addr.text == args.uuid.urn: + logger.debug('invalid resolve request: address ({}) does not match own one ({})'.format( + addr.text, args.uuid.urn)) + return None + + matches = ElementTree.Element('wsd:ResolveMatches') + match = ElementTree.SubElement(matches, 'wsd:ResolveMatch') + self.add_endpoint_reference(match) + self.add_types(match) + self.add_xaddr(match, self.mch.address.transport_str) + self.add_metadata_version(match) + + return matches, WSD_RESOLVE_MATCH + + def add_header_elements(self, header: ElementTree.Element, extra: Any): + ElementTree.SubElement(header, 'wsd:AppSequence', { + 'InstanceId': str(wsd_instance_id), + 'SequenceId': uuid.uuid1().urn, + 'MessageNumber': str(type(self).message_number)}) + + type(self).message_number += 1 + + +class WSDHttpMessageHandler(WSDMessageHandler): + + def __init__(self) -> None: + super().__init__() + + self.handlers[WSD_GET] = self.handle_get + + def handle_get(self, header: ElementTree.Element, body: ElementTree.Element) -> WSDMessage: + # see https://msdn.microsoft.com/en-us/library/hh441784.aspx for an + # example. Some of the properties below might be made configurable + # in future releases. + metadata = ElementTree.Element('wsx:Metadata') + section = ElementTree.SubElement(metadata, 'wsx:MetadataSection', {'Dialect': WSDP_URI + '/ThisDevice'}) + device = ElementTree.SubElement(section, 'wsdp:ThisDevice') + ElementTree.SubElement(device, 'wsdp:FriendlyName').text = ('WSD Device {0}'.format(args.hostname)) + ElementTree.SubElement(device, 'wsdp:FirmwareVersion').text = '1.0' + ElementTree.SubElement(device, 'wsdp:SerialNumber').text = '1' + + section = ElementTree.SubElement(metadata, 'wsx:MetadataSection', {'Dialect': WSDP_URI + '/ThisModel'}) + model = ElementTree.SubElement(section, 'wsdp:ThisModel') + ElementTree.SubElement(model, 'wsdp:Manufacturer').text = 'wsdd' + ElementTree.SubElement(model, 'wsdp:ModelName').text = 'wsdd' + ElementTree.SubElement(model, 'pnpx:DeviceCategory').text = 'Computers' + + section = ElementTree.SubElement(metadata, 'wsx:MetadataSection', {'Dialect': WSDP_URI + '/Relationship'}) + rel = ElementTree.SubElement(section, 'wsdp:Relationship', {'Type': WSDP_URI + '/host'}) + host = ElementTree.SubElement(rel, 'wsdp:Host') + self.add_endpoint_reference(host) + ElementTree.SubElement(host, 'wsdp:Types').text = PUB_COMPUTER + ElementTree.SubElement(host, 'wsdp:ServiceId').text = args.uuid.urn + + fmt = '{0}/Domain:{1}' if args.domain else '{0}/Workgroup:{1}' + value = args.domain if args.domain else args.workgroup.upper() + if args.domain: + dh = args.hostname if args.preserve_case else args.hostname.lower() + else: + dh = args.hostname if args.preserve_case else args.hostname.upper() + + ElementTree.SubElement(host, PUB_COMPUTER).text = fmt.format(dh, value) + + return metadata, WSD_GET_RESPONSE + + +class WSDHttpServer(http.server.HTTPServer): + """ HTTP server both with IPv6 support and WSD handling """ + + mch: MulticastHandler + aio_loop: asyncio.AbstractEventLoop + wsd_handler: WSDHttpMessageHandler + registered: bool + + def __init__(self, mch: MulticastHandler, aio_loop: asyncio.AbstractEventLoop): + # hacky way to convince HTTP/SocketServer of the address family + type(self).address_family = mch.address.family + + self.mch = mch + self.aio_loop = aio_loop + self.wsd_handler = WSDHttpMessageHandler() + self.registered = False + + # WSDHttpRequestHandler is a BaseHTTPRequestHandler. Passing to the parent constructor is therefore safe and + # we can ignore the type error reported by mypy + super().__init__(mch.listen_address, WSDHttpRequestHandler) # type: ignore + + def server_bind(self) -> None: + if self.mch.address.family == socket.AF_INET6: + self.socket.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1) + + super().server_bind() + + def server_activate(self) -> None: + super().server_activate() + self.aio_loop.add_reader(self.fileno(), self.handle_request) + self.registered = True + + def server_close(self) -> None: + if self.registered: + self.aio_loop.remove_reader(self.fileno()) + super().server_close() + + +class WSDHttpRequestHandler(http.server.BaseHTTPRequestHandler): + """Class for handling WSD requests coming over HTTP""" + + def log_message(self, fmt, *args) -> None: + logger.info("{} - - ".format(self.address_string()) + fmt % args) + + def do_POST(self) -> None: + if self.path != '/' + str(args.uuid): + self.send_error(http.HTTPStatus.NOT_FOUND) + + ct = self.headers['Content-Type'] + if ct is None or not ct.startswith(MIME_TYPE_SOAP_XML): + self.send_error(http.HTTPStatus.BAD_REQUEST, 'Invalid Content-Type') + + content_length = int(self.headers['Content-Length']) + body = self.rfile.read(content_length) + + response = self.server.wsd_handler.handle_message(body) # type: ignore + if response: + self.send_response(http.HTTPStatus.OK) + self.send_header('Content-Type', MIME_TYPE_SOAP_XML) + self.end_headers() + self.wfile.write(response.encode('utf-8')) + else: + self.send_error(http.HTTPStatus.BAD_REQUEST) + + +class ApiServer: + + address_monitor: 'NetworkAddressMonitor' + clients: List[asyncio.StreamWriter] + + def __init__(self, aio_loop: asyncio.AbstractEventLoop, listen_address: Any, + address_monitor: 'NetworkAddressMonitor') -> None: + self.server = None + self.clients = [] + self.address_monitor = address_monitor + + # defer server creation + self.create_task = aio_loop.create_task(self.create_server(aio_loop, listen_address)) + + async def create_server(self, aio_loop: asyncio.AbstractEventLoop, listen_address: Any) -> None: + + # It appears mypy is not able to check the argument to create_task and the return value of start_server + # correctly. The docs say start_server returns a coroutine and the create_task takes a coro. And: It works. + # Thus, we ignore type errors here. + if isinstance(listen_address, socket.SocketType): + # create socket from systemd file descriptor/socket + self.server = await aio_loop.create_task(asyncio.start_unix_server( # type: ignore + self.on_connect, sock=listen_address)) + elif isinstance(listen_address, int) or listen_address.isnumeric(): + self.server = await aio_loop.create_task(asyncio.start_server( # type: ignore + self.on_connect, host='localhost', port=int(listen_address), reuse_address=True, + reuse_port=True)) + else: + self.server = await aio_loop.create_task(asyncio.start_unix_server( # type: ignore + self.on_connect, path=listen_address)) + + async def on_connect(self, read_stream: asyncio.StreamReader, write_stream: asyncio.StreamWriter) -> None: + self.clients.append(write_stream) + while True: + try: + line = await read_stream.readline() + if line: + self.handle_command(str(line.strip(), 'utf-8'), write_stream) + if not write_stream.is_closing(): + await write_stream.drain() + else: + self.clients.remove(write_stream) + write_stream.close() + return + except UnicodeDecodeError as e: + logger.debug('invalid input utf8', e) + except Exception as e: + logger.warning('exception in API client', e) + self.clients.remove(write_stream) + write_stream.close() + return + + def handle_command(self, line: str, write_stream: asyncio.StreamWriter) -> None: + words = line.split() + if len(words) == 0: + return + + command = words[0] + command_args = words[1:] + if command == 'probe' and args.discovery: + intf = command_args[0] if command_args else None + logger.debug('probing devices on {} upon request'.format(intf)) + for client in self.get_clients_by_interface(intf): + client.send_probe() + elif command == 'clear' and args.discovery: + logger.debug('clearing list of known devices') + WSDDiscoveredDevice.instances.clear() + elif command == 'list' and args.discovery: + wsd_type = command_args[0] if command_args else None + write_stream.write(bytes(self.get_list_reply(wsd_type), 'utf-8')) + elif command == 'quit': + write_stream.close() + elif command == 'start': + self.address_monitor.enumerate() + elif command == 'stop': + self.address_monitor.teardown() + else: + logger.debug('could not handle API request: {}'.format(line)) + + def get_clients_by_interface(self, interface: Optional[str]) -> List[WSDClient]: + return [c for c in WSDClient.instances if c.mch.address.interface.name == interface or not interface] + + def get_list_reply(self, wsd_type: Optional[str]) -> str: + retval = '' + for dev_uri, dev in WSDDiscoveredDevice.instances.items(): + if wsd_type and (wsd_type not in dev.types): + continue + + addrs_str = [] + for addrs in dev.addresses.items(): + addrs_str.append(', '.join(['{}'.format(a) for a in addrs])) + + retval = retval + '{}\t{}\t{}\t{}\t{}\t{}\n'.format( + dev_uri, + dev.display_name, + dev.props['BelongsTo'] if 'BelongsTo' in dev.props else '', + datetime.datetime.fromtimestamp(dev.last_seen).isoformat('T', 'seconds'), + ','.join(addrs_str), + ','.join(dev.types)) + + retval += '.\n' + return retval + + async def cleanup(self) -> None: + # ensure the server is not created after we have teared down + await self.create_task + if self.server: + self.server.close() + for client in self.clients: + client.close() + await self.server.wait_closed() + + +class MetaEnumAfterInit(type): + + def __call__(cls, *cargs, **kwargs): + obj = super().__call__(*cargs, **kwargs) + if not args.no_autostart: + obj.enumerate() + return obj + + +class NetworkAddressMonitor(metaclass=MetaEnumAfterInit): + """ + Observes changes of network addresses, handles addition and removal of + network addresses, and filters for addresses/interfaces that are or are not + handled. The actual OS-specific implementation that detects the changes is + done in subclasses. This class is used as a singleton + """ + + instance: ClassVar[object] = None + + interfaces: Dict[int, NetworkInterface] + aio_loop: asyncio.AbstractEventLoop + mchs: List[MulticastHandler] + http_servers: List[WSDHttpServer] + teardown_tasks: List[asyncio.Task] + active: bool + + def __init__(self, aio_loop: asyncio.AbstractEventLoop) -> None: + + if NetworkAddressMonitor.instance is not None: + raise RuntimeError('Instance of NetworkAddressMonitor already created') + + NetworkAddressMonitor.instance = self + + self.interfaces = {} + self.aio_loop = aio_loop + + self.mchs = [] + self.http_servers = [] + self.teardown_tasks = [] + + self.active = False + + def enumerate(self) -> None: + """ + Performs an initial enumeration of addresses and sets up everything + for observing future changes. + """ + if self.active: + return + + self.active = True + self.do_enumerate() + + def do_enumerate(self) -> None: + pass + + def handle_change(self) -> None: + """ handle network change message """ + pass + + def add_interface(self, interface: NetworkInterface) -> NetworkInterface: + # TODO: Cleanup + if interface.index in self.interfaces: + pass + # self.interfaces[idx].name = name + else: + self.interfaces[interface.index] = interface + + return self.interfaces[interface.index] + + def get_handled_address_families(self) -> Set[int]: + """ get a set of handles address families for filtering during enumeration """ + if not self.active: + return set() + + if args.ipv4only: + return {socket.AF_INET} + if args.ipv6only: + return {socket.AF_INET6} + + return {socket.AF_INET, socket.AF_INET6} + + def is_address_handled(self, address: NetworkAddress) -> bool: + # do not handle anything when we are not active + if not self.active: + return False + + if not address.is_multicastable: + return False + + # Use interface only if it's in the list of user-provided interface names + if ((args.interface) and (address.interface.name not in args.interface) + and (address.address_str not in args.interface)): + return False + + return True + + def handle_new_address(self, address: NetworkAddress) -> None: + logger.debug('new address {}'.format(address)) + + if not self.is_address_handled(address): + logger.debug('ignoring that address on {}'.format(address.interface)) + return + + # filter out what is not wanted + # Ignore addresses or interfaces we already handle. There can only be + # one multicast handler per address family and network interface + for mch in self.mchs: + if mch.handles_address(address): + return + + logger.debug('handling traffic for {}'.format(address)) + mch = MulticastHandler(address, self.aio_loop) + self.mchs.append(mch) + + if not args.no_host: + WSDHost(mch) + if not args.no_http: + self.http_servers.append(WSDHttpServer(mch, self.aio_loop)) + + if args.discovery: + WSDClient(mch) + + def handle_deleted_address(self, address: NetworkAddress) -> None: + logger.info('deleted address {}'.format(address)) + + if not self.is_address_handled(address): + return + + mch: Optional[MulticastHandler] = self.get_mch_by_address(address) + if mch is None: + return + + # Do not tear the client/hosts down. Saying goodbye does not work + # because the address is already gone (at least on Linux). + for c in WSDClient.instances: + if c.mch == mch: + c.cleanup() + break + for h in WSDHost.instances: + if h.mch == mch: + h.cleanup() + break + for s in self.http_servers: + if s.mch == mch: + s.server_close() + self.http_servers.remove(s) + + mch.cleanup() + self.mchs.remove(mch) + + def teardown(self) -> None: + if not self.active: + return + + self.active = False + + # return if we are still in tear down process + if len(self.teardown_tasks) > 0: + return + + for h in WSDHost.instances: + h.teardown() + h.cleanup() + self.teardown_tasks.extend(h.pending_tasks) + + for c in WSDClient.instances: + c.teardown() + c.cleanup() + self.teardown_tasks.extend(c.pending_tasks) + + for s in self.http_servers: + s.server_close() + + self.http_servers.clear() + + if not self.teardown_tasks: + return + + if not self.aio_loop.is_running(): + # Wait here for all pending tasks so that the main loop can be finished on termination. + self.aio_loop.run_until_complete(asyncio.gather(*self.teardown_tasks)) + else: + for t in self.teardown_tasks: + t.add_done_callback(self.mch_teardown) + + def mch_teardown(self, task) -> None: + if any([not t.done() for t in self.teardown_tasks]): + return + + self.teardown_tasks.clear() + + for mch in self.mchs: + mch.cleanup() + self.mchs.clear() + + def cleanup(self) -> None: + self.teardown() + + def get_mch_by_address(self, address: NetworkAddress) -> Optional[MulticastHandler]: + """ + Get the MCI for the address, its family and the interface. + adress must be given as a string. + """ + for retval in self.mchs: + if retval.handles_address(address): + return retval + + return None + + +# from rtnetlink.h +RTMGRP_LINK: int = 1 +RTMGRP_IPV4_IFADDR: int = 0x10 +RTMGRP_IPV6_IFADDR: int = 0x100 + +# from netlink.h (struct nlmsghdr) +NLM_HDR_DEF: str = '@IHHII' + +NLM_F_REQUEST: int = 0x01 +NLM_F_ROOT: int = 0x100 +NLM_F_MATCH: int = 0x200 +NLM_F_DUMP: int = NLM_F_ROOT | NLM_F_MATCH + +# self defines +NLM_HDR_ALIGNTO: int = 4 + +# ifa flags +IFA_F_DADFAILED: int = 0x08 +IFA_F_HOMEADDRESS: int = 0x10 +IFA_F_DEPRECATED: int = 0x20 +IFA_F_TENTATIVE: int = 0x40 + +# from if_addr.h (struct ifaddrmsg) +IFADDR_MSG_DEF: str = '@BBBBI' +IFA_ADDRESS: int = 1 +IFA_LOCAL: int = 2 +IFA_LABEL: int = 3 +IFA_FLAGS: int = 8 +IFA_MSG_LEN: int = 8 + +RTA_ALIGNTO: int = 4 +RTA_LEN: int = 4 + + +def align_to(x: int, n: int) -> int: + return ((x + n - 1) // n) * n + + +class NetlinkAddressMonitor(NetworkAddressMonitor): + """ + Implementation of the AddressMonitor for Netlink sockets, i.e. Linux + """ + + RTM_NEWADDR: int = 20 + RTM_DELADDR: int = 21 + RTM_GETADDR: int = 22 + + socket: socket.socket + + def __init__(self, aio_loop: asyncio.AbstractEventLoop) -> None: + super().__init__(aio_loop) + + rtm_groups = RTMGRP_LINK + if not args.ipv4only: + rtm_groups = rtm_groups | RTMGRP_IPV6_IFADDR + if not args.ipv6only: + rtm_groups = rtm_groups | RTMGRP_IPV4_IFADDR + + self.socket = socket.socket(socket.AF_NETLINK, socket.SOCK_RAW, socket.NETLINK_ROUTE) + self.socket.bind((0, rtm_groups)) + self.aio_loop.add_reader(self.socket.fileno(), self.handle_change) + + self.NLM_HDR_LEN = struct.calcsize(NLM_HDR_DEF) + + def do_enumerate(self) -> None: + super().do_enumerate() + + kernel = (0, 0) + # Append an unsigned byte to the header for the request. + req = struct.pack(NLM_HDR_DEF + 'B', self.NLM_HDR_LEN + 1, self.RTM_GETADDR, + NLM_F_REQUEST | NLM_F_DUMP, 1, 0, socket.AF_PACKET) + self.socket.sendto(req, kernel) + + def handle_change(self) -> None: + super().handle_change() + + buf, src = self.socket.recvfrom(4096) + logger.debug('netlink message with {} bytes'.format(len(buf))) + handled_families = self.get_handled_address_families() + + offset = 0 + while offset < len(buf): + h_len, h_type, _, _, _ = struct.unpack_from(NLM_HDR_DEF, buf, offset) + offset += self.NLM_HDR_LEN + + msg_len = h_len - self.NLM_HDR_LEN + if msg_len < 0: + break + + if h_type != self.RTM_NEWADDR and h_type != self.RTM_DELADDR: + logger.debug('invalid rtm_message type {}'.format(h_type)) + offset += align_to(msg_len, NLM_HDR_ALIGNTO) + continue + + # decode ifaddrmsg as in if_addr.h + ifa_family, _, ifa_flags, ifa_scope, ifa_idx = struct.unpack_from(IFADDR_MSG_DEF, buf, offset) + if ifa_family not in handled_families: + offset += align_to(msg_len, NLM_HDR_ALIGNTO) + logger.debug('ignore address with wrong address family {}'.format(ifa_family)) + continue + + if ((ifa_flags & IFA_F_DADFAILED) or (ifa_flags & IFA_F_HOMEADDRESS) + or (ifa_flags & IFA_F_DEPRECATED) or (ifa_flags & IFA_F_TENTATIVE)): + logger.debug('ignore address with invalid state {}'.format(hex(ifa_flags))) + offset += align_to(msg_len, NLM_HDR_ALIGNTO) + continue + + logger.debug('RTM new/del addr family: {} flags: {} scope: {} idx: {}'.format( + ifa_family, ifa_flags, ifa_scope, ifa_idx)) + addr = None + i = offset + IFA_MSG_LEN + while i - offset < msg_len: + attr_len, attr_type = struct.unpack_from('HH', buf, i) + logger.debug('rt_attr {} {}'.format(attr_len, attr_type)) + + if attr_len < RTA_LEN: + logger.debug('invalid rtm_attr_len. skipping remainder') + break + + if attr_type == IFA_LABEL: + name, = struct.unpack_from(str(attr_len - 4 - 1) + 's', buf, i + 4) + self.add_interface(NetworkInterface(name.decode(), ifa_scope, ifa_idx)) + elif attr_type == IFA_LOCAL and ifa_family == socket.AF_INET: + addr = buf[i + 4:i + 4 + 4] + elif attr_type == IFA_ADDRESS and ifa_family == socket.AF_INET6: + addr = buf[i + 4:i + 4 + 16] + elif attr_type == IFA_FLAGS: + _, ifa_flags = struct.unpack_from('HI', buf, i) + i += align_to(attr_len, RTA_ALIGNTO) + + if addr is None: + logger.debug('no address in RTM message') + offset += align_to(msg_len, NLM_HDR_ALIGNTO) + continue + + # In case of IPv6 only addresses, there appears to be no IFA_LABEL + # message. Therefore, the name is requested by other means (#94) + if ifa_idx not in self.interfaces: + try: + logger.debug('unknown interface name for idx {}. resolving manually'.format(ifa_idx)) + if_name = socket.if_indextoname(ifa_idx) + self.add_interface(NetworkInterface(if_name, ifa_scope, ifa_idx)) + except OSError: + logger.exception('interface detection failed') + # accept this exception (which should not occur) + pass + + # In case really strange things happen and we could not find out the + # interface name for the returned ifa_idx, we... log a message. + if ifa_idx in self.interfaces: + address = NetworkAddress(ifa_family, addr, self.interfaces[ifa_idx]) + if h_type == self.RTM_NEWADDR: + self.handle_new_address(address) + elif h_type == self.RTM_DELADDR: + self.handle_deleted_address(address) + else: + logger.debug('unknown interface index: {}'.format(ifa_idx)) + + offset += align_to(msg_len, NLM_HDR_ALIGNTO) + + def cleanup(self) -> None: + self.aio_loop.remove_reader(self.socket.fileno()) + self.socket.close() + super().cleanup() + + +# from sys/net/route.h +RTA_IFA: int = 0x20 + +# from sys/socket.h +CTL_NET: int = 4 +NET_RT_IFLIST: int = 3 + +# from sys/net/if.h +IFF_LOOPBACK: int = 0x8 +IFF_MULTICAST: int = 0x800 if platform.system() != 'OpenBSD' else 0x8000 + +# sys/netinet6/in6_var.h +IN6_IFF_TENTATIVE: int = 0x02 +IN6_IFF_DUPLICATED: int = 0x04 +IN6_IFF_NOTREADY: int = IN6_IFF_TENTATIVE | IN6_IFF_DUPLICATED + +SA_ALIGNTO: int = ctypes.sizeof(ctypes.c_long) if platform.system() != "Darwin" else ctypes.sizeof(ctypes.c_uint32) + + +class RouteSocketAddressMonitor(NetworkAddressMonitor): + """ + Implementation of the AddressMonitor for FreeBSD and Darwin using route sockets + """ + + # Common definition for beginning part of if(m?a)?_msghdr structs (see net/if.h/man 4 route). + IF_COMMON_HDR_DEF = '@HBBii' if platform.system() != 'OpenBSD' else '@HBBHHHBBiii' + + # from net/if.h + RTM_NEWADDR: int = 0xC + RTM_DELADDR: int = 0xD + # not tested for OpenBSD + RTM_IFINFO: int = 0xE + + # from route.h (value equals for FreeBSD, Darwin and OpenBSD) + RTM_VERSION: int = 0x5 + + # from net/if.h (struct ifa_msghdr) + IFA_MSGHDR_DEF: str = IF_COMMON_HDR_DEF + ('hi' if platform.system() != 'OpenBSD' else '') + IFA_MSGHDR_SIZE: int = struct.calcsize(IFA_MSGHDR_DEF) + + # The struct package does not allow to specify those, thus we hard code them as chars (x4). + IF_MSG_DEFS: Dict[str, str] = { + # if_data in if_msghdr is prepended with an u_short _ifm_spare1, thus the 'H' a the beginning) + 'FreeBSD': 'hH6c2c8c8c104c8c16c', + # There are 8 bytes and 22 uint32_t in the if_data struct (22 x 4 Bytes + 8 = 96 Bytes) + # It is also aligned on 4-byte boundary necessitating 2 bytes padding inside if_msghdr + 'Darwin': 'h2c8c22I', + # struct if_data from /src/sys/net/if.h for if_msghdr + # (includes struct timeval which is a int64 + long + 'OpenBSD': '4c3I13Q1Iql' + } + + socket: socket.socket + intf_blacklist: List[str] + + is_openbsd: bool = False + + def __init__(self, aio_loop: asyncio.AbstractEventLoop) -> None: + super().__init__(aio_loop) + self.intf_blacklist = [] + + # Create routing socket to get notified about future changes. + # Do this before fetching the current routing information to avoid race condition. + self.socket = socket.socket(socket.AF_ROUTE, socket.SOCK_RAW, socket.AF_UNSPEC) + self.aio_loop.add_reader(self.socket.fileno(), self.handle_change) + + self.IF_MSGHDR_SIZE = struct.calcsize(self.IF_COMMON_HDR_DEF + self.IF_MSG_DEFS[platform.system()]) + self.is_openbsd = platform.system() == 'OpenBSD' + + def do_enumerate(self) -> None: + super().do_enumerate() + mib = [CTL_NET, socket.AF_ROUTE, 0, 0, NET_RT_IFLIST, 0] + rt_mib = (ctypes.c_int * len(mib))() + rt_mib[:] = [ctypes.c_int(m) for m in mib] + + libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True) + + # Ask kernel for routing table size first. + rt_size = ctypes.c_size_t() + if libc.sysctl(ctypes.byref(rt_mib), ctypes.c_size_t(len(rt_mib)), 0, ctypes.byref(rt_size), 0, 0): + raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno())) + + # Get the initial routing (interface list) data. + rt_buf = ctypes.create_string_buffer(rt_size.value) + if libc.sysctl(ctypes.byref(rt_mib), ctypes.c_size_t(len(rt_mib)), rt_buf, ctypes.byref(rt_size), 0, 0): + raise OSError(ctypes.get_errno(), os.strerror(ctypes.get_errno())) + + self.parse_route_socket_response(rt_buf.raw, True) + + def handle_change(self) -> None: + super().handle_change() + + self.parse_route_socket_response(self.socket.recv(4096), False) + + def parse_route_socket_response(self, buf: bytes, keep_intf: bool) -> None: + offset = 0 + + intf = None + intf_flags = 0 + while offset < len(buf): + # unpack route message response + if not self.is_openbsd: + rtm_len, rtm_version, rtm_type, addr_mask, flags = struct.unpack_from( + self.IF_COMMON_HDR_DEF, buf, offset) + else: + rtm_len, rtm_version, rtm_type, ifa_hdr_len, _, _, _, _, addr_mask, flags, _ = struct.unpack_from( + self.IF_COMMON_HDR_DEF, buf, offset) + + # exit condition for OpenBSD where always the complete buffer (ie 4096 bytes) is returned + if rtm_len == 0: + break + + # skip over non-understood packets and versions + if (rtm_type not in [self.RTM_NEWADDR, self.RTM_DELADDR, self.RTM_IFINFO]) or ( + rtm_version != self.RTM_VERSION): + offset += rtm_len + continue + + if rtm_type == self.RTM_IFINFO: + intf_flags = flags + + sa_offset = offset + (self.IF_MSGHDR_SIZE if rtm_type == self.RTM_IFINFO else self.IFA_MSGHDR_SIZE) + + # For a route socket message, and different to a sysctl response, + # the link info is stored inside the same rtm message, so it has to + # survive multiple rtm messages in such cases + if not keep_intf: + intf = None + + new_intf = self.parse_addrs(buf, sa_offset, offset + rtm_len, intf, addr_mask, rtm_type, intf_flags) + intf = new_intf if new_intf else intf + + offset += rtm_len + + def clear_addr_scope(self, raw_addr: bytes) -> bytes: + addr: bytearray = bytearray(raw_addr) + # adapted from in6_clearscope BSD/Mac kernel method (see scope6.c) + if addr[0] == 0xfe and (addr[1] & 0xc0) == 0x80: + addr[2] = 0 + addr[3] = 0 + + return bytes(addr) + + def parse_addrs(self, buf: bytes, offset: int, limit: int, intf: Optional[NetworkInterface], addr_mask: int, + rtm_type: int, flags: int) -> Optional[NetworkInterface]: + addr_type_idx = 1 + addr = None + addr_family: int = socket.AF_UNSPEC + + handled_families = self.get_handled_address_families() + + while offset < limit: + while not (addr_type_idx & addr_mask) and (addr_type_idx <= addr_mask): + addr_type_idx = addr_type_idx << 1 + + sa_len, sa_fam = struct.unpack_from('@BB', buf, offset) + if sa_fam in handled_families and addr_type_idx == RTA_IFA: + addr_family = sa_fam + addr_offset = 4 if sa_fam == socket.AF_INET else 8 + addr_length = 4 if sa_fam == socket.AF_INET else 16 + addr_start = offset + addr_offset + addr = buf[addr_start:addr_start + addr_length] + if sa_fam == socket.AF_INET6: + addr = self.clear_addr_scope(addr) + elif sa_fam == socket.AF_LINK: # type: ignore[attr-defined] + idx, _, name_len = struct.unpack_from('@HBB', buf, offset + 2) + if idx > 0: + off_name = offset + 8 + if_name = (buf[off_name:off_name + name_len]).decode() + intf = self.add_interface(NetworkInterface(if_name, idx, idx)) + + offset += align_to(sa_len, SA_ALIGNTO) if sa_len > 0 else SA_ALIGNTO + addr_type_idx = addr_type_idx << 1 + + if rtm_type == self.RTM_IFINFO and intf is not None: + if flags & IFF_LOOPBACK or not flags & IFF_MULTICAST: + self.intf_blacklist.append(intf.name) + elif intf.name in self.intf_blacklist: + self.intf_blacklist.remove(intf.name) + + if intf is None or intf.name in self.intf_blacklist or addr is None: + return intf + + address = NetworkAddress(addr_family, addr, intf) + if rtm_type == self.RTM_DELADDR: + self.handle_deleted_address(address) + else: + # Too bad, the address may be unuseable (tentative, e.g.) here + # but we won't get any further notifcation about the address being + # available for use. Thus, we try and may fail here + self.handle_new_address(address) + + return intf + + def cleanup(self) -> None: + self.aio_loop.remove_reader(self.socket.fileno()) + self.socket.close() + super().cleanup() + + +class DladmAddressMonitor(NetworkAddressMonitor): + + class sockaddr(ctypes.Structure): + _fields_ = [("family", ctypes.c_ushort), + ("dummy", ctypes.c_ushort), + ("data", ctypes.c_ubyte * 14)] + + class ifaddrs(ctypes.Structure): + pass + + ifaddrs._fields_ = [("next", ctypes.POINTER(ifaddrs)), + ("name", ctypes.c_char_p), + ("flags", ctypes.c_ulonglong), + ("addr", ctypes.POINTER(sockaddr)), + ("netmask", ctypes.POINTER(sockaddr)), + ("dstaddr", ctypes.POINTER(sockaddr)), + ("data", ctypes.c_void_p)] + + def freeifaddrs(self, ifa) -> None: + libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True) + while ifa.next: + curr = ifa + ifa = ifa.next[0] + libc.free(curr.name) + libc.free(curr.addr) + libc.free(curr.netmask) + libc.free(curr.dstaddr) + libc.free(curr.data) + del curr + + def do_enumerate(self) -> None: + super().do_enumerate() + libsocket = ctypes.CDLL(ctypes.util.find_library('socket'), use_errno=True) + ifas = self.ifaddrs() + handled_families = self.get_handled_address_families() + if libsocket.getifaddrs(ctypes.byref(ifas)) == 0: + ifa = ifas + ifa_idx = 0 + while ifa.next: + if ifa.name: + if ifa.addr[0].family not in handled_families: + ifa = ifa.next[0] + ifa_idx += 1 + continue + + logger.debug("{}%{}".format( + socket.inet_ntop(ifa.addr[0].family, bytes(ifa.addr[0].data[:4])), + ifa.name.decode())) + addr = socket.inet_ntop(ifa.addr[0].family, bytes(ifa.addr[0].data[:4])) + intf = NetworkInterface(ifa.name.decode(), 0, ifa_idx) + self.add_interface(intf) + self.handle_new_address(NetworkAddress(ifa.addr[0].family, addr, intf)) + ifa_idx += 1 + + ifa = ifa.next[0] + self.freeifaddrs(ifas) + + +def sigterm_handler() -> None: + logger.info('received termination/interrupt signal, tearing down') + # implictely raise SystemExit to cleanup properly + sys.exit(0) + + +def parse_args() -> None: + global args, logger + + parser = argparse.ArgumentParser() + + parser.add_argument( + '-i', '--interface', + help='interface or address to use', + action='append', default=[]) + parser.add_argument( + '-H', '--hoplimit', + help='hop limit for multicast packets (default = 1)', type=int, + default=1) + parser.add_argument( + '-U', '--uuid', + help='UUID for the target device', + default=None) + parser.add_argument( + '-v', '--verbose', + help='increase verbosity', + action='count', default=0) + parser.add_argument( + '-d', '--domain', + help='set domain name (disables workgroup)', + default=None) + parser.add_argument( + '-n', '--hostname', + help='override (NetBIOS) hostname to be used (default hostname)', + # use only the local part of a possible FQDN + default=socket.gethostname().partition('.')[0]) + parser.add_argument( + '-w', '--workgroup', + help='set workgroup name (default WORKGROUP)', + default='WORKGROUP') + parser.add_argument( + '-A', '--no-autostart', + help='do not start networking after launch', + action='store_true') + parser.add_argument( + '-t', '--no-http', + help='disable http service (for debugging, e.g.)', + action='store_true') + parser.add_argument( + '-4', '--ipv4only', + help='use only IPv4 (default = off)', + action='store_true') + parser.add_argument( + '-6', '--ipv6only', + help='use IPv6 (default = off)', + action='store_true') + parser.add_argument( + '-s', '--shortlog', + help='log only level and message', + action='store_true') + parser.add_argument( + '-p', '--preserve-case', + help='preserve case of the provided/detected hostname', + action='store_true') + parser.add_argument( + '-c', '--chroot', + help='directory to chroot into', + default=None) + parser.add_argument( + '-u', '--user', + help='drop privileges to user:group', + default=None) + parser.add_argument( + '-D', '--discovery', + help='enable discovery operation mode', + action='store_true') + parser.add_argument( + '-l', '--listen', + help='listen on path or localhost port in discovery mode', + default=None) + parser.add_argument( + '-o', '--no-host', + help='disable server mode operation (host will be undiscoverable)', + action='store_true') + parser.add_argument( + '-V', '--version', + help='show version number and exit', + action='store_true') + parser.add_argument( + '--metadata-timeout', + help='set timeout for HTTP-based metadata exchange', + default=2.0) + parser.add_argument( + '--source-port', + help='send multicast traffic/receive replies on this port', + type=int, + default=0) + + args = parser.parse_args(sys.argv[1:]) + + if args.version: + print('wsdd - Web Service Discovery Daemon, v{}'.format(WSDD_VERSION)) + sys.exit(0) + + if args.verbose == 1: + log_level = logging.INFO + elif args.verbose > 1: + log_level = logging.DEBUG + asyncio.get_event_loop().set_debug(True) + logging.getLogger("asyncio").setLevel(logging.DEBUG) + else: + log_level = logging.WARNING + + if args.shortlog: + fmt = '%(levelname)s: %(message)s' + else: + fmt = '%(asctime)s:%(name)s %(levelname)s(pid %(process)d): %(message)s' + + logging.basicConfig(level=log_level, format=fmt) + logger = logging.getLogger('wsdd') + + if not args.interface: + logger.warning('no interface given, using all interfaces') + + if not args.uuid: + def read_uuid_from_file(fn: str) -> Union[None, uuid.UUID]: + try: + with open(fn) as f: + s: str = f.readline().strip() + return uuid.UUID(s) + except Exception: + return None + + # machine uuid: try machine-id file first but also check for hostid (FreeBSD) + args.uuid = read_uuid_from_file('/etc/machine-id') or \ + read_uuid_from_file('/etc/hostid') or \ + uuid.uuid5(uuid.NAMESPACE_DNS, socket.gethostname()) + + logger.info('using pre-defined UUID {0}'.format(str(args.uuid))) + else: + args.uuid = uuid.UUID(args.uuid) + logger.info('user-supplied device UUID is {0}'.format(str(args.uuid))) + + for prefix, uri in namespaces.items(): + ElementTree.register_namespace(prefix, uri) + + +def chroot(root: str) -> bool: + """ + Chroot into a separate directory to isolate ourself for increased security. + """ + # preload for socket.gethostbyaddr() + import encodings.idna + + try: + os.chroot(root) + os.chdir('/') + logger.info('chrooted successfully to {}'.format(root)) + except Exception as e: + logger.error('could not chroot to {}: {}'.format(root, e)) + return False + + return True + + +def get_ids_from_userspec(user_spec: str) -> Tuple[int, int]: + uid: int + gid: int + try: + user, _, group = user_spec.partition(':') + + if user: + uid = pwd.getpwnam(user).pw_uid + + if group: + gid = grp.getgrnam(group).gr_gid + except Exception as e: + raise RuntimeError('could not get uid/gid for {}: {}'.format(user_spec, e)) + + return (uid, gid) + + +def drop_privileges(uid: int, gid: int) -> bool: + try: + if gid is not None: + os.setgid(gid) + os.setegid(gid) + logger.debug('switched uid to {}'.format(uid)) + + if uid is not None: + os.setuid(uid) + os.seteuid(uid) + logger.debug('switched gid to {}'.format(gid)) + + logger.info('running as {} ({}:{})'.format(args.user, uid, gid)) + except Exception as e: + logger.error('dropping privileges failed: {}'.format(e)) + return False + + return True + + +def create_address_monitor(system: str, aio_loop: asyncio.AbstractEventLoop) -> NetworkAddressMonitor: + if system == 'Linux': + return NetlinkAddressMonitor(aio_loop) + elif system in ['FreeBSD', 'Darwin', 'OpenBSD']: + return RouteSocketAddressMonitor(aio_loop) + elif system == 'SunOS': + return DladmAddressMonitor(aio_loop) + else: + raise NotImplementedError('unsupported OS: ' + system) + + +def main() -> int: + global logger, args # noqa: F824 + + parse_args() + + if args.ipv4only and args.ipv6only: + logger.error('Listening to no IP address family.') + return 4 + + aio_loop = asyncio.new_event_loop() + nm = create_address_monitor(platform.system(), aio_loop) + + api_server = None + if args.listen: + api_server = ApiServer(aio_loop, args.listen, nm) + elif 'systemd' in sys.modules: + fds = systemd.daemon.listen_fds() + if fds: + api_server = ApiServer(aio_loop, socket.socket(fileno=fds[0]), nm) + + # get uid:gid before potential chroot'ing + if args.user is not None: + ids = get_ids_from_userspec(args.user) + if not ids: + return 3 + + if args.chroot is not None: + if not chroot(args.chroot): + return 2 + + if args.user is not None: + if not drop_privileges(ids[0], ids[1]): + return 3 + + if args.chroot and (os.getuid() == 0 or os.getgid() == 0): + logger.warning('chrooted but running as root, consider -u option') + + # main loop, serve requests coming from any outbound socket + aio_loop.add_signal_handler(signal.SIGINT, sigterm_handler) + aio_loop.add_signal_handler(signal.SIGTERM, sigterm_handler) + try: + aio_loop.run_forever() + except (SystemExit, KeyboardInterrupt): + logger.info('shutting down gracefully...') + if api_server is not None: + aio_loop.run_until_complete(api_server.cleanup()) + + nm.cleanup() + aio_loop.stop() + except Exception: + logger.exception('error in main loop') + + logger.info('Done.') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/wsdd/usr/share/man/man8/wsdd.8 b/wsdd/usr/share/man/man8/wsdd.8 new file mode 100644 index 0000000..2af506f --- /dev/null +++ b/wsdd/usr/share/man/man8/wsdd.8 @@ -0,0 +1,261 @@ +.TH wsdd 8 +.SH NAME +wsdd \- A Web Service Discovery host and client daemon. +.SH SYNOPSIS +.B wsdd [\fBoptions\fR] +.SH DESCRIPTION +.PP +.B wsdd +implements both a Web Service Discovery (WSD) host and a WSD client daemon. The +host implementation enables (Samba) hosts, like your local NAS device, to be +found by Web Service Discovery clients like Windows. The client mode allows +searching for other WSD hosts on the local network. +.PP +The default mode of operation is the host mode. The client or discovery mode +must be enabled explictely. Unless configured otherwise, the host mode is always +active. Both modes can be used at the same time. +.SH OPTIONS +.SS General options +.TP +\fB\-4\fR, \fB\-\-ipv4only\fR +See below. +.TP +\fB\-6\fR, \fB\-\-ipv6only\fR +Restrict to the given address family. If both options are specified no +addreses will be available and wsdd will exit. +.TP +\fB\-A\fR, \fB\-\-no-autostart\fR +Do not start networking activities automatically when the program is started. +The API interface (see below) can be used to start and stop the networking +activities while the application is running. +.TP +\fB\-c \fIDIRECTORY\fR, \fB\-\-chroot \fIDIRECTORY\fR +chroot into the given \fIDIRECTORY\fR after initialization has been performed +and right before the handling of incoming messages starts. The new root directory +can be empty. Consider using the \fB-u\fR option as well. +.TP +\fB\-h\fR, \fB\-\-help\fR +Show help and exit. +.TP +\fB\-H \fIHOPLIMIT\fR, \fB\-\-hoplimit \fIHOPLIMIT\fR +Set the hop limit for multicast packets. The default is 1 which should +prevent packets from leaving the local network segment. +.TP +\fB\-i \fIINTERFACE/ADDRESS\fR, \fB\-\-interface \fIINTERFACE/ADDRESS\fR +Specify on which interfaces wsdd will be listening on. If no interfaces are +specified, all interfaces are used. Loop-back interfaces are never used, +even when explicitly specified. For interfaces with IPv6 addresses, +only link-local addresses will be used for announcing the host on the +network. This option can be provided multiple times in order to restrict +traffic to more than one interface. +This option also accepts IP addresses that the service should bind to. +For IPv6, only link local addresses are actually considered as noted above. +.TP +\fB\-\-metadata-timeout\ \fITIMEOUT\fR +Set the timeout for HTTP-based metadata exchange. Default is 2.0 seconds. +.TP +\fB\-\-source-port\ \fPORT\fR +Set the source port for outgoing multicast messages, so that replies will +use this as the destination port. +This is useful for firewalls that do not detect incoming unicast replies +to a multicast as part of the flow, so the port needs to be fixed in order +to be allowed manually. +.TP +\fB\-s\fR, \fB\-\-shortlog\fR +Use a shorter logging format that only includes the level and message. +This is useful in cases where the logging mechanism, like systemd on Linux, +automatically prepends a date and process name plus ID to the log message. +.TP +\fB\-u \fIUSER[:GROUP]\fR, \fB\-\-user \fIUSER[:GROUP]\fR +Change user (and group) when running before handling network packets. +Together with \fB\-c\fR this option can be used to increase security +if the execution environment, like the init system, cannot ensure this in +another way. +.TP +\fB\-U \fIUUID\fR, \fB\-\-uuid \fIUUID\fR +The WSD specification requires a device to have a unique address that is stable +across reboots or changes in networks. In the context of the standard, it is +assumed that this is something like a serial number. Wsdd attempts to read the +machine ID from /etc/machine-id and /etc/hostid (in that order) before +potentially chrooting in another environment. If reading the machine ID fails, +wsdd falls back to a version 5 UUID with the DNS namespace and the host name of +the local machine as inputs. Thus, the host name should be stable and not be +modified, e.g. by DHCP. However, if you want wsdd to use a specific UUID you +can use this option. +.TP +\fB\-v\fR, \fB\-\-verbose\fR +Additively increase verbosity of the log output. A single occurrence of +-v/--verbose sets the log level to INFO. More -v options set the log level +to DEBUG. +.TP +\fB\-V\fR, \fB\-\-version\fR +Show the version number and exit. +.SS Host Mode Options +.TP +\fB\-d \fIDOMAIN\fR, \fB\-\-domain \fIDOMAIN\fR +Assume that the host running wsdd joined an ADS domain. This will make +wsdd report the host being a domain member. It disables workgroup +membership reporting. The (provided) hostname is automatically converted +to lower case. Use the `-p` option to change this behavior. +.TP +\fB\-n \fIHOSTNAME\fR, \fB\-\-hostname \fIHOSTNAME\fR +Override the host name wsdd uses during discovery. By default the machine's +host name is used (look at hostname(1)). Only the host name part of a +possible FQDN will be used in the default case. +.TP +\fB\-o\fR, \fB\-\-no-host\fR +Disable host operation mode. If this option is provided, the host cannot be +discovered by other (Windows) hosts. It can be useful when client/discovery +mode is used and no announcement of the host that runs wsdd should be made. +.TP +\fB\-p\fR, \fB\-\-preserve-case\fR +Preserve the hostname as it is. Without this option, the hostname is +converted as follows. For workgroup environments (see -w) the hostname +is made upper case by default. Vice versa it is made lower case for usage +in domains (see -d). +.TP +\fB\-t\fR, \fB\-\-no-http\fR +Do not service HTTP requests of the WSD protocol. This option is intended +for debugging purposes where another process may handle the Get messages. +.TP +\fB\-w \fIWORKGROUP\fR, \fB\-\-workgroup \fIWORKGROUP\fR +By default wsdd reports the host is a member of a workgroup rather than a +domain (use the -d/--domain option to override this). With -w/--workgroup +the default workgroup name can be changed. The default work group name is +WORKGROUP. The (provided) hostname is automatically converted to upper +case. Use the `-p` option to change this behavior. +.SS Client/Discovery Mode Options +.TP +\fB\-D\fR, \fB\-\-discovery\fR +Enable discovery mode to search for other WSD hosts/servers. Found hosts +are logged with INFO priority. The server interface (see below) +can be used for a programatic interface. Refer to the man page for +details of the server interface. +.TP +\fB\-l \fIPATH/PORT\fR, \fB\-\-listen \fIPATH/PORT\fR +Specify the location of the socket for the server programming interface. +If the option value is numeric, it is interpreted as numeric port for a +TCP server port. Then, the server socket is bound to the localhost only. +If the option value is non-numeric, it is assumed to be a path to UNIX +domain socket to which a client can connect to. + +.SH EXAMPLE USAGE +.SS Handle traffic on eth0 and eth2 only, but only with IPv6 addresses + + wsdd \-i eth0 \-i eth2 \-6 + + or + + wsdd \-\-interface eth0 \-\-interface eth2 \-\-ipv6only +.SS Set the Workgroup according to smb.conf, be verbose, run with dropped privileges, and change the root directory to an (empty) directory + + SMB_GROUP=$(grep \-i '^\\s*workgroup\\s*=' smb.conf | cut \-f2 \-d= | tr \-d '[:blank:]') + + wsdd \-v \-w $SMB_GROUP -u daemon:daemon -c /var/run/wsdd/chroot +.SH FIREWALL SETUP +.PP +Traffic for the following ports, directions and addresses must be allowed: +.TP +- Incoming and outgoing traffic to udp/3702 with multicast destination: 239.255.255.250 for IPv4 and ff02::c for IPv6 +.TP +- Outgoing unicast traffic from udp/3702 +.TP +- Incoming traffic to tcp/5357 +.PP +You should further restrict the traffic to the (link-)local subnet, e.g. by +using the `fe80::/10` address space for IPv6. Please note that IGMP traffic +must be enabled in order to get IPv4 multicast traffic working. +.SH API INTERFACE +Wsdd provides a text-based, line-oriented API interface to query information +and trigger actions. The interface can be used with TCP and UNIX domain sockets +(see \fB\-l/\-\-listen\fR option). The TCP socket is bound to the local host +only. The following commands can be issued: +.SS \fBclear\fR - Clear list of discovered devices +Clears the list of all discovered devices. Use the \fBprobe\fR command to +search for devices again. This command does not return any data and is only +available in discover mode. +.SS \fBlist \fI[TYPE]\fR - List discovered devices +Returns a tab-separated list of discovered devices of the provided TYPE (e.g. +"pub:Computer") with the following information. If no type is provided, all +discovered devices are listed. The possibly empty list of detected hosts is +always terminated with a single dot ('.') in an otherwise empty line. This +command is only available in discover mode. +.TP +URI +URI of the discovered device. Note that a multi-homed device should appear +only once but with multiple addresses (see below) +.TP +name +The name reported by the device. For discovered Windows hosts, it is the +configured computer name that is reported here. +.TP +association +Specifies the domain or workgroup to which the discovered host belongs to. The +type of the association (workgroup or domain) is separated from its value by a +colon. +.TP +last_seen +The date and time the device was last seen as a consequence of Probe/Hello +messages provided in ISO8601 with seconds. +.TP +addresses +List of all transport addresses that were collected during the discovery +process delimited by commas. Addresses are provided along with the interface +(separated by '%') on which they were discovered. IPv6 addresses are reported +on square brackets. Note that the reported addresses may not match the actual +device on which the device may be reached. +.TP +types +Types of the detected device, delimited by commas. +.SS \fBprobe \fI[INTERFACE]\fR - Search for devices +Triggers a Probe message on the provided INTERFACE (eth0, e.g.) to search for +WSD hosts. If no interface is provided, all interfaces wsdd listens on are probed. +A Probe messages initiates the discovery message flow. It may take some time for +hosts to be actually discovered. This command does not return any data and is +only available in discovery mode. +.SS \fBstart\fR - Start networking activities +This command starts the networking acitivies of wsdd if they haven't been +started yet. "Hello" messages are emitted and the host is announced on the +network(s) when the host mode is active. If the discovery mode is enabled a +probe process is also started. + +.SS \fBstop\fR - Stop networking activities +This is the reverse operation to start. When this command is received, "Bye" +messages are sent in order to notify hosts in the network about the host's +disappearance. All networking sockets used for the WSD protocol are closed as +well. Activities can be restarted with the start operation. + +.SH SECURITY +.PP +wsdd does not implement any security feature, e.g. by using TLS for the http +service. This is because wsdd's intended usage is within private, i.e. home, +LANs. The \fIHello\fR message contains the hosts transport address, i.e. the IP +address which speeds up discovery (avoids \fIResolve\fR message). +.SH KNOWN ISSUES +.SS Using only IPv6 on FreeBSD +If wsdd is running on FreeBSD using IPv6 only, the host running wsdd may not be +reliably discovered. The reason appears to be that Windows is not always able +to connect to the HTTP service for unknown reasons. As a workaround, run wsdd +with IPv4 only. +.SS Tunnel/Bridge Interface +.PP +If tunnel/bridge interfaces like those created by OpenVPN or Docker exist, they +may interfere with wsdd if executed without providing an interface that it +should bind to (so it binds to all). In such cases, the wsdd hosts appears after +wsdd has been started but it disappears when an update of the Network view in +Windows Explorer is forced, either by refreshing the view or by a reboot of the +Windows machine. To solve this issue, the interface that is connected to the +network on which the host should be announced needs to be specified with the +-i/--interface option. This prevents the usage of the tunnel/bridge +interfaces. +.PP +Background: Tunnel/bridge interfaces may cause \fIResolve\fR requests from Windows +hosts to be delivered to wsdd multiple times, i.e. duplicates of such request +are created. If wsdd receives such a request first from a tunnel/bridge it uses +the transport address (IP address) of that interface and sends the response via +unicast. Further duplicates are not processed due to the duplicate message +detection which is based on message UUIDs. The Windows host which receives the +response appears to detect a mismatch between the transport address in the +\fIResolveMatch\fR message (which is the tunnel/bridge address) and the IP of the +sending host/interface (LAN IP, e.g.). Subsequently, the wsdd host is ignored by +Windows.