diff --git a/COPYING b/COPYING deleted file mode 100644 index 94a9ed02..00000000 --- a/COPYING +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/COPYING.txt b/COPYING.txt deleted file mode 100644 index 94a9ed02..00000000 --- a/COPYING.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..b8afa8de --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2014-2026 Savoir-faire Linux Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 299f4bb1..dd08adb9 100644 --- a/README.md +++ b/README.md @@ -157,11 +157,7 @@ IRC: join us on Libera.chat at [`#opendht`](https://web.libera.chat/#opendht). ## License Copyright (c) 2014-2026 Savoir-faire Linux Inc. -OpenDHT 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. - -See COPYING or https://www.gnu.org/licenses/gpl-3.0.en.html for the full GPLv3 license. +OpenDHT is released under the MIT License. See [LICENSE](LICENSE) for details. ## Acknowledgements This project was originally based on https://github.com/jech/dht by Juliusz Chroboczek. diff --git a/c/opendht.cpp b/c/opendht.cpp index d6e569c8..cb239581 100644 --- a/c/opendht.cpp +++ b/c/opendht.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "opendht_c.h" @@ -31,67 +17,94 @@ extern "C" { #include -const char* dht_version() +const char* +dht_version() { return dht::version(); } // dht::InfoHash -inline dht_infohash dht_infohash_to_c(const dht::InfoHash& h) { +inline dht_infohash +dht_infohash_to_c(const dht::InfoHash& h) +{ dht_infohash ret; *reinterpret_cast(&ret) = h; return ret; } -inline dht_pkid dht_pkid_to_c(const dht::PkId& h) { +inline dht_pkid +dht_pkid_to_c(const dht::PkId& h) +{ dht_pkid ret; *reinterpret_cast(&ret) = h; return ret; } -const char* dht_infohash_print(const dht_infohash* h) { +const char* +dht_infohash_print(const dht_infohash* h) +{ return reinterpret_cast(h)->to_c_str(); } -void dht_infohash_zero(dht_infohash* h) { - *reinterpret_cast(h) = dht::InfoHash{}; +void +dht_infohash_zero(dht_infohash* h) +{ + *reinterpret_cast(h) = dht::InfoHash {}; } -void dht_infohash_random(dht_infohash* h) { +void +dht_infohash_random(dht_infohash* h) +{ *reinterpret_cast(h) = dht::InfoHash::getRandom(); } -void dht_infohash_get(dht_infohash* h, const uint8_t* dat, size_t dat_size) { +void +dht_infohash_get(dht_infohash* h, const uint8_t* dat, size_t dat_size) +{ *reinterpret_cast(h) = dht::InfoHash::get(dat, dat_size); } -void dht_infohash_get_from_string(dht_infohash* h, const char* dat) { - *reinterpret_cast(h) = dht::InfoHash::get((const uint8_t*)dat, (size_t)strlen(dat)); +void +dht_infohash_get_from_string(dht_infohash* h, const char* dat) +{ + *reinterpret_cast(h) = dht::InfoHash::get((const uint8_t*) dat, (size_t) strlen(dat)); } -bool dht_infohash_is_zero(const dht_infohash* h) { +bool +dht_infohash_is_zero(const dht_infohash* h) +{ return !static_cast(*reinterpret_cast(h)); } -void dht_infohash_from_hex(dht_infohash* h, const char* dat) { - *h = dht_infohash_to_c(dht::InfoHash(std::string_view(dat, HASH_LEN*2))); +void +dht_infohash_from_hex(dht_infohash* h, const char* dat) +{ + *h = dht_infohash_to_c(dht::InfoHash(std::string_view(dat, HASH_LEN * 2))); } -void dht_infohash_from_hex_null(dht_infohash* h, const char* dat) { +void +dht_infohash_from_hex_null(dht_infohash* h, const char* dat) +{ *h = dht_infohash_to_c(dht::InfoHash(std::string_view(dat))); } -const char* dht_pkid_print(const dht_pkid* h) { +const char* +dht_pkid_print(const dht_pkid* h) +{ return reinterpret_cast(h)->to_c_str(); } // dht::Blob -void dht_blob_delete(dht_blob* data) { +void +dht_blob_delete(dht_blob* data) +{ delete reinterpret_cast(data); } -dht_data_view dht_blob_get_data(const dht_blob* data) { +dht_data_view +dht_blob_get_data(const dht_blob* data) +{ dht_data_view view; view.data = reinterpret_cast(data)->data(); view.size = reinterpret_cast(data)->size(); @@ -99,7 +112,9 @@ dht_data_view dht_blob_get_data(const dht_blob* data) { } // dht::Value -dht_data_view dht_value_get_data(const dht_value* data) { +dht_data_view +dht_value_get_data(const dht_value* data) +{ const ValueSp& vsp(*reinterpret_cast(data)); dht_data_view view; view.data = vsp->data.data(); @@ -107,140 +122,193 @@ dht_data_view dht_value_get_data(const dht_value* data) { return view; } -dht_value_id dht_value_get_id(const dht_value* data) { +dht_value_id +dht_value_get_id(const dht_value* data) +{ const ValueSp& vsp(*reinterpret_cast(data)); return vsp->id; } -dht_publickey* dht_value_get_owner(const dht_value* data) { +dht_publickey* +dht_value_get_owner(const dht_value* data) +{ const ValueSp& vsp(*reinterpret_cast(data)); return vsp->owner ? reinterpret_cast(new PubkeySp(vsp->owner)) : nullptr; } -dht_infohash dht_value_get_recipient(const dht_value* data) { +dht_infohash +dht_value_get_recipient(const dht_value* data) +{ const ValueSp& vsp(*reinterpret_cast(data)); return dht_infohash_to_c(vsp->recipient); } -const char* dht_value_get_user_type(const dht_value* data) { +const char* +dht_value_get_user_type(const dht_value* data) +{ const ValueSp& vsp(*reinterpret_cast(data)); return vsp->user_type.c_str(); } -void dht_value_set_user_type(dht_value* data, const char* user_type) { +void +dht_value_set_user_type(dht_value* data, const char* user_type) +{ (*reinterpret_cast(data))->user_type = user_type; } -dht_value* dht_value_with_id_new(const uint8_t* data, size_t size, uint64_t value_id) { - return reinterpret_cast(new ValueSp(std::make_shared(dht::ValueType::USER_DATA.id, data, size, value_id))); +dht_value* +dht_value_with_id_new(const uint8_t* data, size_t size, uint64_t value_id) +{ + return reinterpret_cast( + new ValueSp(std::make_shared(dht::ValueType::USER_DATA.id, data, size, value_id))); } -dht_value* dht_value_new(const uint8_t* data, size_t size) { +dht_value* +dht_value_new(const uint8_t* data, size_t size) +{ return dht_value_with_id_new(data, size, 0); } -dht_value* dht_value_new_from_string(const char* str) { - ValueSp value = std::make_shared((const uint8_t*)str, strlen(str)); +dht_value* +dht_value_new_from_string(const char* str) +{ + ValueSp value = std::make_shared((const uint8_t*) str, strlen(str)); value->user_type = "text/plain"; return reinterpret_cast(new ValueSp(std::move(value))); } -dht_value* dht_value_ref(const dht_value* v) { +dht_value* +dht_value_ref(const dht_value* v) +{ return reinterpret_cast(new ValueSp(*reinterpret_cast(v))); } -void dht_value_unref(dht_value* v) { +void +dht_value_unref(dht_value* v) +{ delete reinterpret_cast(v); } // dht::crypto::PublicKey -dht_publickey* dht_publickey_import(const uint8_t* dat, size_t dat_size) { +dht_publickey* +dht_publickey_import(const uint8_t* dat, size_t dat_size) +{ try { - return reinterpret_cast(new PubkeySp(std::make_shared(dat, dat_size))); + return reinterpret_cast( + new PubkeySp(std::make_shared(dat, dat_size))); } catch (const dht::crypto::CryptoException& e) { return nullptr; } } -void dht_publickey_delete(dht_publickey* pk) { +void +dht_publickey_delete(dht_publickey* pk) +{ delete reinterpret_cast(pk); } -int dht_publickey_export(const dht_publickey* pk, char* out, size_t* outlen) { +int +dht_publickey_export(const dht_publickey* pk, char* out, size_t* outlen) +{ const auto& pkey = *reinterpret_cast(pk); - return pkey->pack((uint8_t*)out, outlen); + return pkey->pack((uint8_t*) out, outlen); } -dht_infohash dht_publickey_get_id(const dht_publickey* pk) { +dht_infohash +dht_publickey_get_id(const dht_publickey* pk) +{ const auto& pkey = *reinterpret_cast(pk); return dht_infohash_to_c(pkey->getId()); } -dht_pkid dht_publickey_get_long_id(const dht_publickey* pk) { +dht_pkid +dht_publickey_get_long_id(const dht_publickey* pk) +{ const auto& pkey = *reinterpret_cast(pk); return dht_pkid_to_c(pkey->getLongId()); } -bool dht_publickey_check_signature(const dht_publickey* pk, const char* data, size_t data_size, const char* signature, size_t signature_size) { +bool +dht_publickey_check_signature( + const dht_publickey* pk, const char* data, size_t data_size, const char* signature, size_t signature_size) +{ const auto& pkey = *reinterpret_cast(pk); - return pkey->checkSignature((const uint8_t*)data, data_size, (const uint8_t*)signature, signature_size); + return pkey->checkSignature((const uint8_t*) data, data_size, (const uint8_t*) signature, signature_size); } -dht_blob* dht_publickey_encrypt(const dht_publickey* pk, const char* data, size_t data_size) { +dht_blob* +dht_publickey_encrypt(const dht_publickey* pk, const char* data, size_t data_size) +{ const auto& pkey = *reinterpret_cast(pk); try { auto rdata = std::make_unique(); - *rdata = pkey->encrypt((const uint8_t*)data, data_size); - return (dht_blob*)rdata.release(); + *rdata = pkey->encrypt((const uint8_t*) data, data_size); + return (dht_blob*) rdata.release(); } catch (...) { return nullptr; } } // dht::crypto::PrivateKey -dht_privatekey* dht_privatekey_generate(unsigned key_length_bits) { +dht_privatekey* +dht_privatekey_generate(unsigned key_length_bits) +{ if (key_length_bits == 0) key_length_bits = 4096; - return reinterpret_cast(new PrivkeySp(std::make_shared(dht::crypto::PrivateKey::generate(key_length_bits)))); + return reinterpret_cast( + new PrivkeySp(std::make_shared(dht::crypto::PrivateKey::generate(key_length_bits)))); } -dht_privatekey* dht_privatekey_import(const uint8_t* dat, size_t dat_size, const char* password) { +dht_privatekey* +dht_privatekey_import(const uint8_t* dat, size_t dat_size, const char* password) +{ try { - return reinterpret_cast(new PrivkeySp(std::make_shared(dat, dat_size, password))); + return reinterpret_cast( + new PrivkeySp(std::make_shared(dat, dat_size, password))); } catch (const dht::crypto::CryptoException& e) { return nullptr; } } -int dht_privatekey_export(const dht_privatekey* k, char* out, size_t* out_size, const char* password) { +int +dht_privatekey_export(const dht_privatekey* k, char* out, size_t* out_size, const char* password) +{ if (!out or !out_size or !*out_size) return -1; const auto& key = *reinterpret_cast(k); - return key->serialize((uint8_t*)out, out_size, password); + return key->serialize((uint8_t*) out, out_size, password); } -dht_publickey* dht_privatekey_get_publickey(const dht_privatekey* k) { +dht_publickey* +dht_privatekey_get_publickey(const dht_privatekey* k) +{ const auto& key = *reinterpret_cast(k); return reinterpret_cast(new PubkeySp(key->getSharedPublicKey())); } -dht_blob* dht_privatekey_decrypt(const dht_privatekey* k, const char* data, size_t data_size) { +dht_blob* +dht_privatekey_decrypt(const dht_privatekey* k, const char* data, size_t data_size) +{ const auto& key = *reinterpret_cast(k); try { auto rdata = std::make_unique(); - *rdata = key->decrypt((const uint8_t*)data, data_size); - return (dht_blob*)rdata.release(); + *rdata = key->decrypt((const uint8_t*) data, data_size); + return (dht_blob*) rdata.release(); } catch (...) { return nullptr; } } -void dht_privatekey_delete(dht_privatekey* pk) { +void +dht_privatekey_delete(dht_privatekey* pk) +{ delete reinterpret_cast(pk); } // dht::crypto::Certificate -dht_certificate* dht_certificate_import(const uint8_t* dat, size_t dat_size) { +dht_certificate* +dht_certificate_import(const uint8_t* dat, size_t dat_size) +{ try { return reinterpret_cast(new CertSp(std::make_shared(dat, dat_size))); } catch (const dht::crypto::CryptoException& e) { @@ -248,21 +316,29 @@ dht_certificate* dht_certificate_import(const uint8_t* dat, size_t dat_size) { } } -void dht_certificate_delete(dht_certificate* c) { +void +dht_certificate_delete(dht_certificate* c) +{ delete reinterpret_cast(c); } -dht_infohash dht_certificate_get_id(const dht_certificate* c) { +dht_infohash +dht_certificate_get_id(const dht_certificate* c) +{ const auto& cert = *reinterpret_cast(c); return dht_infohash_to_c(cert->getId()); } -dht_pkid dht_certificate_get_long_id(const dht_certificate* c) { +dht_pkid +dht_certificate_get_long_id(const dht_certificate* c) +{ const auto& cert = *reinterpret_cast(c); return dht_pkid_to_c(cert->getLongId()); } -dht_publickey* dht_certificate_get_publickey(const dht_certificate* c) { +dht_publickey* +dht_certificate_get_publickey(const dht_certificate* c) +{ const auto& cert = *reinterpret_cast(c); return reinterpret_cast(new PubkeySp(cert->getSharedPublicKey())); } @@ -273,7 +349,9 @@ dht_publickey* dht_certificate_get_publickey(const dht_certificate* c) { #endif // dht::crypto::Identity -inline dht::crypto::Identity dht_identity_from_c(const dht_identity* cid) { +inline dht::crypto::Identity +dht_identity_from_c(const dht_identity* cid) +{ dht::crypto::Identity id {}; if (cid and cid->privatekey) id.first = *reinterpret_cast(cid->privatekey); @@ -282,7 +360,9 @@ inline dht::crypto::Identity dht_identity_from_c(const dht_identity* cid) { return id; } -inline dht_identity dht_identity_to_c(const dht::crypto::Identity& id) { +inline dht_identity +dht_identity_to_c(const dht::crypto::Identity& id) +{ dht_identity cid {}; cid.privatekey = id.first ? reinterpret_cast(new PrivkeySp(id.first)) : NULL; cid.certificate = id.second ? reinterpret_cast(new CertSp(id.second)) : NULL; @@ -293,11 +373,15 @@ inline dht_identity dht_identity_to_c(const dht::crypto::Identity& id) { extern "C" { #endif -OPENDHT_C_PUBLIC dht_identity dht_identity_generate(const char* common_name, const dht_identity* ca) { +OPENDHT_C_PUBLIC dht_identity +dht_identity_generate(const char* common_name, const dht_identity* ca) +{ return dht_identity_to_c(dht::crypto::generateIdentity(common_name, dht_identity_from_c(ca))); } -OPENDHT_C_PUBLIC void dht_identity_delete(dht_identity* id) { +OPENDHT_C_PUBLIC void +dht_identity_delete(dht_identity* id) +{ if (id->certificate) { dht_certificate_delete(id->certificate); id->certificate = NULL; @@ -309,41 +393,52 @@ OPENDHT_C_PUBLIC void dht_identity_delete(dht_identity* id) { } // config -void dht_runner_config_default(dht_runner_config* config) { +void +dht_runner_config_default(dht_runner_config* config) +{ memset(config, 0, sizeof(dht_runner_config)); config->threaded = true; } // dht::DhtRunner -dht_runner* dht_runner_new(void) { +dht_runner* +dht_runner_new(void) +{ return reinterpret_cast(new dht::DhtRunner); } -void dht_runner_delete(dht_runner* runner) { +void +dht_runner_delete(dht_runner* runner) +{ delete reinterpret_cast(runner); } -int dht_runner_run(dht_runner* r, in_port_t port) { +int +dht_runner_run(dht_runner* r, in_port_t port) +{ auto runner = reinterpret_cast(r); try { runner->run(port, {}, true); - } catch(...) { + } catch (...) { return ENOTCONN; } return 0; } -int dht_runner_run_config(dht_runner* r, in_port_t port, const dht_runner_config* conf) { +int +dht_runner_run_config(dht_runner* r, in_port_t port, const dht_runner_config* conf) +{ auto runner = reinterpret_cast(r); try { dht::DhtRunner::Config config; - config.dht_config.node_config.is_bootstrap = conf->dht_config.node_config.is_bootstrap; + config.dht_config.node_config.is_bootstrap = conf->dht_config.node_config.is_bootstrap; config.dht_config.node_config.maintain_storage = conf->dht_config.node_config.maintain_storage; - config.dht_config.node_config.node_id = *reinterpret_cast(&conf->dht_config.node_config.node_id); - config.dht_config.node_config.network = conf->dht_config.node_config.network; - config.dht_config.node_config.persist_path = conf->dht_config.node_config.persist_path - ? std::string(conf->dht_config.node_config.persist_path) - : std::string{}; + config.dht_config.node_config.node_id = *reinterpret_cast( + &conf->dht_config.node_config.node_id); + config.dht_config.node_config.network = conf->dht_config.node_config.network; + config.dht_config.node_config.persist_path = conf->dht_config.node_config.persist_path + ? std::string(conf->dht_config.node_config.persist_path) + : std::string {}; if (conf->dht_config.id.privatekey) config.dht_config.id.first = *reinterpret_cast(conf->dht_config.id.privatekey); @@ -351,42 +446,45 @@ int dht_runner_run_config(dht_runner* r, in_port_t port, const dht_runner_config if (conf->dht_config.id.certificate) config.dht_config.id.second = *reinterpret_cast(conf->dht_config.id.certificate); - config.threaded = conf->threaded; - config.proxy_server = conf->proxy_server ? std::string(conf->proxy_server) : std::string{}; - config.push_node_id = conf->push_node_id ? std::string(conf->push_node_id) : std::string{}; - config.push_token = conf->push_token ? std::string(conf->push_token) : std::string{}; - config.push_topic = conf->push_topic ? std::string(conf->push_topic) : std::string{}; - config.push_platform = conf->push_platform ? std::string(conf->push_platform) : std::string{}; - config.proxy_user_agent = conf->proxy_user_agent ? std::string(conf->proxy_user_agent) : std::string{}; - config.peer_discovery = conf->peer_discovery; - config.peer_publish = conf->peer_publish; + config.threaded = conf->threaded; + config.proxy_server = conf->proxy_server ? std::string(conf->proxy_server) : std::string {}; + config.push_node_id = conf->push_node_id ? std::string(conf->push_node_id) : std::string {}; + config.push_token = conf->push_token ? std::string(conf->push_token) : std::string {}; + config.push_topic = conf->push_topic ? std::string(conf->push_topic) : std::string {}; + config.push_platform = conf->push_platform ? std::string(conf->push_platform) : std::string {}; + config.proxy_user_agent = conf->proxy_user_agent ? std::string(conf->proxy_user_agent) : std::string {}; + config.peer_discovery = conf->peer_discovery; + config.peer_publish = conf->peer_publish; if (conf->server_ca) - config.server_ca = *reinterpret_cast(conf->server_ca); - config.client_identity = dht_identity_from_c(&conf->client_identity); + config.server_ca = *reinterpret_cast(conf->server_ca); + config.client_identity = dht_identity_from_c(&conf->client_identity); dht::DhtRunner::Context context; if (conf->log) { context.logger = dht::log::getStdLogger(); } runner->run(port, config, std::move(context)); - } catch(...) { + } catch (...) { return ENOTCONN; } return 0; } -void dht_runner_ping(dht_runner* r, struct sockaddr* addr, socklen_t addr_len, dht_done_cb done_cb, void* cb_user_data) { +void +dht_runner_ping(dht_runner* r, struct sockaddr* addr, socklen_t addr_len, dht_done_cb done_cb, void* cb_user_data) +{ auto runner = reinterpret_cast(r); if (done_cb) { - runner->bootstrap(dht::SockAddr(addr, addr_len), [done_cb, cb_user_data](bool ok){ - done_cb(ok, cb_user_data); - }); + runner->bootstrap(dht::SockAddr(addr, addr_len), + [done_cb, cb_user_data](bool ok) { done_cb(ok, cb_user_data); }); } else { runner->bootstrap(dht::SockAddr(addr, addr_len)); } } -void dht_runner_bootstrap(dht_runner* r, const char* host, const char* service) { +void +dht_runner_bootstrap(dht_runner* r, const char* host, const char* service) +{ auto runner = reinterpret_cast(r); if (service) runner->bootstrap(host, service); @@ -394,136 +492,196 @@ void dht_runner_bootstrap(dht_runner* r, const char* host, const char* service) runner->bootstrap(host); } -void dht_runner_get(dht_runner* r, const dht_infohash* h, dht_get_cb cb, dht_done_cb done_cb, void* cb_user_data) { +void +dht_runner_get(dht_runner* r, const dht_infohash* h, dht_get_cb cb, dht_done_cb done_cb, void* cb_user_data) +{ auto runner = reinterpret_cast(r); auto hash = reinterpret_cast(h); - runner->get(*hash, [cb,cb_user_data](std::shared_ptr value){ - return cb(reinterpret_cast(&value), cb_user_data); - }, [done_cb, cb_user_data](bool ok){ - if (done_cb) - done_cb(ok, cb_user_data); - }); + runner->get( + *hash, + [cb, cb_user_data](std::shared_ptr value) { + return cb(reinterpret_cast(&value), cb_user_data); + }, + [done_cb, cb_user_data](bool ok) { + if (done_cb) + done_cb(ok, cb_user_data); + }); } -struct ScopeGuardCb { +struct ScopeGuardCb +{ ScopeGuardCb(dht_shutdown_cb cb, void* data) - : onDestroy(cb), userData(data) {} + : onDestroy(cb) + , userData(data) + {} - ~ScopeGuardCb() { + ~ScopeGuardCb() + { if (onDestroy) - onDestroy((void*)userData); + onDestroy((void*) userData); } + private: const dht_shutdown_cb onDestroy; void const* userData; }; -dht_op_token* dht_runner_listen(dht_runner* r, const dht_infohash* h, dht_value_cb cb, dht_shutdown_cb done_cb, void* cb_user_data) { +dht_op_token* +dht_runner_listen(dht_runner* r, const dht_infohash* h, dht_value_cb cb, dht_shutdown_cb done_cb, void* cb_user_data) +{ auto runner = reinterpret_cast(r); auto hash = reinterpret_cast(h); auto fret = new std::future; - *fret = runner->listen(*hash, [ - cb, - cb_user_data, - guard = done_cb ? std::make_shared(done_cb, cb_user_data) : std::shared_ptr{} - ](const std::vector>& values, bool expired) { - for (const auto& value : values) { - if (not cb(reinterpret_cast(&value), expired, cb_user_data)) - return false; - } - return true; - }); - return (dht_op_token*)fret; + *fret = runner->listen(*hash, + [cb, + cb_user_data, + guard = done_cb ? std::make_shared(done_cb, cb_user_data) + : std::shared_ptr {}]( + const std::vector>& values, bool expired) { + for (const auto& value : values) { + if (not cb(reinterpret_cast(&value), expired, cb_user_data)) + return false; + } + return true; + }); + return (dht_op_token*) fret; } -void dht_runner_cancel_listen(dht_runner* r, const dht_infohash* h, dht_op_token* t) { +void +dht_runner_cancel_listen(dht_runner* r, const dht_infohash* h, dht_op_token* t) +{ auto runner = reinterpret_cast(r); auto hash = reinterpret_cast(h); auto token = reinterpret_cast*>(t); runner->cancelListen(*hash, std::move(*token)); } -void dht_op_token_delete(dht_op_token* token) { +void +dht_op_token_delete(dht_op_token* token) +{ delete reinterpret_cast*>(token); } -void dht_runner_put(dht_runner* r, const dht_infohash* h, const dht_value* v, dht_done_cb done_cb, void* cb_user_data, bool permanent) { +void +dht_runner_put( + dht_runner* r, const dht_infohash* h, const dht_value* v, dht_done_cb done_cb, void* cb_user_data, bool permanent) +{ auto runner = reinterpret_cast(r); auto hash = reinterpret_cast(h); auto value = reinterpret_cast(v); - runner->put(*hash, *value, [done_cb, cb_user_data](bool ok){ - if (done_cb) - done_cb(ok, cb_user_data); - }, dht::time_point::max(), permanent); + runner->put( + *hash, + *value, + [done_cb, cb_user_data](bool ok) { + if (done_cb) + done_cb(ok, cb_user_data); + }, + dht::time_point::max(), + permanent); } -void dht_runner_put_signed(dht_runner* r, const dht_infohash* h, const dht_value* v, dht_done_cb done_cb, void* cb_user_data, bool permanent) { +void +dht_runner_put_signed( + dht_runner* r, const dht_infohash* h, const dht_value* v, dht_done_cb done_cb, void* cb_user_data, bool permanent) +{ auto runner = reinterpret_cast(r); auto hash = reinterpret_cast(h); auto value = reinterpret_cast(v); - runner->putSigned(*hash, *value, [done_cb, cb_user_data](bool ok){ - if (done_cb) - done_cb(ok, cb_user_data); - }, permanent); + runner->putSigned( + *hash, + *value, + [done_cb, cb_user_data](bool ok) { + if (done_cb) + done_cb(ok, cb_user_data); + }, + permanent); } -void dht_runner_put_encrypted(dht_runner* r, const dht_infohash* h, const dht_infohash* to, const dht_value* v, dht_done_cb done_cb, void* cb_user_data, bool permanent) { +void +dht_runner_put_encrypted(dht_runner* r, + const dht_infohash* h, + const dht_infohash* to, + const dht_value* v, + dht_done_cb done_cb, + void* cb_user_data, + bool permanent) +{ auto runner = reinterpret_cast(r); auto hash = reinterpret_cast(h); auto toHash = reinterpret_cast(to); auto value = reinterpret_cast(v); - runner->putEncrypted(*hash, *toHash, *value, [done_cb, cb_user_data](bool ok){ - if (done_cb) - done_cb(ok, cb_user_data); - }, permanent); + runner->putEncrypted( + *hash, + *toHash, + *value, + [done_cb, cb_user_data](bool ok) { + if (done_cb) + done_cb(ok, cb_user_data); + }, + permanent); } -void dht_runner_cancel_put(dht_runner* r, const dht_infohash* h, dht_value_id value_id) { +void +dht_runner_cancel_put(dht_runner* r, const dht_infohash* h, dht_value_id value_id) +{ auto runner = reinterpret_cast(r); auto hash = reinterpret_cast(h); runner->cancelPut(*hash, value_id); } -void dht_runner_shutdown(dht_runner* r, dht_shutdown_cb done_cb, void* cb_user_data) { +void +dht_runner_shutdown(dht_runner* r, dht_shutdown_cb done_cb, void* cb_user_data) +{ auto runner = reinterpret_cast(r); - runner->shutdown([done_cb, cb_user_data](){ + runner->shutdown([done_cb, cb_user_data]() { if (done_cb) done_cb(cb_user_data); }); } -bool dht_runner_is_running(const dht_runner* r) { - if (not r) return false; +bool +dht_runner_is_running(const dht_runner* r) +{ + if (not r) + return false; auto runner = reinterpret_cast(r); return runner->isRunning(); } -in_port_t dht_runner_get_bound_port(const dht_runner* r, sa_family_t af) { +in_port_t +dht_runner_get_bound_port(const dht_runner* r, sa_family_t af) +{ auto runner = reinterpret_cast(r); return runner->getBoundPort(af); } -dht_infohash dht_runner_get_node_id(const dht_runner* r) { +dht_infohash +dht_runner_get_node_id(const dht_runner* r) +{ auto runner = reinterpret_cast(r); dht_infohash ret; *reinterpret_cast(&ret) = runner->getNodeId(); return ret; } -dht_infohash dht_runner_get_id(const dht_runner* r) { +dht_infohash +dht_runner_get_id(const dht_runner* r) +{ auto runner = reinterpret_cast(r); dht_infohash ret; *reinterpret_cast(&ret) = runner->getId(); return ret; } -struct sockaddr** dht_runner_get_public_address(const dht_runner* r) { +struct sockaddr** +dht_runner_get_public_address(const dht_runner* r) +{ auto runner = reinterpret_cast(r); auto addrs = const_cast(runner)->getPublicAddress(); if (addrs.empty()) return nullptr; - auto ret = (struct sockaddr**)malloc(sizeof(struct sockaddr*) * (addrs.size() + 1)); - for (size_t i=0; i. - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #ifdef __cplusplus @@ -38,7 +23,8 @@ typedef uint16_t in_port_t; #endif // Non-owning data view -struct OPENDHT_C_PUBLIC dht_data_view { +struct OPENDHT_C_PUBLIC dht_data_view +{ const uint8_t* data; size_t size; }; @@ -53,7 +39,10 @@ OPENDHT_C_PUBLIC dht_data_view dht_blob_get_data(const dht_blob* data); OPENDHT_C_PUBLIC void dht_blob_delete(dht_blob* data); // dht::InfoHash -struct OPENDHT_C_PUBLIC dht_infohash { uint8_t d[HASH_LEN]; }; +struct OPENDHT_C_PUBLIC dht_infohash +{ + uint8_t d[HASH_LEN]; +}; typedef struct dht_infohash dht_infohash; OPENDHT_C_PUBLIC void dht_infohash_zero(dht_infohash* h); OPENDHT_C_PUBLIC void dht_infohash_random(dht_infohash* h); @@ -65,7 +54,10 @@ OPENDHT_C_PUBLIC const char* dht_infohash_print(const dht_infohash* h); OPENDHT_C_PUBLIC bool dht_infohash_is_zero(const dht_infohash* h); // dht::PkId -struct OPENDHT_C_PUBLIC dht_pkid { uint8_t d[32]; }; +struct OPENDHT_C_PUBLIC dht_pkid +{ + uint8_t d[32]; +}; typedef struct dht_pkid dht_pkid; OPENDHT_C_PUBLIC const char* dht_pkid_print(const dht_pkid* h); @@ -77,7 +69,8 @@ OPENDHT_C_PUBLIC void dht_publickey_delete(dht_publickey* pk); OPENDHT_C_PUBLIC int dht_publickey_export(const dht_publickey* pk, char* out, size_t* out_size); OPENDHT_C_PUBLIC dht_infohash dht_publickey_get_id(const dht_publickey* pk); OPENDHT_C_PUBLIC dht_pkid dht_publickey_get_long_id(const dht_publickey* pk); -OPENDHT_C_PUBLIC bool dht_publickey_check_signature(const dht_publickey* pk, const char* data, size_t data_size, const char* signature, size_t signature_size); +OPENDHT_C_PUBLIC bool dht_publickey_check_signature( + const dht_publickey* pk, const char* data, size_t data_size, const char* signature, size_t signature_size); OPENDHT_C_PUBLIC dht_blob* dht_publickey_encrypt(const dht_publickey* pk, const char* data, size_t data_size); // dht::crypto::PrivateKey @@ -99,7 +92,8 @@ OPENDHT_C_PUBLIC dht_pkid dht_certificate_get_long_id(const dht_certificate*); OPENDHT_C_PUBLIC dht_publickey* dht_certificate_get_publickey(const dht_certificate*); OPENDHT_C_PUBLIC void dht_certificate_delete(dht_certificate*); -struct OPENDHT_C_PUBLIC dht_identity { +struct OPENDHT_C_PUBLIC dht_identity +{ dht_privatekey* privatekey; dht_certificate* certificate; }; @@ -134,7 +128,8 @@ typedef struct dht_op_token dht_op_token; OPENDHT_C_PUBLIC void dht_op_token_delete(dht_op_token* token); // config -struct OPENDHT_C_PUBLIC dht_node_config { +struct OPENDHT_C_PUBLIC dht_node_config +{ dht_infohash node_id; uint32_t network; bool is_bootstrap; @@ -143,13 +138,15 @@ struct OPENDHT_C_PUBLIC dht_node_config { }; typedef struct dht_node_config dht_node_config; -struct OPENDHT_C_PUBLIC dht_secure_config { +struct OPENDHT_C_PUBLIC dht_secure_config +{ dht_node_config node_config; dht_identity id; }; typedef struct dht_secure_config dht_secure_config; -struct OPENDHT_C_PUBLIC dht_runner_config { +struct OPENDHT_C_PUBLIC dht_runner_config +{ dht_secure_config dht_config; bool threaded; const char* proxy_server; @@ -176,14 +173,33 @@ OPENDHT_C_PUBLIC void dht_runner_delete(dht_runner* runner); OPENDHT_C_PUBLIC int dht_runner_run(dht_runner* runner, in_port_t port); /* Returns 0 on success, standard error code on failure */ OPENDHT_C_PUBLIC int dht_runner_run_config(dht_runner* runner, in_port_t port, const dht_runner_config* config); -OPENDHT_C_PUBLIC void dht_runner_ping(dht_runner* runner, struct sockaddr* addr, socklen_t addr_len, dht_done_cb done_cb, void* cb_user_data); +OPENDHT_C_PUBLIC void dht_runner_ping( + dht_runner* runner, struct sockaddr* addr, socklen_t addr_len, dht_done_cb done_cb, void* cb_user_data); OPENDHT_C_PUBLIC void dht_runner_bootstrap(dht_runner* runner, const char* host, const char* service); -OPENDHT_C_PUBLIC void dht_runner_get(dht_runner* runner, const dht_infohash* hash, dht_get_cb cb, dht_done_cb done_cb, void* cb_user_data); -OPENDHT_C_PUBLIC dht_op_token* dht_runner_listen(dht_runner* runner, const dht_infohash* hash, dht_value_cb cb, dht_shutdown_cb done_cb, void* cb_user_data); +OPENDHT_C_PUBLIC void dht_runner_get( + dht_runner* runner, const dht_infohash* hash, dht_get_cb cb, dht_done_cb done_cb, void* cb_user_data); +OPENDHT_C_PUBLIC dht_op_token* dht_runner_listen( + dht_runner* runner, const dht_infohash* hash, dht_value_cb cb, dht_shutdown_cb done_cb, void* cb_user_data); OPENDHT_C_PUBLIC void dht_runner_cancel_listen(dht_runner* runner, const dht_infohash* hash, dht_op_token* token); -OPENDHT_C_PUBLIC void dht_runner_put(dht_runner* runner, const dht_infohash* hash, const dht_value* value, dht_done_cb done_cb, void* cb_user_data, bool permanent); -OPENDHT_C_PUBLIC void dht_runner_put_signed(dht_runner* runner, const dht_infohash* hash, const dht_value* value, dht_done_cb done_cb, void* cb_user_data, bool permanent); -OPENDHT_C_PUBLIC void dht_runner_put_encrypted(dht_runner* runner, const dht_infohash* hash, const dht_infohash* to, const dht_value* value, dht_done_cb done_cb, void* cb_user_data, bool permanent); +OPENDHT_C_PUBLIC void dht_runner_put(dht_runner* runner, + const dht_infohash* hash, + const dht_value* value, + dht_done_cb done_cb, + void* cb_user_data, + bool permanent); +OPENDHT_C_PUBLIC void dht_runner_put_signed(dht_runner* runner, + const dht_infohash* hash, + const dht_value* value, + dht_done_cb done_cb, + void* cb_user_data, + bool permanent); +OPENDHT_C_PUBLIC void dht_runner_put_encrypted(dht_runner* runner, + const dht_infohash* hash, + const dht_infohash* to, + const dht_value* value, + dht_done_cb done_cb, + void* cb_user_data, + bool permanent); OPENDHT_C_PUBLIC void dht_runner_cancel_put(dht_runner* runner, const dht_infohash* hash, dht_value_id value_id); OPENDHT_C_PUBLIC void dht_runner_shutdown(dht_runner* runner, dht_shutdown_cb done_cb, void* cb_user_data); OPENDHT_C_PUBLIC dht_infohash dht_runner_get_node_id(const dht_runner* runner); diff --git a/include/opendht.h b/include/opendht.h index a486db06..ead9d5a4 100644 --- a/include/opendht.h +++ b/include/opendht.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "opendht/dhtrunner.h" diff --git a/include/opendht/callbacks.h b/include/opendht/callbacks.h index 1432df3e..463431b4 100644 --- a/include/opendht/callbacks.h +++ b/include/opendht/callbacks.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "infohash.h" @@ -43,17 +28,15 @@ enum class NodeStatus { }; inline constexpr const char* -statusToStr(NodeStatus status) { - return status == NodeStatus::Connected ? "connected" : ( - status == NodeStatus::Connecting ? "connecting" : - "disconnected"); +statusToStr(NodeStatus status) +{ + return status == NodeStatus::Connected ? "connected" + : (status == NodeStatus::Connecting ? "connecting" : "disconnected"); } -struct OPENDHT_PUBLIC NodeStats { - unsigned good_nodes {0}, - dubious_nodes {0}, - cached_nodes {0}, - incoming_nodes {0}; +struct OPENDHT_PUBLIC NodeStats +{ + unsigned good_nodes {0}, dubious_nodes {0}, cached_nodes {0}, incoming_nodes {0}; unsigned table_depth {0}; unsigned searches {0}; unsigned node_cache_size {0}; @@ -73,7 +56,8 @@ struct OPENDHT_PUBLIC NodeStats { MSGPACK_DEFINE_MAP(good_nodes, dubious_nodes, cached_nodes, incoming_nodes, table_depth, searches, node_cache_size) }; -struct OPENDHT_PUBLIC NodeInfo { +struct OPENDHT_PUBLIC NodeInfo +{ InfoHash id; InfoHash node_id; NodeStats ipv4 {}; @@ -99,7 +83,8 @@ struct OPENDHT_PUBLIC NodeInfo { /** * Dht configuration. */ -struct OPENDHT_PUBLIC Config { +struct OPENDHT_PUBLIC Config +{ /** DHT node ID */ InfoHash node_id {}; @@ -160,7 +145,7 @@ struct OPENDHT_PUBLIC SecureDhtConfig bool cert_cache_all {false}; }; -enum class OPENDHT_PUBLIC PushNotificationResult: uint8_t { +enum class OPENDHT_PUBLIC PushNotificationResult : uint8_t { /* success codes */ PutRefresh, ListenRefresh, @@ -186,19 +171,19 @@ using ShutdownCallback = std::function; using IdentityAnnouncedCb = std::function; using PublicAddressChangedCb = std::function)>; -using CertificateStoreQueryLegacy = std::function>(const InfoHash& pk_id)>; +using CertificateStoreQueryLegacy + = std::function>(const InfoHash& pk_id)>; using CertificateStoreQuery = std::function>(const PkId& pk_id)>; using DoneCallback = std::function>& nodes)>; using DoneCallbackSimple = std::function; -typedef bool (*GetCallbackRaw)(std::shared_ptr, void *user_data); -typedef bool (*ValueCallbackRaw)(std::shared_ptr, bool expired, void *user_data); -typedef void (*DoneCallbackRaw)(bool, std::vector>*, void *user_data); -typedef void (*ShutdownCallbackRaw)(void *user_data); -typedef void (*DoneCallbackSimpleRaw)(bool, void *user_data); -typedef bool (*FilterRaw)(const Value&, void *user_data); - +typedef bool (*GetCallbackRaw)(std::shared_ptr, void* user_data); +typedef bool (*ValueCallbackRaw)(std::shared_ptr, bool expired, void* user_data); +typedef void (*DoneCallbackRaw)(bool, std::vector>*, void* user_data); +typedef void (*ShutdownCallbackRaw)(void* user_data); +typedef void (*DoneCallbackSimpleRaw)(bool, void* user_data); +typedef bool (*FilterRaw)(const Value&, void* user_data); OPENDHT_PUBLIC GetCallbackSimple bindGetCb(GetCallbackRaw raw_cb, void* user_data); OPENDHT_PUBLIC GetCallback bindGetCb(GetCallbackSimple cb); @@ -209,4 +194,4 @@ OPENDHT_PUBLIC DoneCallback bindDoneCb(DoneCallbackRaw raw_cb, void* user_data); OPENDHT_PUBLIC DoneCallbackSimple bindDoneCbSimple(DoneCallbackSimpleRaw raw_cb, void* user_data); OPENDHT_PUBLIC Value::Filter bindFilterRaw(FilterRaw raw_filter, void* user_data); -} +} // namespace dht diff --git a/include/opendht/crypto.h b/include/opendht/crypto.h index 62912298..c7e744da 100644 --- a/include/opendht/crypto.h +++ b/include/opendht/crypto.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "infohash.h" diff --git a/include/opendht/crypto/secure_vector.h b/include/opendht/crypto/secure_vector.h index 479a4fcb..e4e64c6c 100644 --- a/include/opendht/crypto/secure_vector.h +++ b/include/opendht/crypto/secure_vector.h @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include @@ -22,71 +8,91 @@ namespace dht { namespace crypto { -template +template class secure_vector { public: secure_vector() {} secure_vector(secure_vector const&) = default; - secure_vector(secure_vector &&) = default; - explicit secure_vector(unsigned size): data_(size) {} - explicit secure_vector(unsigned size, T _item): data_(size, _item) {} - explicit secure_vector(const std::vector& c): data_(c) {} - secure_vector(std::vector&& c): data_(std::move(c)) {} + secure_vector(secure_vector&&) = default; + explicit secure_vector(unsigned size) + : data_(size) + {} + explicit secure_vector(unsigned size, T _item) + : data_(size, _item) + {} + explicit secure_vector(const std::vector& c) + : data_(c) + {} + secure_vector(std::vector&& c) + : data_(std::move(c)) + {} ~secure_vector() { clean(); } - static secure_vector getRandom(size_t size) { + static secure_vector getRandom(size_t size) + { secure_vector ret(size); std::random_device rdev; #ifdef _WIN32 - std::uniform_int_distribution rand_byte{ 0, std::numeric_limits::max() }; + std::uniform_int_distribution rand_byte {0, std::numeric_limits::max()}; #else std::uniform_int_distribution rand_byte; #endif - std::generate_n((uint8_t*)ret.data_.data(), ret.size()*sizeof(T), std::bind(rand_byte, std::ref(rdev))); + std::generate_n((uint8_t*) ret.data_.data(), ret.size() * sizeof(T), std::bind(rand_byte, std::ref(rdev))); return ret; } - secure_vector& operator=(const secure_vector& c) { + secure_vector& operator=(const secure_vector& c) + { if (&c == this) return *this; clean(); data_ = c.data_; return *this; } - secure_vector& operator=(secure_vector&& c) { + secure_vector& operator=(secure_vector&& c) + { if (&c == this) return *this; clean(); data_ = std::move(c.data_); return *this; } - secure_vector& operator=(std::vector&& c) { + secure_vector& operator=(std::vector&& c) + { clean(); data_ = std::move(c); return *this; } - std::vector& writable() { clean(); return data_; } + std::vector& writable() + { + clean(); + return data_; + } const std::vector& makeInsecure() const { return data_; } const uint8_t* data() const { return data_.data(); } - void clean() { - clean(data_.begin(), data_.end()); - } + void clean() { clean(data_.begin(), data_.end()); } - void clear() { clean(); data_.clear(); } + void clear() + { + clean(); + data_.clear(); + } size_t size() const { return data_.size(); } bool empty() const { return data_.empty(); } void swap(secure_vector& other) { data_.swap(other.data_); } - void resize(size_t s) { - if (s == data_.size()) return; + void resize(size_t s) + { + if (s == data_.size()) + return; if (s < data_.size()) { - //shrink - clean(data_.begin()+s, data_.end()); + // shrink + clean(data_.begin() + s, data_.end()); data_.resize(s); } else { - //grow + // grow auto data = std::move(data_); // move protected data clear(); data_.resize(s); @@ -99,7 +105,8 @@ private: /** * Securely wipe memory */ - static void clean(const typename std::vector::iterator& i, const typename std::vector::iterator& j) { + static void clean(const typename std::vector::iterator& i, const typename std::vector::iterator& j) + { volatile uint8_t* b = reinterpret_cast(&*i); volatile uint8_t* e = reinterpret_cast(&*j); std::fill(b, e, 0); @@ -110,5 +117,5 @@ private: using SecureBlob = secure_vector; -} -} +} // namespace crypto +} // namespace dht diff --git a/include/opendht/default_types.h b/include/opendht/default_types.h index 68581cb1..5862185d 100644 --- a/include/opendht/default_types.h +++ b/include/opendht/default_types.h @@ -1,32 +1,12 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "value.h" #include "sockaddr.h" namespace dht { -enum class ImStatus : uint8_t { - NONE = 0, - TYPING, - RECEIVED, - READ -}; +enum class ImStatus : uint8_t { NONE = 0, TYPING, RECEIVED, READ }; } MSGPACK_ADD_ENUM(dht::ImStatus) @@ -37,11 +17,12 @@ class OPENDHT_PUBLIC DhtMessage : public Value::Serializable public: static const ValueType TYPE; - DhtMessage(const std::string& s = {}, const Blob& msg = {}) : service(s), data(msg) {} + DhtMessage(const std::string& s = {}, const Blob& msg = {}) + : service(s) + , data(msg) + {} - std::string getService() const { - return service; - } + std::string getService() const { return service; } static Value::Filter getFilter() { return {}; } @@ -50,21 +31,22 @@ public: static Value::Filter ServiceFilter(const std::string& s); /** print value for debugging */ - friend std::ostream& operator<< (std::ostream&, const DhtMessage&); + friend std::ostream& operator<<(std::ostream&, const DhtMessage&); std::string service; Blob data; MSGPACK_DEFINE(service, data) }; -template +template class SignedValue : public Value::Serializable { private: using BaseClass = Value::Serializable; public: - virtual void unpackValue(const Value& v) override { + virtual void unpackValue(const Value& v) override + { if (v.owner) { owner = v.owner; from = v.owner->getId(); @@ -74,22 +56,26 @@ public: BaseClass::unpackValue(v); } - static Value::Filter getFilter() { - return [](const Value& v){ return v.isSigned(); }; + static Value::Filter getFilter() + { + return [](const Value& v) { + return v.isSigned(); + }; } Sp owner; dht::InfoHash from; }; -template +template class EncryptedValue : public SignedValue { public: using BaseClass = SignedValue; public: - virtual void unpackValue(const Value& v) override { + virtual void unpackValue(const Value& v) override + { if (!v.recipient) { throw std::runtime_error("Value has no recipient"); } @@ -97,11 +83,10 @@ public: BaseClass::unpackValue(v); } - static Value::Filter getFilter() { - return Value::Filter::chain( - BaseClass::getFilter(), - [](const Value& v) { return static_cast(v.recipient); } - ); + static Value::Filter getFilter() + { + return Value::Filter::chain(BaseClass::getFilter(), + [](const Value& v) { return static_cast(v.recipient); }); } dht::InfoHash to; @@ -117,20 +102,31 @@ public: ImMessage() {} ImMessage(dht::Value::Id id, std::string&& m, long d = 0) - : id(id), msg(std::move(m)), date(d) {} - ImMessage(dht::Value::Id id, std::string &&dt, std::string &&m, long d = 0) - : id(id), msg(std::move(m)), datatype(std::move(dt)), date(d) {} - ImMessage(dht::Value::Id id, std::string &&dt, std::string &&m, std::map &&md, long d = 0) - : id(id), msg(std::move(m)), datatype(std::move(dt)), metadatas(std::move(md)), date(d) {} + : id(id) + , msg(std::move(m)) + , date(d) + {} + ImMessage(dht::Value::Id id, std::string&& dt, std::string&& m, long d = 0) + : id(id) + , msg(std::move(m)) + , datatype(std::move(dt)) + , date(d) + {} + ImMessage(dht::Value::Id id, std::string&& dt, std::string&& m, std::map&& md, long d = 0) + : id(id) + , msg(std::move(m)) + , datatype(std::move(dt)) + , metadatas(std::move(md)) + , date(d) + {} - virtual void unpackValue(const Value& v) override { + virtual void unpackValue(const Value& v) override + { to = v.recipient; SignedValue::unpackValue(v); } - static Value::Filter getFilter() { - return SignedValue::getFilter(); - } + static Value::Filter getFilter() { return SignedValue::getFilter(); } dht::InfoHash to; dht::Value::Id id {0}; @@ -152,12 +148,17 @@ public: static const ValueType TYPE; TrustRequest() {} - TrustRequest(std::string s, std::string ci = {}) : service(s), conversationId(ci) {} - TrustRequest(std::string s, std::string ci, const Blob& d) : service(s), conversationId(ci), payload(d) {} + TrustRequest(std::string s, std::string ci = {}) + : service(s) + , conversationId(ci) + {} + TrustRequest(std::string s, std::string ci, const Blob& d) + : service(s) + , conversationId(ci) + , payload(d) + {} - static Value::Filter getFilter() { - return EncryptedValue::getFilter(); - } + static Value::Filter getFilter() { return EncryptedValue::getFilter(); } std::string service; std::string conversationId; @@ -175,20 +176,21 @@ public: static const ValueType TYPE; IceCandidates() {} - IceCandidates(Value::Id msg_id, Blob ice) : id(msg_id), ice_data(ice) {} + IceCandidates(Value::Id msg_id, Blob ice) + : id(msg_id) + , ice_data(ice) + {} - static Value::Filter getFilter() { - return EncryptedValue::getFilter(); - } + static Value::Filter getFilter() { return EncryptedValue::getFilter(); } - template + template void msgpack_pack(Packer& pk) const { pk.pack_array(2); pk.pack(id); #if 1 pk.pack_bin(ice_data.size()); - pk.pack_bin_body((const char*)ice_data.data(), ice_data.size()); + pk.pack_bin_body((const char*) ice_data.data(), ice_data.size()); #else // hack for backward compatibility with old opendht compiled with msgpack 1.0 // remove when enough people have moved to new versions @@ -200,8 +202,10 @@ public: virtual void msgpack_unpack(const msgpack::object& o) { - if (o.type != msgpack::type::ARRAY) throw msgpack::type_error(); - if (o.via.array.size < 2) throw msgpack::type_error(); + if (o.type != msgpack::type::ARRAY) + throw msgpack::type_error(); + if (o.via.array.size < 2) + throw msgpack::type_error(); id = o.via.array.ptr[0].as(); ice_data = unpackBlob(o.via.array.ptr[1]); } @@ -220,59 +224,51 @@ private: public: static const ValueType TYPE; - IpServiceAnnouncement(sa_family_t family = AF_UNSPEC, in_port_t p = 0) { + IpServiceAnnouncement(sa_family_t family = AF_UNSPEC, in_port_t p = 0) + { addr.setFamily(family); addr.setPort(p); } - IpServiceAnnouncement(const SockAddr& sa) : addr(sa) {} + IpServiceAnnouncement(const SockAddr& sa) + : addr(sa) + {} - IpServiceAnnouncement(const Blob& b) { - msgpack_unpack(unpackMsg(b).get()); - } + IpServiceAnnouncement(const Blob& b) { msgpack_unpack(unpackMsg(b).get()); } - template + template void msgpack_pack(Packer& pk) const { pk.pack_bin(addr.getLength()); - pk.pack_bin_body((const char*)addr.get(), addr.getLength()); + pk.pack_bin_body((const char*) addr.get(), addr.getLength()); } virtual void msgpack_unpack(const msgpack::object& o) { if (o.type == msgpack::type::BIN) - addr = {(sockaddr*)o.via.bin.ptr, (socklen_t)o.via.bin.size}; + addr = {(sockaddr*) o.via.bin.ptr, (socklen_t) o.via.bin.size}; else throw msgpack::type_error(); } - in_port_t getPort() const { - return addr.getPort(); - } - void setPort(in_port_t p) { - addr.setPort(p); - } + in_port_t getPort() const { return addr.getPort(); } + void setPort(in_port_t p) { addr.setPort(p); } - const SockAddr& getPeerAddr() const { - return addr; - } + const SockAddr& getPeerAddr() const { return addr; } - virtual const ValueType& getType() const { - return TYPE; - } + virtual const ValueType& getType() const { return TYPE; } static bool storePolicy(InfoHash, std::shared_ptr&, const InfoHash&, const SockAddr&); /** print value for debugging */ - friend std::ostream& operator<< (std::ostream&, const IpServiceAnnouncement&); + friend std::ostream& operator<<(std::ostream&, const IpServiceAnnouncement&); private: SockAddr addr; }; - OPENDHT_PUBLIC extern const std::array, 5> DEFAULT_TYPES; OPENDHT_PUBLIC extern const std::array, 1> DEFAULT_INSECURE_TYPES; -} +} // namespace dht diff --git a/include/opendht/dht.h b/include/opendht/dht.h index c553a61a..4b594e9e 100644 --- a/include/opendht/dht.h +++ b/include/opendht/dht.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "infohash.h" @@ -56,13 +41,17 @@ struct LocalListener; * Must be given open UDP sockets and ::periodic must be * called regularly. */ -class OPENDHT_PUBLIC Dht final : public DhtInterface { +class OPENDHT_PUBLIC Dht final : public DhtInterface +{ public: /** * Initialise the Dht with two open sockets (for IPv4 and IP6) * and an ID for the node. */ - Dht(std::unique_ptr&& sock, const Config& config, const Sp& l = {}, std::unique_ptr&& rd = {}); + Dht(std::unique_ptr&& sock, + const Config& config, + const Sp& l = {}, + std::unique_ptr&& rd = {}); virtual ~Dht(); @@ -70,22 +59,16 @@ public: * Get the ID of the node. */ inline const InfoHash& getNodeId() const override { return myid; } - void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { - publicAddressChangedCb_ = std::move(cb); - } + void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { publicAddressChangedCb_ = std::move(cb); } NodeStatus updateStatus(sa_family_t af) override; /** * Get the current status of the node for the given family. */ - NodeStatus getStatus(sa_family_t af) const override { - return dht(af).status; - } + NodeStatus getStatus(sa_family_t af) const override { return dht(af).status; } - NodeStatus getStatus() const override { - return std::max(getStatus(AF_INET), getStatus(AF_INET6)); - } + NodeStatus getStatus() const override { return std::max(getStatus(AF_INET), getStatus(AF_INET6)); } net::DatagramSocket* getSocket() const override { return network_engine.getSocket(); }; @@ -102,21 +85,16 @@ public: */ bool isRunning(sa_family_t af = 0) const override; - virtual void registerType(const ValueType& type) override { - types.registerType(type); - } - const ValueType& getType(ValueType::Id type_id) const override { - return types.getType(type_id); - } + virtual void registerType(const ValueType& type) override { types.registerType(type); } + const ValueType& getType(ValueType::Id type_id) const override { return types.getType(type_id); } - void addBootstrap(const std::string& host, const std::string& service) override { + void addBootstrap(const std::string& host, const std::string& service) override + { bootstrap_nodes.emplace_back(host, service); startBootstrap(); } - void clearBootstrap() override { - bootstrap_nodes.clear(); - } + void clearBootstrap() override { bootstrap_nodes.clear(); } /** * Insert a node in the main routing table. @@ -124,14 +102,14 @@ public: * used to bootstrap efficiently from previously known nodes. */ void insertNode(const InfoHash& id, const SockAddr&) override; - void insertNode(const NodeExport& n) override { - insertNode(n.id, n.addr); - } + void insertNode(const NodeExport& n) override { insertNode(n.id, n.addr); } - void pingNode(SockAddr, DoneCallbackSimple&& cb={}) override; + void pingNode(SockAddr, DoneCallbackSimple&& cb = {}) override; - time_point periodic(const uint8_t *buf, size_t buflen, SockAddr, const time_point& now) override; - time_point periodic(const uint8_t *buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override { + time_point periodic(const uint8_t* buf, size_t buflen, SockAddr, const time_point& now) override; + time_point periodic( + const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override + { return periodic(buf, buflen, SockAddr(from, fromlen), now); } @@ -145,14 +123,30 @@ public: cb and donecb won't be called again afterward. * @param f a filter function used to prefilter values. */ - virtual void get(const InfoHash& key, GetCallback cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override; - virtual void get(const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f={}, Where&& w = {}) override { + virtual void get( + const InfoHash& key, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {}) override; + virtual void get(const InfoHash& key, + GetCallback cb, + DoneCallbackSimple donecb = {}, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(key, cb, bindDoneCb(donecb), std::forward(f), std::forward(w)); } - virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override { + virtual void get(const InfoHash& key, + GetCallbackSimple cb, + DoneCallback donecb = {}, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(key, bindGetCb(cb), donecb, std::forward(f), std::forward(w)); } - virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) override { + virtual void get(const InfoHash& key, + GetCallbackSimple cb, + DoneCallbackSimple donecb, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(key, bindGetCb(cb), bindDoneCb(donecb), std::forward(f), std::forward(w)); } /** @@ -166,7 +160,8 @@ public: * response. */ virtual void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override; - virtual void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override { + virtual void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override + { query(key, cb, bindDoneCb(done_cb), std::forward(q)); } @@ -187,32 +182,32 @@ public: * The done callback will be called once, when the first announce succeeds, or fails. */ void put(const InfoHash& key, - Sp, - DoneCallback cb=nullptr, - time_point created=time_point::max(), - bool permanent = false) override; + Sp, + DoneCallback cb = nullptr, + time_point created = time_point::max(), + bool permanent = false) override; void put(const InfoHash& key, - const Sp& v, - DoneCallbackSimple cb, - time_point created=time_point::max(), - bool permanent = false) override + const Sp& v, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) override { put(key, v, bindDoneCb(cb), created, permanent); } void put(const InfoHash& key, - Value&& v, - DoneCallback cb=nullptr, - time_point created=time_point::max(), - bool permanent = false) override + Value&& v, + DoneCallback cb = nullptr, + time_point created = time_point::max(), + bool permanent = false) override { put(key, std::make_shared(std::move(v)), cb, created, permanent); } void put(const InfoHash& key, - Value&& v, - DoneCallbackSimple cb, - time_point created=time_point::max(), - bool permanent = false) override + Value&& v, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) override { put(key, std::forward(v), bindDoneCb(cb), created, permanent); } @@ -240,16 +235,22 @@ public: * * @return a token to cancel the listener later. */ - size_t listen(const InfoHash&, ValueCallback, Value::Filter={}, Where={}) override; + size_t listen(const InfoHash&, ValueCallback, Value::Filter = {}, Where = {}) override; - size_t listen(const InfoHash& key, GetCallback cb, Value::Filter f={}, Where w={}) override { - return listen(key, [cb](const std::vector>& vals, bool expired){ - if (not expired) - return cb(vals); - return true; - }, std::forward(f), std::forward(w)); + size_t listen(const InfoHash& key, GetCallback cb, Value::Filter f = {}, Where w = {}) override + { + return listen( + key, + [cb](const std::vector>& vals, bool expired) { + if (not expired) + return cb(vals); + return true; + }, + std::forward(f), + std::forward(w)); } - size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w={}) override { + size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) override + { return listen(key, bindGetCb(cb), std::forward(f), std::forward(w)); } @@ -261,7 +262,8 @@ public: * The DHT will recontact neighbor nodes, re-register for listen ops etc. */ void connectivityChanged(sa_family_t) override; - void connectivityChanged() override { + void connectivityChanged() override + { connectivityChanged(AF_INET); connectivityChanged(AF_INET6); } @@ -288,37 +290,32 @@ public: std::string getSearchLog(const InfoHash&, sa_family_t af = AF_UNSPEC) const override; void dumpTables() const override; - std::vector getNodeMessageStats(bool in = false) override { + std::vector getNodeMessageStats(bool in = false) override + { return network_engine.getNodeMessageStats(in); } /** * Set the in-memory storage limit in bytes */ - void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) override { - max_store_size = limit; - } - size_t getStorageLimit() const override { - return max_store_size; - } + void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) override { max_store_size = limit; } + size_t getStorageLimit() const override { return max_store_size; } /** * Returns the total memory usage of stored values and the number * of stored values. */ - std::pair getStoreSize() const override { - return {total_store_size, total_values}; - } + std::pair getStoreSize() const override { return {total_store_size, total_values}; } std::vector getPublicAddress(sa_family_t family = 0) override; - PushNotificationResult pushNotificationReceived(const std::map&) override { + PushNotificationResult pushNotificationReceived(const std::map&) override + { return PushNotificationResult::IgnoredDisabled; } void resubscribe(unsigned) {} private: - /* When performing a search, we search for up to SEARCH_NODES closest nodes to the destination, and use the additional ones to backtrack if any of the target 8 turn out to be dead. */ @@ -384,7 +381,8 @@ private: using SearchMap = std::map>; using ReportedAddr = std::pair; - struct Kad { + struct Kad + { RoutingTable buckets {}; SearchMap searches {}; unsigned pending_pings {0}; @@ -399,7 +397,7 @@ private: Kad dht6 {}; PublicAddressChangedCb publicAddressChangedCb_ {}; - std::vector> bootstrap_nodes {}; + std::vector> bootstrap_nodes {}; std::chrono::steady_clock::duration bootstrap_period {BOOTSTRAP_PERIOD}; Sp bootstrapJob {}; @@ -418,7 +416,6 @@ private: std::map> listeners {}; size_t listener_token {1}; - // timing Scheduler scheduler; Sp nextNodesConfirmation {}; @@ -436,7 +433,8 @@ private: const bool maintain_storage {false}; const bool public_stable {false}; - inline const duration& getListenExpiration() const { + inline const duration& getListenExpiration() const + { return public_stable ? LISTEN_EXPIRE_TIME_PUBLIC : LISTEN_EXPIRE_TIME; } @@ -449,7 +447,11 @@ private: // Storage void storageAddListener(const InfoHash& id, const Sp& node, size_t tid, Query&& = {}, int version = 0); - bool storageStore(const InfoHash& id, const Sp& value, time_point created, const SockAddr& sa = {}, bool permanent = false); + bool storageStore(const InfoHash& id, + const Sp& value, + time_point created, + const SockAddr& sa = {}, + bool permanent = false); bool storageRefresh(const InfoHash& id, Value::Id vid); void expireStore(); void expireStorage(InfoHash h); @@ -465,19 +467,21 @@ private: * nodes. */ void dataPersistence(InfoHash id); - size_t maintainStorage(decltype(store)::value_type&, bool force=false, const DoneCallback& donecb={}); + size_t maintainStorage(decltype(store)::value_type&, bool force = false, const DoneCallback& donecb = {}); // Buckets Kad& dht(sa_family_t af) { return af == AF_INET ? dht4 : dht6; } const Kad& dht(sa_family_t af) const { return af == AF_INET ? dht4 : dht6; } RoutingTable& buckets(sa_family_t af) { return dht(af).buckets; } const RoutingTable& buckets(sa_family_t af) const { return dht(af).buckets; } - Bucket* findBucket(const InfoHash& id, sa_family_t af) { + Bucket* findBucket(const InfoHash& id, sa_family_t af) + { auto& b = buckets(af); auto it = b.findBucket(id); return it == b.end() ? nullptr : &(*it); } - const Bucket* findBucket(const InfoHash& id, sa_family_t af) const { + const Bucket* findBucket(const InfoHash& id, sa_family_t af) const + { return const_cast(this)->findBucket(id, af); } @@ -502,9 +506,20 @@ private: * Low-level method that will perform a search on the DHT for the specified * infohash (id), using the specified IP version (IPv4 or IPv6). */ - Sp search(const InfoHash& id, sa_family_t af, GetCallback = {}, QueryCallback = {}, DoneCallback = {}, Value::Filter = {}, const Sp& q = {}); + Sp search(const InfoHash& id, + sa_family_t af, + GetCallback = {}, + QueryCallback = {}, + DoneCallback = {}, + Value::Filter = {}, + const Sp& q = {}); - void announce(const InfoHash& id, sa_family_t af, Sp value, DoneCallback callback, time_point created=time_point::max(), bool permanent = false); + void announce(const InfoHash& id, + sa_family_t af, + Sp value, + DoneCallback callback, + time_point created = time_point::max(), + bool permanent = false); size_t listenTo(const InfoHash& id, sa_family_t af, ValueCallback cb, Value::Filter f = {}, const Sp& q = {}); /** @@ -532,9 +547,9 @@ private: * @param query The query sent to the node. */ void searchNodeGetDone(const net::Request& status, - net::RequestAnswer&& answer, - std::weak_ptr ws, - Sp query); + net::RequestAnswer&& answer, + std::weak_ptr ws, + Sp query); /** * Generic function to execute when a 'get' request expires. @@ -559,7 +574,7 @@ private: /** * If update is true, this method will also send message to synced but non-updated search nodes. */ - SearchNode* searchSendGetValues(Sp sr, SearchNode *n = nullptr, bool update = true); + SearchNode* searchSendGetValues(Sp sr, SearchNode* n = nullptr, bool update = true); /** * Forwards an 'announce' request for a list of nodes to the network engine. @@ -591,41 +606,22 @@ private: net::RequestAnswer onPing(Sp node); /* when we receive a "find node" request */ net::RequestAnswer onFindNode(Sp node, const InfoHash& hash, want_t want); - void onFindNodeDone(const Sp& status, - net::RequestAnswer& a, - Sp sr); + void onFindNodeDone(const Sp& status, net::RequestAnswer& a, Sp sr); /* when we receive a "get values" request */ - net::RequestAnswer onGetValues(Sp node, - const InfoHash& hash, - want_t want, - const Query& q); - void onGetValuesDone(const Sp& status, - net::RequestAnswer& a, - Sp& sr, - const Sp& orig_query); + net::RequestAnswer onGetValues(Sp node, const InfoHash& hash, want_t want, const Query& q); + void onGetValuesDone(const Sp& status, net::RequestAnswer& a, Sp& sr, const Sp& orig_query); /* when we receive a listen request */ - net::RequestAnswer onListen(Sp node, - const InfoHash& hash, - const Blob& token, - size_t socket_id, - const Query& query, - int version = 0); - void onListenDone(const Sp& status, - net::RequestAnswer& a, - Sp& sr); + net::RequestAnswer onListen( + Sp node, const InfoHash& hash, const Blob& token, size_t socket_id, const Query& query, int version = 0); + void onListenDone(const Sp& status, net::RequestAnswer& a, Sp& sr); /* when we receive an announce request */ net::RequestAnswer onAnnounce(Sp node, - const InfoHash& hash, - const Blob& token, - const std::vector>& v, - const time_point& created); - net::RequestAnswer onRefresh(Sp node, - const InfoHash& hash, - const Blob& token, - const Value::Id& vid); - void onAnnounceDone(const Sp& status, - net::RequestAnswer& a, - Sp& sr); + const InfoHash& hash, + const Blob& token, + const std::vector>& v, + const time_point& created); + net::RequestAnswer onRefresh(Sp node, const InfoHash& hash, const Blob& token, const Value::Id& vid); + void onAnnounceDone(const Sp& status, net::RequestAnswer& a, Sp& sr); }; -} +} // namespace dht diff --git a/include/opendht/dht_interface.h b/include/opendht/dht_interface.h index 3ea4f063..bf8b1102 100644 --- a/include/opendht/dht_interface.h +++ b/include/opendht/dht_interface.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "infohash.h" @@ -26,14 +11,19 @@ namespace dht { namespace net { - class DatagramSocket; +class DatagramSocket; } -class OPENDHT_PUBLIC DhtInterface { +class OPENDHT_PUBLIC DhtInterface +{ public: DhtInterface() = default; - DhtInterface(const Logger& l) : logger_(std::make_shared(l)) {} - DhtInterface(const std::shared_ptr& l) : logger_(l) {} + DhtInterface(const Logger& l) + : logger_(std::make_shared(l)) + {} + DhtInterface(const std::shared_ptr& l) + : logger_(l) + {} virtual ~DhtInterface() = default; // [[deprecated]] @@ -48,9 +38,7 @@ public: virtual NodeStatus getStatus(sa_family_t af) const = 0; virtual NodeStatus getStatus() const = 0; - void addOnConnectedCallback(std::function cb) { - onConnectCallbacks_.emplace(std::move(cb)); - } + void addOnConnectedCallback(std::function cb) { onConnectCallbacks_.emplace(std::move(cb)); } virtual void setOnPublicAddressChanged(PublicAddressChangedCb) {} virtual net::DatagramSocket* getSocket() const { return {}; } @@ -90,10 +78,12 @@ public: virtual void insertNode(const InfoHash& id, const SockAddr&) = 0; virtual void insertNode(const NodeExport& n) = 0; - virtual void pingNode(SockAddr, DoneCallbackSimple&& cb={}) = 0; + virtual void pingNode(SockAddr, DoneCallbackSimple&& cb = {}) = 0; - virtual time_point periodic(const uint8_t *buf, size_t buflen, SockAddr, const time_point& now) = 0; - virtual time_point periodic(const uint8_t *buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) = 0; + virtual time_point periodic(const uint8_t* buf, size_t buflen, SockAddr, const time_point& now) = 0; + virtual time_point periodic( + const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) + = 0; /** * Get a value by searching on all available protocols (IPv4, IPv6), @@ -105,10 +95,18 @@ public: cb and donecb won't be called again afterward. * @param f a filter function used to prefilter values. */ - virtual void get(const InfoHash& key, GetCallback cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0; - virtual void get(const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0; - virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) = 0; - virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) = 0; + virtual void get( + const InfoHash& key, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {}) + = 0; + virtual void get( + const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb = {}, Value::Filter&& f = {}, Where&& w = {}) + = 0; + virtual void get( + const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {}) + = 0; + virtual void get( + const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f = {}, Where&& w = {}) + = 0; /** * Similar to Dht::get, but sends a Query to filter data remotely. @@ -140,25 +138,29 @@ public: * The done callback will be called once, when the first announce succeeds, or fails. */ virtual void put(const InfoHash& key, - Sp, - DoneCallback cb=nullptr, - time_point created=time_point::max(), - bool permanent = false) = 0; + Sp, + DoneCallback cb = nullptr, + time_point created = time_point::max(), + bool permanent = false) + = 0; virtual void put(const InfoHash& key, - const Sp& v, - DoneCallbackSimple cb, - time_point created=time_point::max(), - bool permanent = false) = 0; + const Sp& v, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) + = 0; virtual void put(const InfoHash& key, - Value&& v, - DoneCallback cb=nullptr, - time_point created=time_point::max(), - bool permanent = false) = 0; + Value&& v, + DoneCallback cb = nullptr, + time_point created = time_point::max(), + bool permanent = false) + = 0; virtual void put(const InfoHash& key, - Value&& v, - DoneCallbackSimple cb, - time_point created=time_point::max(), - bool permanent = false) = 0; + Value&& v, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) + = 0; /** * Get data currently being put at the given hash. @@ -183,9 +185,9 @@ public: * * @return a token to cancel the listener later. */ - virtual size_t listen(const InfoHash&, GetCallback, Value::Filter={}, Where w = {}) = 0; - virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w = {}) = 0; - virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter={}, Where w = {}) = 0; + virtual size_t listen(const InfoHash&, GetCallback, Value::Filter = {}, Where w = {}) = 0; + virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) = 0; + virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter = {}, Where w = {}) = 0; virtual bool cancelListen(const InfoHash&, size_t token) = 0; @@ -232,16 +234,15 @@ public: virtual std::vector getPublicAddress(sa_family_t family = 0) = 0; - virtual void setLogger(const Logger& l) { + virtual void setLogger(const Logger& l) + { if (logger_) *logger_ = l; else - logger_= std::make_shared(l); + logger_ = std::make_shared(l); } - virtual void setLogger(const std::shared_ptr& l) { - logger_ = l; - } + virtual void setLogger(const std::shared_ptr& l) { logger_ = l; } /** * Only print logs related to the given InfoHash (if given), or disable filter (if zeroes). diff --git a/include/opendht/dht_proxy_client.h b/include/opendht/dht_proxy_client.h index f3b3946c..8a022452 100644 --- a/include/opendht/dht_proxy_client.h +++ b/include/opendht/dht_proxy_client.h @@ -1,22 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * Adrien Béraud - * Vsevolod Ivanov - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include @@ -42,33 +25,32 @@ class Value; namespace http { class Resolver; class Request; -} +} // namespace http namespace dht { -class OPENDHT_PUBLIC DhtProxyClient final : public DhtInterface { +class OPENDHT_PUBLIC DhtProxyClient final : public DhtInterface +{ public: - DhtProxyClient(); - explicit DhtProxyClient( - std::shared_ptr serverCA, - crypto::Identity clientIdentity, - std::function loopSignal, - const std::string& serverHost, - const std::string& userAgent = "", - const std::string& pushClientId = "", - const std::string& pushToken = "", - const std::string& pushTopic = "", - const std::string& pushPlatform = "", - std::shared_ptr logger = {} - ); + explicit DhtProxyClient(std::shared_ptr serverCA, + crypto::Identity clientIdentity, + std::function loopSignal, + const std::string& serverHost, + const std::string& userAgent = "", + const std::string& pushClientId = "", + const std::string& pushToken = "", + const std::string& pushTopic = "", + const std::string& pushPlatform = "", + std::shared_ptr logger = {}); void setHeaderFields(http::Request& request); virtual void setPushNotificationToken(const std::string& token) override; - virtual void setPushNotificationTopic(const std::string& topic) override { + virtual void setPushNotificationTopic(const std::string& topic) override + { #ifdef OPENDHT_PUSH_NOTIFICATIONS notificationTopic_ = topic; #else @@ -76,7 +58,8 @@ public: #endif } - virtual void setPushNotificationPlatform(const std::string& platform) override { + virtual void setPushNotificationPlatform(const std::string& platform) override + { #ifdef OPENDHT_PUSH_NOTIFICATIONS platform_ = platform; #else @@ -90,17 +73,13 @@ public: * Get the ID of the node. */ inline const InfoHash& getNodeId() const override { return myid; } - void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { - publicAddressChangedCb_ = std::move(cb); - } + void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { publicAddressChangedCb_ = std::move(cb); } /** * Get the current status of the node for the given family. */ NodeStatus getStatus(sa_family_t af) const override; - NodeStatus getStatus() const override { - return std::max(getStatus(AF_INET), getStatus(AF_INET6)); - } + NodeStatus getStatus() const override { return std::max(getStatus(AF_INET), getStatus(AF_INET6)); } /** * Performs final operations before quitting. @@ -125,14 +104,30 @@ public: cb and donecb won't be called again afterward. * @param f a filter function used to prefilter values. */ - virtual void get(const InfoHash& key, GetCallback cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override; - virtual void get(const InfoHash& key, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f={}, Where&& w = {}) override { + virtual void get( + const InfoHash& key, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& f = {}, Where&& w = {}) override; + virtual void get(const InfoHash& key, + GetCallback cb, + DoneCallbackSimple donecb = {}, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(key, cb, bindDoneCb(std::move(donecb)), std::forward(f), std::forward(w)); } - virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override { + virtual void get(const InfoHash& key, + GetCallbackSimple cb, + DoneCallback donecb = {}, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(key, bindGetCb(cb), std::move(donecb), std::forward(f), std::forward(w)); } - virtual void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) override { + virtual void get(const InfoHash& key, + GetCallbackSimple cb, + DoneCallbackSimple donecb, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(key, bindGetCb(cb), bindDoneCb(std::move(donecb)), std::forward(f), std::forward(w)); } @@ -144,32 +139,32 @@ public: * NOTE: For now, created parameter is ignored. */ void put(const InfoHash& key, - Sp, - DoneCallback cb=nullptr, - time_point created=time_point::max(), - bool permanent = false) override; + Sp, + DoneCallback cb = nullptr, + time_point created = time_point::max(), + bool permanent = false) override; void put(const InfoHash& key, - const Sp& v, - DoneCallbackSimple cb, - time_point created=time_point::max(), - bool permanent = false) override + const Sp& v, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) override { put(key, v, bindDoneCb(std::move(cb)), created, permanent); } void put(const InfoHash& key, - Value&& v, - DoneCallback cb=nullptr, - time_point created=time_point::max(), - bool permanent = false) override + Value&& v, + DoneCallback cb = nullptr, + time_point created = time_point::max(), + bool permanent = false) override { put(key, std::make_shared(std::move(v)), std::move(cb), created, permanent); } void put(const InfoHash& key, - Value&& v, - DoneCallbackSimple cb, - time_point created=time_point::max(), - bool permanent = false) override + Value&& v, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) override { put(key, std::forward(v), bindDoneCb(std::move(cb)), created, permanent); } @@ -193,16 +188,22 @@ public: * * @return a token to cancel the listener later. */ - virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter={}, Where={}) override; + virtual size_t listen(const InfoHash&, ValueCallback, Value::Filter = {}, Where = {}) override; - virtual size_t listen(const InfoHash& key, GetCallback cb, Value::Filter f={}, Where w={}) override { - return listen(key, [cb=std::move(cb)](const std::vector>& vals, bool expired){ - if (not expired) - return cb(vals); - return true; - }, std::forward(f), std::forward(w)); + virtual size_t listen(const InfoHash& key, GetCallback cb, Value::Filter f = {}, Where w = {}) override + { + return listen( + key, + [cb = std::move(cb)](const std::vector>& vals, bool expired) { + if (not expired) + return cb(vals); + return true; + }, + std::forward(f), + std::forward(w)); } - virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w={}) override { + virtual size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) override + { return listen(key, bindGetCb(std::move(cb)), std::forward(f), std::forward(w)); } /* @@ -218,7 +219,9 @@ public: PushNotificationResult pushNotificationReceived(const std::map& notification) override; time_point periodic(const uint8_t*, size_t, SockAddr, const time_point& now) override; - time_point periodic(const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override { + time_point periodic( + const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override + { return periodic(buf, buflen, SockAddr(from, fromlen), now); } @@ -232,8 +235,13 @@ public: * @param q a query used to filter values on the remotes before they send a * response. */ - virtual void query(const InfoHash& /*key*/, QueryCallback /*cb*/, DoneCallback /*done_cb*/ = {}, Query&& /*q*/ = {}) override { } - virtual void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override { + virtual void query(const InfoHash& /*key*/, + QueryCallback /*cb*/, + DoneCallback /*done_cb*/ = {}, + Query&& /*q*/ = {}) override + {} + virtual void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override + { query(key, cb, bindDoneCb(std::move(done_cb)), std::forward(q)); } @@ -253,14 +261,10 @@ public: */ bool cancelPut(const InfoHash&, const Value::Id&) override; - void pingNode(SockAddr, DoneCallbackSimple&& /*cb*/={}) override { } + void pingNode(SockAddr, DoneCallbackSimple&& /*cb*/ = {}) override {} - virtual void registerType(const ValueType& type) override { - types.registerType(type); - } - const ValueType& getType(ValueType::Id type_id) const override { - return types.getType(type_id); - } + virtual void registerType(const ValueType& type) override { types.registerType(type); } + const ValueType& getType(ValueType::Id type_id) const override { return types.getType(type_id); } std::vector> getLocal(const InfoHash& k, const Value::Filter& filter) const override; Sp getLocalById(const InfoHash& k, Value::Id id) const override; @@ -269,8 +273,8 @@ public: * NOTE: The following methods will not be implemented because the * DhtProxyClient doesn't have any storage nor synchronization process */ - void insertNode(const InfoHash&, const SockAddr&) override { } - void insertNode(const NodeExport&) override { } + void insertNode(const InfoHash&, const SockAddr&) override {} + void insertNode(const NodeExport&) override {} std::pair getStoreSize() const override { return {}; } std::vector exportNodes() const override { return {}; } std::vector exportValues() const override { return {}; } @@ -284,17 +288,14 @@ public: std::vector getNodeMessageStats(bool) override { return {}; } void setStorageLimit(size_t) override {} virtual size_t getStorageLimit() const override { return 0; } - void connectivityChanged(sa_family_t) override { - getProxyInfos(); - } - void connectivityChanged() override { + void connectivityChanged(sa_family_t) override { getProxyInfos(); } + void connectivityChanged() override + { getProxyInfos(); loopSignal_(); } - void listenKeepIdle(uint32_t seconds) { - listenKeepIdle_ = seconds; - } + void listenKeepIdle(uint32_t seconds) { listenKeepIdle_ = seconds; } inline uint32_t listenKeepIdle() { return listenKeepIdle_; } private: @@ -310,13 +311,15 @@ private: */ struct InfoState; void getProxyInfos(); - void queryProxyInfo(const std::shared_ptr& infoState, const std::shared_ptr& resolver, sa_family_t family); + void queryProxyInfo(const std::shared_ptr& infoState, + const std::shared_ptr& resolver, + sa_family_t family); void onProxyInfos(const Json::Value& val, const sa_family_t family); SockAddr parsePublicAddress(const Json::Value& val); void opFailed(); - void handleExpireListener(const asio::error_code &ec, const InfoHash& key); + void handleExpireListener(const asio::error_code& ec, const InfoHash& key); struct Listener; struct OperationState; @@ -325,15 +328,21 @@ private: SUBSCRIBE, RESUBSCRIBE, }; - using CacheValueCallback = std::function>& values, bool expired, system_clock::time_point)>; + using CacheValueCallback + = std::function>& values, bool expired, system_clock::time_point)>; /** * Send Listen with httpClient_ */ - void sendListen(const restinio::http_request_header_t& header, const CacheValueCallback& cb, - const Sp& opstate, Listener& listener, ListenMethod method = ListenMethod::LISTEN); - void handleResubscribe(const asio::error_code& ec, const InfoHash& key, - const size_t token, std::shared_ptr opstate); + void sendListen(const restinio::http_request_header_t& header, + const CacheValueCallback& cb, + const Sp& opstate, + Listener& listener, + ListenMethod method = ListenMethod::LISTEN); + void handleResubscribe(const asio::error_code& ec, + const InfoHash& key, + const size_t token, + std::shared_ptr opstate); void doPut(const InfoHash&, Sp, DoneCallbackSimple, time_point created, bool permanent); void handleRefreshPut(const asio::error_code& ec, InfoHash key, Value::Id id); @@ -413,14 +422,14 @@ private: /** * Retrieve if we can connect to the proxy (update statusIpvX_) */ - void handleProxyConfirm(const asio::error_code &ec); + void handleProxyConfirm(const asio::error_code& ec); std::unique_ptr nextProxyConfirmationTimer_; std::unique_ptr listenerRestartTimer_; /** * Relaunch LISTEN requests if the client disconnect/reconnect. */ - void restartListeners(const asio::error_code &ec); + void restartListeners(const asio::error_code& ec); /** * Refresh a listen via a token @@ -444,12 +453,12 @@ private: */ std::string platform_ #ifdef __ANDROID__ - {"android"}; + {"android"}; #else #ifdef __APPLE__ - {"ios"}; + {"ios"}; #else - {}; + {}; #endif #endif @@ -466,4 +475,4 @@ private: std::shared_ptr buildRequest(const std::string& target = {}); }; -} +} // namespace dht diff --git a/include/opendht/dht_proxy_server.h b/include/opendht/dht_proxy_server.h index c71585e2..4ee7d0f8 100644 --- a/include/opendht/dht_proxy_server.h +++ b/include/opendht/dht_proxy_server.h @@ -1,22 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * Adrien Béraud - * Vsevolod Ivanov - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "callbacks.h" @@ -36,12 +19,7 @@ #include namespace dht { -enum class PushType { - None = 0, - Android, - iOS, - UnifiedPush -}; +enum class PushType { None = 0, Android, iOS, UnifiedPush }; } MSGPACK_ADD_ENUM(dht::PushType) @@ -54,14 +32,15 @@ namespace dht { namespace http { class Request; struct ListenerSession; -} +} // namespace http class DhtRunner; using RestRouter = restinio::router::express_router_t<>; using RequestStatus = restinio::request_handling_status_t; -struct OPENDHT_PUBLIC ProxyServerConfig { +struct OPENDHT_PUBLIC ProxyServerConfig +{ std::string address {}; in_port_t port {8000}; std::string pushServer {}; @@ -85,8 +64,8 @@ public: * it will fails silently */ DhtProxyServer(const std::shared_ptr& dht, - const ProxyServerConfig& config = {}, - const std::shared_ptr& logger = {}); + const ProxyServerConfig& config = {}, + const std::shared_ptr& logger = {}); virtual ~DhtProxyServer(); @@ -100,30 +79,35 @@ public: using clock = std::chrono::steady_clock; using time_point = clock::time_point; - struct PushStats { + struct PushStats + { uint64_t highPriorityCount {0}; uint64_t normalPriorityCount {0}; - void increment(bool highPriority) { + void increment(bool highPriority) + { if (highPriority) highPriorityCount++; else normalPriorityCount++; } - Json::Value toJson() const { + Json::Value toJson() const + { Json::Value val; val["highPriorityCount"] = static_cast(highPriorityCount); val["normalPriorityCount"] = static_cast(normalPriorityCount); return val; } - std::string toString() const { + std::string toString() const + { return fmt::format("{} high priority, {} normal priority", highPriorityCount, normalPriorityCount); } }; - struct OPENDHT_PUBLIC ServerStats { + struct OPENDHT_PUBLIC ServerStats + { /** Current number of listen operations */ size_t listenCount {0}; /** Current number of permanent put operations (hash used) */ @@ -138,7 +122,7 @@ public: /** Last time at which the stats were updated */ time_point lastUpdated; /** Total number of push notification requests that the server attempted to - * send since being started, broken down by type and priority level */ + * send since being started, broken down by type and priority level */ PushStats androidPush; PushStats iosPush; PushStats unifiedPush; @@ -167,13 +151,12 @@ private: struct RestRouterTraitsTls; struct RestRouterTraits; - template + template static HttpResponse initHttpResponse(HttpResponse response); static restinio::request_handling_status_t serverError(restinio::request_t& request); - template< typename ServerSettings > - void addServerSettings(ServerSettings& serverSettings, - const unsigned int max_pipelined_requests = 16); + template + void addServerSettings(ServerSettings& serverSettings, const unsigned int max_pipelined_requests = 16); std::unique_ptr createRestRouter(); @@ -186,8 +169,7 @@ private: * On error: HTTP 503, body: {"err":"xxxx"} * @param session */ - RequestStatus getNodeInfo(restinio::request_handle_t request, - restinio::router::route_params_t params) const; + RequestStatus getNodeInfo(restinio::request_handle_t request, restinio::router::route_params_t params) const; /** * Return ServerStats in JSON format @@ -195,8 +177,7 @@ private: * Result: HTTP 200, body: Node infos in JSON format * @param session */ - RequestStatus getStats(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus getStats(restinio::request_handle_t request, restinio::router::route_params_t params); /** * Return Values of an infoHash @@ -208,8 +189,7 @@ private: * On error: HTTP 503, body: {"err":"xxxx"} * @param session */ - RequestStatus get(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus get(restinio::request_handle_t request, restinio::router::route_params_t params); /** * Listen incoming Values of an infoHash. @@ -221,8 +201,7 @@ private: * On error: HTTP 503, body: {"err":"xxxx"} * @param session */ - RequestStatus listen(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus listen(restinio::request_handle_t request, restinio::router::route_params_t params); /** * Put a value on the DHT @@ -233,10 +212,9 @@ private: * HTTP 400, body: {"err":"xxxx"} if bad json or HTTP 502 if put fails * @param session */ - RequestStatus put(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus put(restinio::request_handle_t request, restinio::router::route_params_t params); - void handleCancelPermamentPut(const asio::error_code &ec, const InfoHash& key, Value::Id vid); + void handleCancelPermamentPut(const asio::error_code& ec, const InfoHash& key, Value::Id vid); #ifdef OPENDHT_PROXY_SERVER_IDENTITY /** @@ -248,8 +226,7 @@ private: * HTTP 400, body: {"err":"xxxx"} if bad json * @param session */ - RequestStatus putSigned(restinio::request_handle_t request, - restinio::router::route_params_t params) const; + RequestStatus putSigned(restinio::request_handle_t request, restinio::router::route_params_t params) const; /** * Put a value to encrypt by the proxy on the DHT @@ -260,8 +237,7 @@ private: * HTTP 400, body: {"err":"xxxx"} if bad json * @param session */ - RequestStatus putEncrypted(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus putEncrypted(restinio::request_handle_t request, restinio::router::route_params_t params); #endif // OPENDHT_PROXY_SERVER_IDENTITY @@ -275,8 +251,7 @@ private: * On error: HTTP 503, body: {"err":"xxxx"} * @param session */ - RequestStatus getFiltered(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus getFiltered(restinio::request_handle_t request, restinio::router::route_params_t params); /** * Respond allowed Methods @@ -285,21 +260,22 @@ private: * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS * @param session */ - RequestStatus options(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus options(restinio::request_handle_t request, restinio::router::route_params_t params); - struct PushSessionContext { + struct PushSessionContext + { std::mutex lock; std::string sessionId; - PushSessionContext(const std::string& id) : sessionId(id) {} + PushSessionContext(const std::string& id) + : sessionId(id) + {} }; #ifdef OPENDHT_PUSH_NOTIFICATIONS PushType getTypeFromString(const std::string& type); std::string getDefaultTopic(PushType type); - RequestStatus pingPush(restinio::request_handle_t request, - restinio::router::route_params_t /*params*/); + RequestStatus pingPush(restinio::request_handle_t request, restinio::router::route_params_t /*params*/); /** * Subscribe to push notifications for an iOS or Android device. * Method: SUBSCRIBE "/{InfoHash: .*}" @@ -309,8 +285,7 @@ private: * so you need to refresh the operation each six hours. * @param session */ - RequestStatus subscribe(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus subscribe(restinio::request_handle_t request, restinio::router::route_params_t params); /** * Unsubscribe to push notifications for an iOS or Android device. @@ -319,15 +294,15 @@ private: * Return: nothing * @param session */ - RequestStatus unsubscribe(restinio::request_handle_t request, - restinio::router::route_params_t params); + RequestStatus unsubscribe(restinio::request_handle_t request, restinio::router::route_params_t params); /** * Send a push notification via a gorush push gateway * @param key of the device * @param json, the content to send */ - void sendPushNotification(const std::string& key, Json::Value&& json, PushType type, bool highPriority, const std::string& topic); + void sendPushNotification( + const std::string& key, Json::Value&& json, PushType type, bool highPriority, const std::string& topic); /** * Send push notification with an expire timeout. @@ -337,8 +312,11 @@ private: * @param type * @param topic */ - void handleNotifyPushListenExpire(const asio::error_code &ec, const std::string pushToken, - std::function json, PushType type, const std::string& topic); + void handleNotifyPushListenExpire(const asio::error_code& ec, + const std::string pushToken, + std::function json, + PushType type, + const std::string& topic); /** * Remove a push listener between a client and a hash @@ -347,8 +325,10 @@ private: * @param key * @param clientId */ - void handleCancelPushListen(const asio::error_code &ec, const std::string pushToken, - const InfoHash key, const std::string clientId); + void handleCancelPushListen(const asio::error_code& ec, + const std::string pushToken, + const InfoHash key, + const std::string clientId); /** * Handles a push listen request. @@ -363,20 +343,24 @@ private: * @param expired A boolean indicating whether the push listen request has expired. * @return true. */ - bool handlePushListen(const InfoHash& infoHash, const std::string& pushToken, - PushType type, const std::string& clientId, - const std::shared_ptr& sessionCtx, const std::string& topic, - const std::vector>& values, bool expired); + bool handlePushListen(const InfoHash& infoHash, + const std::string& pushToken, + PushType type, + const std::string& clientId, + const std::shared_ptr& sessionCtx, + const std::string& topic, + const std::vector>& values, + bool expired); -#endif //OPENDHT_PUSH_NOTIFICATIONS +#endif // OPENDHT_PUSH_NOTIFICATIONS - void handlePrintStats(const asio::error_code &ec); + void handlePrintStats(const asio::error_code& ec); void updateStats(); - template + template void saveState(Os& stream); - template + template void loadState(Is& is, size_t size); std::shared_ptr ioContext_; @@ -415,7 +399,8 @@ private: std::map listeners_; // Connection Listener observing conn state changes. std::shared_ptr connListener_; - struct PermanentPut { + struct PermanentPut + { time_point expiration; std::string pushToken; std::string clientId; @@ -426,31 +411,40 @@ private: PushType type; std::string topic; - template + template void msgpack_pack(Packer& p) const { - p.pack_map(2 + (sessionCtx ? 1 : 0) + (clientId.empty() ? 0 : 1) + (type == PushType::None ? 0 : 2) + (topic.empty() ? 0 : 1)); - p.pack("value"); p.pack(value); - p.pack("exp"); p.pack(to_time_t(expiration)); + p.pack_map(2 + (sessionCtx ? 1 : 0) + (clientId.empty() ? 0 : 1) + (type == PushType::None ? 0 : 2) + + (topic.empty() ? 0 : 1)); + p.pack("value"); + p.pack(value); + p.pack("exp"); + p.pack(to_time_t(expiration)); if (not clientId.empty()) { - p.pack("cid"); p.pack(clientId); + p.pack("cid"); + p.pack(clientId); } if (sessionCtx) { std::lock_guard l(sessionCtx->lock); - p.pack("sid"); p.pack(sessionCtx->sessionId); + p.pack("sid"); + p.pack(sessionCtx->sessionId); } if (type != PushType::None) { - p.pack("t"); p.pack(type); - p.pack("token"); p.pack(pushToken); + p.pack("t"); + p.pack(type); + p.pack("token"); + p.pack(pushToken); } if (not topic.empty()) { - p.pack("top"); p.pack(topic); + p.pack("top"); + p.pack(topic); } } void msgpack_unpack(const msgpack::object& o); }; - struct SearchPuts { + struct SearchPuts + { std::map puts; MSGPACK_DEFINE_ARRAY(puts) }; @@ -464,7 +458,8 @@ private: std::string bundleId_; #ifdef OPENDHT_PUSH_NOTIFICATIONS - struct Listener { + struct Listener + { time_point expiration; std::string clientId; std::shared_ptr sessionCtx; @@ -474,30 +469,36 @@ private: PushType type; std::string topic; - template + template void msgpack_pack(Packer& p) const { p.pack_map(3 + (sessionCtx ? 1 : 0) + (topic.empty() ? 0 : 1)); - p.pack("cid"); p.pack(clientId); - p.pack("exp"); p.pack(to_time_t(expiration)); + p.pack("cid"); + p.pack(clientId); + p.pack("exp"); + p.pack(to_time_t(expiration)); if (sessionCtx) { std::lock_guard l(sessionCtx->lock); - p.pack("sid"); p.pack(sessionCtx->sessionId); + p.pack("sid"); + p.pack(sessionCtx->sessionId); } - p.pack("t"); p.pack(type); + p.pack("t"); + p.pack(type); if (!topic.empty()) { - p.pack("top"); p.pack(topic); + p.pack("top"); + p.pack(topic); } } void msgpack_unpack(const msgpack::object& o); }; - struct PushListener { + struct PushListener + { std::map> listeners; MSGPACK_DEFINE_ARRAY(listeners) }; std::map pushListeners_; -#endif //OPENDHT_PUSH_NOTIFICATIONS +#endif // OPENDHT_PUSH_NOTIFICATIONS }; -} +} // namespace dht diff --git a/include/opendht/dhtrunner.h b/include/opendht/dhtrunner.h index d1668f67..af44d466 100644 --- a/include/opendht/dhtrunner.h +++ b/include/opendht/dhtrunner.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" @@ -48,12 +33,13 @@ struct SecureDhtConfig; * either wait for (expectedly frequent) calls to ::loop() or start an internal * thread that will update the DHT when appropriate. */ -class OPENDHT_PUBLIC DhtRunner { - +class OPENDHT_PUBLIC DhtRunner +{ public: using StatusCallback = std::function; - struct Config { + struct Config + { SecureDhtConfig dht_config {}; bool threaded {true}; std::string proxy_server {}; @@ -69,7 +55,8 @@ public: SockAddr bind4 {}, bind6 {}; }; - struct Context { + struct Context + { std::shared_ptr logger {}; std::unique_ptr sock; std::shared_ptr peerDiscovery {}; @@ -85,196 +72,270 @@ public: DhtRunner(); virtual ~DhtRunner(); - void get(InfoHash id, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter f = {}, Where w = {}) { + void get(InfoHash id, GetCallbackSimple cb, DoneCallback donecb = {}, Value::Filter f = {}, Where w = {}) + { get(id, bindGetCb(cb), donecb, f, w); } - void get(InfoHash id, GetCallbackSimple cb, DoneCallbackSimple donecb={}, Value::Filter f = {}, Where w = {}) { + void get(InfoHash id, GetCallbackSimple cb, DoneCallbackSimple donecb = {}, Value::Filter f = {}, Where w = {}) + { get(id, bindGetCb(cb), donecb, f, w); } - void get(InfoHash hash, GetCallback vcb, DoneCallback dcb, Value::Filter f={}, Where w = {}); + void get(InfoHash hash, GetCallback vcb, DoneCallback dcb, Value::Filter f = {}, Where w = {}); - void get(InfoHash id, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter f = {}, Where w = {}) { + void get(InfoHash id, GetCallback cb, DoneCallbackSimple donecb = {}, Value::Filter f = {}, Where w = {}) + { get(id, cb, bindDoneCb(donecb), f, w); } - void get(const std::string& key, GetCallback vcb, DoneCallbackSimple dcb={}, Value::Filter f = {}, Where w = {}); + void get(const std::string& key, GetCallback vcb, DoneCallbackSimple dcb = {}, Value::Filter f = {}, Where w = {}); - template - void get(InfoHash hash, std::function&&)> cb, DoneCallbackSimple dcb={}) + template + void get(InfoHash hash, std::function&&)> cb, DoneCallbackSimple dcb = {}) { - get(hash, [cb=std::move(cb)](const std::vector>& vals) { - return cb(unpackVector(vals)); - }, - dcb, - getFilterSet()); + get( + hash, + [cb = std::move(cb)](const std::vector>& vals) { return cb(unpackVector(vals)); }, + dcb, + getFilterSet()); } - template - void get(InfoHash hash, std::function cb, DoneCallbackSimple dcb={}) + template + void get(InfoHash hash, std::function cb, DoneCallbackSimple dcb = {}) { - get(hash, [cb=std::move(cb)](const std::vector>& vals) { - for (const auto& v : vals) { - try { - if (not cb(Value::unpack(*v))) - return false; - } catch (const std::exception&) { - continue; + get( + hash, + [cb = std::move(cb)](const std::vector>& vals) { + for (const auto& v : vals) { + try { + if (not cb(Value::unpack(*v))) + return false; + } catch (const std::exception&) { + continue; + } } - } - return true; - }, - dcb, - getFilterSet()); + return true; + }, + dcb, + getFilterSet()); } - std::future>> get(InfoHash key, Value::Filter f = {}, Where w = {}) { - auto p = std::make_shared>>>(); - auto values = std::make_shared>>(); - get(key, [=](const std::vector>& vlist) { - values->insert(values->end(), vlist.begin(), vlist.end()); - return true; - }, [=](bool) { - p->set_value(std::move(*values)); - }, - f, w); + std::future>> get(InfoHash key, Value::Filter f = {}, Where w = {}) + { + auto p = std::make_shared>>>(); + auto values = std::make_shared>>(); + get( + key, + [=](const std::vector>& vlist) { + values->insert(values->end(), vlist.begin(), vlist.end()); + return true; + }, + [=](bool) { p->set_value(std::move(*values)); }, + f, + w); return p->get_future(); } - template - std::future> get(InfoHash key) { + template + std::future> get(InfoHash key) + { auto p = std::make_shared>>(); auto values = std::make_shared>(); - get(key, [=](T&& v) { - values->emplace_back(std::move(v)); - return true; - }, [=](bool) { - p->set_value(std::move(*values)); - }); + get( + key, + [=](T&& v) { + values->emplace_back(std::move(v)); + return true; + }, + [=](bool) { p->set_value(std::move(*values)); }); return p->get_future(); } void query(const InfoHash& hash, QueryCallback cb, DoneCallback done_cb = {}, Query q = {}); - void query(const InfoHash& hash, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query q = {}) { + void query(const InfoHash& hash, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query q = {}) + { query(hash, cb, bindDoneCb(done_cb), q); } std::future listen(InfoHash key, ValueCallback vcb, Value::Filter f = {}, Where w = {}); - std::future listen(InfoHash key, GetCallback cb, Value::Filter f={}, Where w={}) { - return listen(key, [cb=std::move(cb)](const std::vector>& vals, bool expired){ - if (not expired) - return cb(vals); - return true; - }, std::forward(f), std::forward(w)); + std::future listen(InfoHash key, GetCallback cb, Value::Filter f = {}, Where w = {}) + { + return listen( + key, + [cb = std::move(cb)](const std::vector>& vals, bool expired) { + if (not expired) + return cb(vals); + return true; + }, + std::forward(f), + std::forward(w)); } std::future listen(const std::string& key, GetCallback vcb, Value::Filter f = {}, Where w = {}); - std::future listen(InfoHash key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) { + std::future listen(InfoHash key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) + { return listen(key, bindGetCb(cb), f, w); } - template + template std::future listen(InfoHash hash, std::function&&)> cb) { - return listen(hash, [cb=std::move(cb)](const std::vector>& vals) { - return cb(unpackVector(vals)); - }, - getFilterSet()); + return listen( + hash, + [cb = std::move(cb)](const std::vector>& vals) { return cb(unpackVector(vals)); }, + getFilterSet()); } - template + template std::future listen(InfoHash hash, std::function&&, bool)> cb) { - return listen(hash, [cb=std::move(cb)](const std::vector>& vals, bool expired) { - return cb(unpackVector(vals), expired); - }, - getFilterSet()); + return listen( + hash, + [cb = std::move(cb)](const std::vector>& vals, bool expired) { + return cb(unpackVector(vals), expired); + }, + getFilterSet()); } - template + template std::future listen(InfoHash hash, std::function cb, Value::Filter f = {}, Where w = {}) { - return listen(hash, [cb=std::move(cb)](const std::vector>& vals) { - for (const auto& v : vals) { - try { - if (not cb(Value::unpack(*v))) - return false; - } catch (const std::exception&) { - continue; + return listen( + hash, + [cb = std::move(cb)](const std::vector>& vals) { + for (const auto& v : vals) { + try { + if (not cb(Value::unpack(*v))) + return false; + } catch (const std::exception&) { + continue; + } } - } - return true; - }, - getFilterSet(f), w); + return true; + }, + getFilterSet(f), + w); } - template + template std::future listen(InfoHash hash, std::function cb, Value::Filter f = {}, Where w = {}) { - return listen(hash, [cb=std::move(cb)](const std::vector>& vals, bool expired) { - for (const auto& v : vals) { - try { - if (not cb(Value::unpack(*v), expired)) - return false; - } catch (const std::exception&) { - continue; + return listen( + hash, + [cb = std::move(cb)](const std::vector>& vals, bool expired) { + for (const auto& v : vals) { + try { + if (not cb(Value::unpack(*v), expired)) + return false; + } catch (const std::exception&) { + continue; + } } - } - return true; - }, - getFilterSet(f), w); + return true; + }, + getFilterSet(f), + w); } void cancelListen(InfoHash h, size_t token); void cancelListen(InfoHash h, std::shared_future token); - void put(InfoHash hash, std::shared_ptr value, DoneCallback cb={}, time_point created=time_point::max(), bool permanent = false); - void put(InfoHash hash, std::shared_ptr value, DoneCallbackSimple cb, time_point created=time_point::max(), bool permanent = false) { + void put(InfoHash hash, + std::shared_ptr value, + DoneCallback cb = {}, + time_point created = time_point::max(), + bool permanent = false); + void put(InfoHash hash, + std::shared_ptr value, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) + { put(hash, value, bindDoneCb(cb), created, permanent); } - void put(InfoHash hash, Value&& value, DoneCallback cb={}, time_point created=time_point::max(), bool permanent = false); - void put(InfoHash hash, Value&& value, DoneCallbackSimple cb, time_point created=time_point::max(), bool permanent = false) { + void put(InfoHash hash, + Value&& value, + DoneCallback cb = {}, + time_point created = time_point::max(), + bool permanent = false); + void put(InfoHash hash, + Value&& value, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) + { put(hash, std::forward(value), bindDoneCb(cb), created, permanent); } - void put(const std::string& key, Value&& value, DoneCallbackSimple cb={}, time_point created=time_point::max(), bool permanent = false); + void put(const std::string& key, + Value&& value, + DoneCallbackSimple cb = {}, + time_point created = time_point::max(), + bool permanent = false); void cancelPut(const InfoHash& h, Value::Id id); void cancelPut(const InfoHash& h, const std::shared_ptr& value); - void putSigned(InfoHash hash, std::shared_ptr value, DoneCallback cb={}, bool permanent = false); - void putSigned(InfoHash hash, std::shared_ptr value, DoneCallbackSimple cb, bool permanent = false) { + void putSigned(InfoHash hash, std::shared_ptr value, DoneCallback cb = {}, bool permanent = false); + void putSigned(InfoHash hash, std::shared_ptr value, DoneCallbackSimple cb, bool permanent = false) + { putSigned(hash, value, bindDoneCb(cb), permanent); } - void putSigned(InfoHash hash, Value&& value, DoneCallback cb={}, bool permanent = false); - void putSigned(InfoHash hash, Value&& value, DoneCallbackSimple cb, bool permanent = false) { + void putSigned(InfoHash hash, Value&& value, DoneCallback cb = {}, bool permanent = false); + void putSigned(InfoHash hash, Value&& value, DoneCallbackSimple cb, bool permanent = false) + { putSigned(hash, std::forward(value), bindDoneCb(cb), permanent); } - void putSigned(const std::string& key, Value&& value, DoneCallbackSimple cb={}, bool permanent = false); + void putSigned(const std::string& key, Value&& value, DoneCallbackSimple cb = {}, bool permanent = false); - void putEncrypted(InfoHash hash, InfoHash to, std::shared_ptr value, DoneCallback cb={}, bool permanent = false); - void putEncrypted(InfoHash hash, InfoHash to, std::shared_ptr value, DoneCallbackSimple cb, bool permanent = false) { + void putEncrypted( + InfoHash hash, InfoHash to, std::shared_ptr value, DoneCallback cb = {}, bool permanent = false); + void putEncrypted( + InfoHash hash, InfoHash to, std::shared_ptr value, DoneCallbackSimple cb, bool permanent = false) + { putEncrypted(hash, to, value, bindDoneCb(cb), permanent); } - void putEncrypted(InfoHash hash, InfoHash to, Value&& value, DoneCallback cb={}, bool permanent = false); - void putEncrypted(InfoHash hash, InfoHash to, Value&& value, DoneCallbackSimple cb, bool permanent = false) { + void putEncrypted(InfoHash hash, InfoHash to, Value&& value, DoneCallback cb = {}, bool permanent = false); + void putEncrypted(InfoHash hash, InfoHash to, Value&& value, DoneCallbackSimple cb, bool permanent = false) + { putEncrypted(hash, to, std::forward(value), bindDoneCb(cb), permanent); } - void putEncrypted(const std::string& key, InfoHash to, Value&& value, DoneCallback cb={}, bool permanent = false); + void putEncrypted(const std::string& key, InfoHash to, Value&& value, DoneCallback cb = {}, bool permanent = false); - void putEncrypted(InfoHash hash, const std::shared_ptr& to, std::shared_ptr value, DoneCallback cb={}, bool permanent = false); - void putEncrypted(InfoHash hash, const std::shared_ptr& to, std::shared_ptr value, DoneCallbackSimple cb, bool permanent = false) { + void putEncrypted(InfoHash hash, + const std::shared_ptr& to, + std::shared_ptr value, + DoneCallback cb = {}, + bool permanent = false); + void putEncrypted(InfoHash hash, + const std::shared_ptr& to, + std::shared_ptr value, + DoneCallbackSimple cb, + bool permanent = false) + { putEncrypted(hash, to, value, bindDoneCb(cb), permanent); } [[deprecated("Use the shared_ptr version instead")]] - void putEncrypted(InfoHash hash, const std::shared_ptr& to, Value&& value, DoneCallback cb={}, bool permanent = false); + void putEncrypted(InfoHash hash, + const std::shared_ptr& to, + Value&& value, + DoneCallback cb = {}, + bool permanent = false); [[deprecated("Use the shared_ptr version instead")]] - void putEncrypted(InfoHash hash, const std::shared_ptr& to, Value&& value, DoneCallbackSimple cb, bool permanent = false) { + void putEncrypted(InfoHash hash, + const std::shared_ptr& to, + Value&& value, + DoneCallbackSimple cb, + bool permanent = false) + { putEncrypted(hash, to, std::forward(value), bindDoneCb(cb), permanent); } - void putEncrypted(InfoHash hash, const PkId& to, std::shared_ptr value, DoneCallback cb={}, bool permanent = false); - void putEncrypted(InfoHash hash, const PkId& to, std::shared_ptr value, DoneCallbackSimple cb, bool permanent = false) { + void putEncrypted( + InfoHash hash, const PkId& to, std::shared_ptr value, DoneCallback cb = {}, bool permanent = false); + void putEncrypted( + InfoHash hash, const PkId& to, std::shared_ptr value, DoneCallbackSimple cb, bool permanent = false) + { putEncrypted(hash, to, value, bindDoneCb(cb), permanent); } @@ -282,8 +343,8 @@ public: * Insert known nodes to the routing table, without necessarly ping them. * Usefull to restart a node and get things running fast without putting load on the network. */ - void bootstrap(std::vector nodes, DoneCallbackSimple cb={}); - void bootstrap(SockAddr addr, DoneCallbackSimple cb={}); + void bootstrap(std::vector nodes, DoneCallbackSimple cb = {}); + void bootstrap(SockAddr addr, DoneCallbackSimple cb = {}); /** * Insert known nodes to the routing table, without necessarly ping them. @@ -353,9 +414,7 @@ public: std::vector exportValues() const; void setLogger(const Sp& logger = {}); - void setLogger(const Logger& logger) { - setLogger(std::make_shared(logger)); - } + void setLogger(const Logger& logger) { setLogger(std::make_shared(logger)); } /** * Only print logs related to the given InfoHash (if given), or disable filter (if zeroes). @@ -367,12 +426,14 @@ public: void importValues(const std::vector& values); - bool isRunning() const { - return running != State::Idle; - } + bool isRunning() const { return running != State::Idle; } NodeStats getNodesStats(sa_family_t af) const; - unsigned getNodesStats(sa_family_t af, unsigned *good_return, unsigned *dubious_return, unsigned *cached_return, unsigned *incoming_return) const; + unsigned getNodesStats(sa_family_t af, + unsigned* good_return, + unsigned* dubious_return, + unsigned* cached_return, + unsigned* incoming_return) const; NodeInfo getNodeInfo() const; void getNodeInfo(std::function)>); @@ -401,7 +462,11 @@ public: * @param threaded: If false, ::loop() must be called periodically. Otherwise a thread is launched. * @param cb: Optional callback to receive general state information. */ - void run(in_port_t port = dht::net::DHT_DEFAULT_PORT, const crypto::Identity& identity = {}, bool threaded = true, NetId network = 0) { + void run(in_port_t port = dht::net::DHT_DEFAULT_PORT, + const crypto::Identity& identity = {}, + bool threaded = true, + NetId network = 0) + { Config config; config.dht_config.node_config.network = network; config.dht_config.id = identity; @@ -411,13 +476,15 @@ public: void run(in_port_t port, Config& config, Context&& context = {}); /** - * Same as @run(sockaddr_in, sockaddr_in6, Identity, bool, StatusCallback), but with string IP addresses and service (port). + * Same as @run(sockaddr_in, sockaddr_in6, Identity, bool, StatusCallback), but with string IP addresses and service + * (port). */ void run(const char* ip4, const char* ip6, const char* service, Config& config, Context&& context = {}); void run(const Config& config, Context&& context); - void setOnStatusChanged(StatusCallback&& cb) { + void setOnStatusChanged(StatusCallback&& cb) + { if (cb) statusCbs.emplace_back(std::move(cb)); } @@ -427,7 +494,8 @@ public: * regularly and everytime a new packet is received. * @return the next op */ - time_point loop() { + time_point loop() + { std::lock_guard lck(dht_mtx); return loop_(); } @@ -463,12 +531,12 @@ public: */ void setPushNotificationToken(const std::string& token); - /** + /** * Sets the push notification topic */ void setPushNotificationTopic(const std::string& topic); - /** + /** * Sets the push notification platform */ void setPushNotificationPlatform(const std::string& platform); @@ -482,17 +550,11 @@ public: void forwardAllMessages(bool forward); private: - enum class State { - Idle, - Running, - Stopping - }; + enum class State { Idle, Running, Stopping }; time_point loop_(); - NodeStatus getStatus() const { - return std::max(status4, status6); - } + NodeStatus getStatus() const { return std::max(status4, status6); } bool checkShutdown(); void opEnded(); @@ -529,8 +591,7 @@ private: std::atomic_size_t ongoing_ops {0}; std::vector shutdownCallbacks_; - NodeStatus status4 {NodeStatus::Disconnected}, - status6 {NodeStatus::Disconnected}; + NodeStatus status4 {NodeStatus::Disconnected}, status6 {NodeStatus::Disconnected}; std::vector statusCbs {}; @@ -544,4 +605,4 @@ private: std::shared_ptr logger_; }; -} +} // namespace dht diff --git a/include/opendht/http.h b/include/opendht/http.h index fbcba9c2..5ce278d5 100644 --- a/include/opendht/http.h +++ b/include/opendht/http.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" diff --git a/include/opendht/indexation/pht.h b/include/opendht/indexation/pht.h index 7289210e..030329a3 100644 --- a/include/opendht/indexation/pht.h +++ b/include/opendht/indexation/pht.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include @@ -43,25 +28,32 @@ namespace indexation { * the node in question is a leaf, *the label is a prefix of all the keys * contained in the leaf*. */ -struct OPENDHT_PUBLIC Prefix { +struct OPENDHT_PUBLIC Prefix +{ Prefix() {} - Prefix(InfoHash h) : size_(h.size() * 8), content_(h.begin(), h.end()) { } - Prefix(const Blob& d, const Blob& f={}) : size_(d.size()*8), flags_(f), content_(d) { } + Prefix(InfoHash h) + : size_(h.size() * 8) + , content_(h.begin(), h.end()) + {} + Prefix(const Blob& d, const Blob& f = {}) + : size_(d.size() * 8) + , flags_(f) + , content_(d) + {} - Prefix(const Prefix& p, size_t first) : - size_(std::min(first, p.content_.size()*8)), - content_(Blob(p.content_.begin(), p.content_.begin()+size_/8)) + Prefix(const Prefix& p, size_t first) + : size_(std::min(first, p.content_.size() * 8)) + , content_(Blob(p.content_.begin(), p.content_.begin() + size_ / 8)) { - auto rem = size_ % 8; - if ( not p.flags_.empty() ) { - flags_ = Blob(p.flags_.begin(), p.flags_.begin()+size_/8); + if (not p.flags_.empty()) { + flags_ = Blob(p.flags_.begin(), p.flags_.begin() + size_ / 8); if (rem) - flags_.push_back(p.flags_[size_/8] & (0xFF << (8 - rem))); + flags_.push_back(p.flags_[size_ / 8] & (0xFF << (8 - rem))); } if (rem) - content_.push_back(p.content_[size_/8] & (0xFF << (8 - rem))); + content_.push_back(p.content_[size_ / 8] & (0xFF << (8 - rem))); } /** @@ -76,8 +68,9 @@ struct OPENDHT_PUBLIC Prefix { * * @throw out_of_range if len is larger than size of the content */ - Prefix getPrefix(ssize_t len) const { - if ((size_t)std::abs(len) >= content_.size() * 8) + Prefix getPrefix(ssize_t len) const + { + if ((size_t) std::abs(len) >= content_.size() * 8) throw std::out_of_range("len larger than prefix size."); if (len < 0) len += size_; @@ -91,33 +84,31 @@ struct OPENDHT_PUBLIC Prefix { ee * * @see isActiveBit in private function */ - bool isFlagActive(size_t pos) const { - return flags_.empty() or isActiveBit(flags_, pos); - } + bool isFlagActive(size_t pos) const { return flags_.empty() or isActiveBit(flags_, pos); } /** * @see isActiveBit in private function */ - bool isContentBitActive(size_t pos) const { - return isActiveBit(content_, pos); - } + bool isContentBitActive(size_t pos) const { return isActiveBit(content_, pos); } - Prefix getFullSize() { return Prefix(*this, content_.size()*8); } + Prefix getFullSize() { return Prefix(*this, content_.size() * 8); } /** * This methods gets the prefix of its sibling in the PHT structure. * * @return The prefix of this sibling. */ - Prefix getSibling() const { + Prefix getSibling() const + { Prefix copy = *this; - if ( size_ ) + if (size_) copy.swapContentBit(size_ - 1); return copy; } - InfoHash hash() const { + InfoHash hash() const + { Blob copy(content_); copy.push_back(size_); return InfoHash::get(copy); @@ -130,22 +121,20 @@ ee * * @param p2 second prefix to compared * @return Lenght of the larger common prefix between both */ - static inline unsigned commonBits(const Prefix& p1, const Prefix& p2) { + static inline unsigned commonBits(const Prefix& p1, const Prefix& p2) + { unsigned i, j; uint8_t x; auto longest_prefix_size = std::min(p1.size_, p2.size_); for (i = 0; i < longest_prefix_size; i++) { - if (p1.content_.data()[i] != p2.content_.data()[i] - or not p1.isFlagActive(i) - or not p2.isFlagActive(i) ) { - - break; + if (p1.content_.data()[i] != p2.content_.data()[i] or not p1.isFlagActive(i) or not p2.isFlagActive(i)) { + break; } } if (i == longest_prefix_size) - return 8*longest_prefix_size; + return 8 * longest_prefix_size; x = p1.content_.data()[i] ^ p2.content_.data()[i]; @@ -161,38 +150,33 @@ ee * /** * @see doc of swap private function */ - void swapContentBit(size_t bit) { - swapBit(content_, bit); - } + void swapContentBit(size_t bit) { swapBit(content_, bit); } /** * @see doc of swap private function */ - void swapFlagBit(size_t bit) { - swapBit(flags_, bit); - } + void swapFlagBit(size_t bit) { swapBit(flags_, bit); } /** * @see doc of addPadding private function */ - void addPaddingContent(size_t size) { - content_ = addPadding(content_, size); - } + void addPaddingContent(size_t size) { content_ = addPadding(content_, size); } - void updateFlags() { + void updateFlags() + { /* Fill first known bit */ auto csize = size_ - flags_.size() * 8; - while(csize >= 8) { + while (csize >= 8) { flags_.push_back(0xFF); csize -= 8; } /* if needed fill remaining bit */ - if ( csize ) + if (csize) flags_.push_back(0xFF << (8 - csize)); /* Complet vector space missing */ - for ( auto i = flags_.size(); i < content_.size(); i++ ) + for (auto i = flags_.size(); i < content_.size(); i++) flags_.push_back(0xFF); } @@ -207,7 +191,6 @@ ee * Blob content_ {}; private: - /** * Add a padding to the input blob * @@ -216,9 +199,10 @@ private: * * @return Copy of the input Blob but with a padding */ - Blob addPadding(Blob toP, size_t size) { + Blob addPadding(Blob toP, size_t size) + { Blob copy = toP; - for ( auto i = copy.size(); i < size; i++ ) + for (auto i = copy.size(); i < size; i++) copy.push_back(0); swapBit(copy, size_ + 1); @@ -235,11 +219,12 @@ private: * * @throw out_of_range if bit is superior to blob size * 8 */ - bool isActiveBit(const Blob &b, size_t pos) const { - if ( pos >= content_.size() * 8 ) + bool isActiveBit(const Blob& b, size_t pos) const + { + if (pos >= content_.size() * 8) throw std::out_of_range("Can't detect active bit at pos, pos larger than prefix size or empty prefix"); - return ((b[pos / 8] >> (7 - (pos % 8)) ) & 1) == 1; + return ((b[pos / 8] >> (7 - (pos % 8))) & 1) == 1; } /** @@ -252,8 +237,9 @@ private: * * @throw out_of_range if bit is superior to blob size * 8 */ - void swapBit(Blob &b, size_t bit) { - if ( bit >= b.size() * 8 ) + void swapBit(Blob& b, size_t bit) + { + if (bit >= b.size() * 8) throw std::out_of_range("bit larger than prefix size."); size_t offset_bit = (8 - bit) % 8; @@ -262,15 +248,18 @@ private: }; using Value = std::pair; -struct OPENDHT_PUBLIC IndexEntry : public dht::Value::Serializable { +struct OPENDHT_PUBLIC IndexEntry : public dht::Value::Serializable +{ static const ValueType& TYPE; - virtual void unpackValue(const dht::Value& v) { + virtual void unpackValue(const dht::Value& v) + { Serializable::unpackValue(v); name = v.user_type; } - virtual dht::Value packValue() const { + virtual dht::Value packValue() const + { auto pack = Serializable::packValue(); pack.user_type = name; return pack; @@ -282,14 +271,14 @@ struct OPENDHT_PUBLIC IndexEntry : public dht::Value::Serializable { MSGPACK_DEFINE_MAP(prefix, value) }; -class OPENDHT_PUBLIC Pht { +class OPENDHT_PUBLIC Pht +{ static constexpr const char* INVALID_KEY = "Key does not match the PHT key spec."; /* Prefixes the user_type for all dht values put on the DHT */ static constexpr const char* INDEX_PREFIX = "index.pht."; public: - /* This is the maximum number of entries per node. This parameter is * critical and influences the traffic a lot during a lookup operation. */ @@ -303,28 +292,34 @@ public: using KeySpec = std::map; using LookupCallback = std::function>& values, const Prefix& p)>; - typedef void (*LookupCallbackRaw)(std::vector>* values, Prefix* p, void *user_data); - static LookupCallback - bindLookupCb(LookupCallbackRaw raw_cb, void* user_data) { - if (not raw_cb) return {}; + typedef void (*LookupCallbackRaw)(std::vector>* values, Prefix* p, void* user_data); + static LookupCallback bindLookupCb(LookupCallbackRaw raw_cb, void* user_data) + { + if (not raw_cb) + return {}; return [=](std::vector>& values, const Prefix& p) { raw_cb((std::vector>*) &values, (Prefix*) &p, user_data); }; } using LookupCallbackSimple = std::function>& values)>; - typedef void (*LookupCallbackSimpleRaw)(std::vector>* values, void *user_data); - static LookupCallbackSimple - bindLookupCbSimple(LookupCallbackSimpleRaw raw_cb, void* user_data) { - if (not raw_cb) return {}; + typedef void (*LookupCallbackSimpleRaw)(std::vector>* values, void* user_data); + static LookupCallbackSimple bindLookupCbSimple(LookupCallbackSimpleRaw raw_cb, void* user_data) + { + if (not raw_cb) + return {}; return [=](std::vector>& values) { raw_cb((std::vector>*) &values, user_data); }; } Pht(std::string name, KeySpec k_spec, std::shared_ptr dht) - : name_(INDEX_PREFIX + name), canary_(name_ + ".canary"), keySpec_(k_spec), dht_(dht) {} + : name_(INDEX_PREFIX + name) + , canary_(name_ + ".canary") + , keySpec_(k_spec) + , dht_(dht) + {} - virtual ~Pht () { } + virtual ~Pht() {} /** * Lookup a key for a value. @@ -332,7 +327,11 @@ public: void lookup(Key k, LookupCallback cb = {}, DoneCallbackSimple done_cb = {}, bool exact_match = true); void lookup(Key k, LookupCallbackSimple cb = {}, DoneCallbackSimple done_cb = {}, bool exact_match = true) { - lookup(k, [cb=std::move(cb)](std::vector>& values, Prefix) { cb(values); }, done_cb, exact_match); + lookup( + k, + [cb = std::move(cb)](std::vector>& values, Prefix) { cb(values); }, + done_cb, + exact_match); } /** @@ -342,7 +341,8 @@ public: * @param v : Value to insert * @param done_cb : Callbakc which going to be call when all the insert is done */ - void insert(Key k, Value v, DoneCallbackSimple done_cb = {}) { + void insert(Key k, Value v, DoneCallbackSimple done_cb = {}) + { Prefix p = linearize(k); auto lo = std::make_shared(0); @@ -357,7 +357,6 @@ public: } private: - /** * Insert function which really insert onto the pht * @@ -370,10 +369,16 @@ private: * @param done_cb : Callback to call when the insert is done */ - void insert(const Prefix& kp, IndexEntry entry, std::shared_ptr lo, std::shared_ptr hi, time_point time_p, - bool check_split, DoneCallbackSimple done_cb = {}); + void insert(const Prefix& kp, + IndexEntry entry, + std::shared_ptr lo, + std::shared_ptr hi, + time_point time_p, + bool check_split, + DoneCallbackSimple done_cb = {}); - class Cache { + class Cache + { public: /** * Insert all needed node into the tree according to a prefix @@ -395,14 +400,15 @@ private: static constexpr const size_t MAX_ELEMENT {1024}; static constexpr const std::chrono::minutes NODE_EXPIRE_TIME {5}; - struct Node { + struct Node + { time_point last_reply; /* Made the assocation between leaves and leaves multimap */ std::shared_ptr parent; /* Share_ptr to the parent, it allow the self destruction of tree */ std::weak_ptr left_child; /* Left child, for bit equal to 1 */ std::weak_ptr right_child; /* Right child, for bit equal to 0 */ }; - std::weak_ptr root_; /* Root of the tree */ + std::weak_ptr root_; /* Root of the tree */ /** * This mutlimap contains all prefix insert in the tree in time order @@ -427,14 +433,19 @@ private: * @param cb : Callback to use at the end of the lookupStep (call on the value of vals) * @param done_cb : Callback at the end of the lookupStep * @param max_common_prefix_len: used in the inexacte lookup match case, indicate the longest common prefix found - * @param start : If start is set then lo and hi will be ignore for the first step, if the step fail lo and hi will be used + * @param start : If start is set then lo and hi will be ignore for the first step, if the step fail lo and hi + * will be used * @param all_values : If all value is true then all value met during the lookupstep will be in the vector vals */ - void lookupStep(Prefix k, std::shared_ptr lo, std::shared_ptr hi, - std::shared_ptr>> vals, - LookupCallbackWrapper cb, DoneCallbackSimple done_cb, - std::shared_ptr max_common_prefix_len, - int start = -1, bool all_values = false); + void lookupStep(Prefix k, + std::shared_ptr lo, + std::shared_ptr hi, + std::shared_ptr>> vals, + LookupCallbackWrapper cb, + DoneCallbackSimple done_cb, + std::shared_ptr max_common_prefix_len, + int start = -1, + bool all_values = false); /** * Apply the zcurve algorithm on the list of input prefix @@ -463,7 +474,7 @@ private: * @param entry The entry to put at the prefix p * @param end_cb Callback to use at the end of counting */ - void getRealPrefix(const std::shared_ptr& p, IndexEntry entry, RealInsertCallback end_cb ); + void getRealPrefix(const std::shared_ptr& p, IndexEntry entry, RealInsertCallback end_cb); /** * Looking where to put the data cause if there is free space on the node @@ -482,10 +493,11 @@ private: * @param vals : The vector of values to compare with comapred * @return position compared diverge from all others */ - static size_t findSplitLocation(const Prefix& compared, const std::vector>& vals) { - for ( size_t i = 0; i < compared.content_.size() * 8 - 1; i++ ) - for ( auto const& v : vals) - if ( Prefix(v->prefix).isContentBitActive(i) != compared.isContentBitActive(i) ) + static size_t findSplitLocation(const Prefix& compared, const std::vector>& vals) + { + for (size_t i = 0; i < compared.content_.size() * 8 - 1; i++) + for (auto const& v : vals) + if (Prefix(v->prefix).isContentBitActive(i) != compared.isContentBitActive(i)) return i + 1; return compared.content_.size() * 8 - 1; } @@ -498,18 +510,23 @@ private: * @param entry : Entry to put on the pht * @param end_cb : Callback to apply to the insert prefi (here does the insert) */ - void split(const Prefix& insert, const std::vector>& vals, IndexEntry entry, RealInsertCallback end_cb); + void split(const Prefix& insert, + const std::vector>& vals, + IndexEntry entry, + RealInsertCallback end_cb); /** * Tells if the key is valid according to the key spec. */ - bool validKey(const Key& k) const { - return k.size() == keySpec_.size() and - std::equal(k.begin(), k.end(), keySpec_.begin(), - [&](const Key::value_type& key, const KeySpec::value_type& key_spec) { - return key.first == key_spec.first and key.second.size() <= key_spec.second; - } - ); + bool validKey(const Key& k) const + { + return k.size() == keySpec_.size() + and std::equal(k.begin(), + k.end(), + keySpec_.begin(), + [&](const Key::value_type& key, const KeySpec::value_type& key_spec) { + return key.first == key_spec.first and key.second.size() <= key_spec.second; + }); } /** @@ -525,6 +542,5 @@ private: std::shared_ptr dht_; }; -} /* indexation */ -} /* dht */ - +} // namespace indexation +} // namespace dht diff --git a/include/opendht/infohash.h b/include/opendht/infohash.h index 393cc285..5c36939e 100644 --- a/include/opendht/infohash.h +++ b/include/opendht/infohash.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" @@ -53,7 +38,7 @@ namespace dht { using byte = uint8_t; namespace crypto { - OPENDHT_PUBLIC void hash(const uint8_t* data, size_t data_length, uint8_t* hash, size_t hash_length); +OPENDHT_PUBLIC void hash(const uint8_t* data, size_t data_length, uint8_t* hash, size_t hash_length); } /** @@ -61,17 +46,17 @@ namespace crypto { * a byte array of N bytes. * Hashes identify nodes and values in the Dht. */ -template -class Hash { +template +class Hash +{ public: using T = std::array; typedef typename T::iterator iterator; typedef typename T::const_iterator const_iterator; - Hash() noexcept { - data_.fill(0); - } - Hash(const uint8_t* h, size_t data_len) { + Hash() noexcept { data_.fill(0); } + Hash(const uint8_t* h, size_t data_len) + { if (data_len < N) data_.fill(0); else @@ -82,16 +67,15 @@ public: * hex must be at least 2.HASH_LEN characters long. * If too long, only the first 2.HASH_LEN characters are read. */ - explicit Hash(std::string_view hex) { - if (hex.size() < 2*N) + explicit Hash(std::string_view hex) + { + if (hex.size() < 2 * N) data_.fill(0); else fromString(hex.data()); } - Hash(const msgpack::object& o) { - msgpack_unpack(o); - } + Hash(const msgpack::object& o) { msgpack_unpack(o); } static constexpr size_t size() noexcept { return N; } const uint8_t* data() const { return data_.data(); } @@ -101,22 +85,22 @@ public: iterator end() { return data_.end(); } const_iterator cend() const { return data_.cend(); } - static constexpr inline Hash zero() noexcept { return Hash{}; } + static constexpr inline Hash zero() noexcept { return Hash {}; } - bool operator==(const Hash& h) const { - return data_ == h.data_; - } + bool operator==(const Hash& h) const { return data_ == h.data_; } bool operator!=(const Hash& h) const { return !(*this == h); } - bool operator<(const Hash& o) const { + bool operator<(const Hash& o) const + { for (unsigned i = 0; i < N; i++) { - if(data_[i] != o.data_[i]) + if (data_[i] != o.data_[i]) return data_[i] < o.data_[i]; } return false; } - Hash operator^(const Hash& o) const { + Hash operator^(const Hash& o) const + { Hash result; for (auto i = 0u; i < N; i++) { result[i] = data_[i] ^ o.data_[i]; @@ -124,7 +108,8 @@ public: return result; } - explicit operator bool() const { + explicit operator bool() const + { auto a = reinterpret_cast(data_.data()); auto b = reinterpret_cast(data_.data() + N); for (; a != b; a++) { @@ -141,41 +126,42 @@ public: * Find the lowest 1 bit in an id. * Result will allways be lower than 8*N */ - inline int lowbit() const { + inline int lowbit() const + { int i, j; - for(i = N-1; i >= 0; i--) - if(data_[i] != 0) + for (i = N - 1; i >= 0; i--) + if (data_[i] != 0) break; - if(i < 0) + if (i < 0) return -1; - for(j = 7; j >= 0; j--) - if((data_[i] & (0x80 >> j)) != 0) + for (j = 7; j >= 0; j--) + if ((data_[i] & (0x80 >> j)) != 0) break; return 8 * i + j; } - static inline int cmp(const Hash& id1, const Hash& id2) { + static inline int cmp(const Hash& id1, const Hash& id2) + { return std::memcmp(id1.data_.data(), id2.data_.data(), N); } /** Find how many bits two ids have in common. */ - static inline unsigned - commonBits(const Hash& id1, const Hash& id2) + static inline unsigned commonBits(const Hash& id1, const Hash& id2) { unsigned i, j; uint8_t x; - for(i = 0; i < N; i++) { - if(id1.data_[i] != id2.data_[i]) + for (i = 0; i < N; i++) { + if (id1.data_[i] != id2.data_[i]) break; } - if(i == N) - return 8*N; + if (i == N) + return 8 * N; x = id1.data_[i] ^ id2.data_[i]; j = 0; - while((x & 0x80) == 0) { + while ((x & 0x80) == 0) { x <<= 1; j++; } @@ -184,11 +170,10 @@ public: } /** Determine whether id1 or id2 is closer to this */ - int - xorCmp(const Hash& id1, const Hash& id2) const + int xorCmp(const Hash& id1, const Hash& id2) const { for (unsigned i = 0; i < N; i++) { - if(id1.data_[i] == id2.data_[i]) + if (id1.data_[i] == id2.data_[i]) continue; uint8_t xor1 = id1.data_[i] ^ data_[i]; uint8_t xor2 = id2.data_[i] ^ data_[i]; @@ -197,40 +182,36 @@ public: return 0; } - bool - getBit(unsigned nbit) const + bool getBit(unsigned nbit) const { - auto& num = *(data_.cbegin()+(nbit/8)); + auto& num = *(data_.cbegin() + (nbit / 8)); unsigned bit = 7 - (nbit % 8); return (num >> bit) & 1; } - void - setBit(unsigned nbit, bool b) + void setBit(unsigned nbit, bool b) { - auto& num = data_[nbit/8]; + auto& num = data_[nbit / 8]; unsigned bit = 7 - (nbit % 8); num ^= (-b ^ num) & (1 << bit); } - double toFloat() const { + double toFloat() const + { using D = size_t; double v = 0.; - for (size_t i = 0; i < std::min(N, sizeof(D)-1); i++) - v += *(data_.cbegin()+i) / (double)((D)1 << 8*(i+1)); + for (size_t i = 0; i < std::min(N, sizeof(D) - 1); i++) + v += *(data_.cbegin() + i) / (double) ((D) 1 << 8 * (i + 1)); return v; } - static inline Hash get(std::string_view data) { - return get((const uint8_t*)data.data(), data.size()); - } + static inline Hash get(std::string_view data) { return get((const uint8_t*) data.data(), data.size()); } - static inline Hash get(const std::vector& data) { - return get(data.data(), data.size()); - } + static inline Hash get(const std::vector& data) { return get(data.data(), data.size()); } - template - static Hash get(const Hash& o) { + template + static Hash get(const Hash& o) + { return get(o.data(), o.size()); } @@ -246,33 +227,35 @@ public: static Hash getRandom(); - template + template static Hash getRandom(Rd&); - template - friend std::ostream& operator<< (std::ostream& s, const Hash& h); + template + friend std::ostream& operator<<(std::ostream& s, const Hash& h); - template - friend std::istream& operator>> (std::istream& s, Hash& h); + template + friend std::istream& operator>>(std::istream& s, Hash& h); /** Returns view to thread-allocated memory, only valid until the next call to this function. */ - std::string_view to_view() const { return std::string_view(to_c_str(), N*2); } + std::string_view to_view() const { return std::string_view(to_c_str(), N * 2); } const char* to_c_str() const; std::string toString() const; - template + template void msgpack_pack(Packer& pk) const { pk.pack_bin(N); - pk.pack_bin_body((char*)data_.data(), N); + pk.pack_bin_body((char*) data_.data(), N); } - void msgpack_unpack(msgpack::object o) { + void msgpack_unpack(msgpack::object o) + { if (o.type != msgpack::type::BIN or o.via.bin.size != N) throw msgpack::type_error(); std::copy_n(o.via.bin.ptr, N, data_.data()); } + private: T data_; void fromString(const char*); @@ -283,41 +266,48 @@ using InfoHash = Hash; using h256 = Hash<32>; using PkId = h256; -template -std::ostream& operator<< (std::ostream& s, const Hash& h) +template +std::ostream& +operator<<(std::ostream& s, const Hash& h) { - s.write(h.to_c_str(), N*2); + s.write(h.to_c_str(), N * 2); return s; } -template -std::istream& operator>> (std::istream& s, Hash& h) +template +std::istream& +operator>>(std::istream& s, Hash& h) { - std::array dat; + std::array dat; s.exceptions(std::istream::eofbit | std::istream::failbit); s.read(&(*dat.begin()), dat.size()); fromString(dat.data()); return s; } -template +template void -Hash::fromString(const char* in) { +Hash::fromString(const char* in) +{ auto hex2bin = [](char c) -> uint8_t { - if (c >= 'a' and c <= 'f') return 10 + c - 'a'; - else if (c >= 'A' and c <= 'F') return 10 + c - 'A'; - else if (c >= '0' and c <= '9') return c - '0'; - else throw std::domain_error("not an hex character"); + if (c >= 'a' and c <= 'f') + return 10 + c - 'a'; + else if (c >= 'A' and c <= 'F') + return 10 + c - 'A'; + else if (c >= '0' and c <= '9') + return c - '0'; + else + throw std::domain_error("not an hex character"); }; try { - for (size_t i=0; i +template Hash Hash::getRandom() { @@ -330,8 +320,8 @@ Hash::getRandom() return h; } -template -template +template +template Hash Hash::getRandom(Rd& rdev) { @@ -343,14 +333,18 @@ Hash::getRandom(Rd& rdev) return h; } -struct alignas(std::max_align_t) HexMap : public std::array, 256> { - constexpr HexMap(): std::array, 256>() { +struct alignas(std::max_align_t) HexMap : public std::array, 256> +{ + constexpr HexMap() + : std::array, 256>() + { for (size_t i = 0; i < size(); i++) { auto& e = (*this)[i]; e[0] = hex_digits[(i >> 4) & 0x0F]; e[1] = hex_digits[i & 0x0F]; } } + private: static constexpr const char* hex_digits = "0123456789abcdef"; }; @@ -358,47 +352,51 @@ private: inline constexpr HexMap hex_map {}; inline std::string -toHex(const uint8_t* data, size_t size) { +toHex(const uint8_t* data, size_t size) +{ std::string ret(size * 2, '\0'); - for (size_t i=0; i& data) { +toHex(const std::vector& data) +{ return toHex(data.data(), data.size()); } -template +template const char* Hash::to_c_str() const { - alignas(std::max_align_t) thread_local std::array buf; - for (size_t i=0; i buf; + for (size_t i = 0; i < N; i++) { + auto b = buf.data() + i * 2; const auto& m = hex_map[data_[i]]; - *((uint16_t*)b) = *((uint16_t*)&m); + *((uint16_t*) b) = *((uint16_t*) &m); } - buf[N*2] = '\0'; + buf[N * 2] = '\0'; return buf.data(); } -template +template std::string Hash::toString() const { - return std::string(to_c_str(), N*2); + return std::string(to_c_str(), N * 2); } -} +} // namespace dht -template -struct fmt::formatter>: formatter { - constexpr auto format(const dht::Hash& c, format_context& ctx) const { - return formatter::format(c.to_view(), ctx); - } +template +struct fmt::formatter> : formatter +{ + constexpr auto format(const dht::Hash& c, format_context& ctx) const + { + return formatter::format(c.to_view(), ctx); + } }; diff --git a/include/opendht/log.h b/include/opendht/log.h index eb5462b5..10d642c3 100644 --- a/include/opendht/log.h +++ b/include/opendht/log.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" @@ -36,22 +21,18 @@ OPENDHT_PUBLIC std::shared_ptr getStdLogger(); OPENDHT_PUBLIC -std::shared_ptr getFileLogger(const std::string &path); +std::shared_ptr getFileLogger(const std::string& path); OPENDHT_PUBLIC std::shared_ptr getSyslogLogger(const char* name); -OPENDHT_PUBLIC void -enableLogging(dht::DhtRunner &dht); +OPENDHT_PUBLIC void enableLogging(dht::DhtRunner& dht); -OPENDHT_PUBLIC void -enableFileLogging(dht::DhtRunner &dht, const std::string &path); +OPENDHT_PUBLIC void enableFileLogging(dht::DhtRunner& dht, const std::string& path); -OPENDHT_PUBLIC void -disableLogging(dht::DhtRunner &dht); +OPENDHT_PUBLIC void disableLogging(dht::DhtRunner& dht); -OPENDHT_PUBLIC void -enableSyslog(dht::DhtRunner &dht, const char* name); +OPENDHT_PUBLIC void enableSyslog(dht::DhtRunner& dht, const char* name); -} /* log */ -} /* dht */ +} // namespace log +} // namespace dht diff --git a/include/opendht/logger.h b/include/opendht/logger.h index cfbe6b6f..b568fdc9 100644 --- a/include/opendht/logger.h +++ b/include/opendht/logger.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "infohash.h" diff --git a/include/opendht/network_engine.h b/include/opendht/network_engine.h index 7530da6f..35fab7fe 100644 --- a/include/opendht/network_engine.h +++ b/include/opendht/network_engine.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "node_cache.h" @@ -46,23 +31,25 @@ struct TransId; #define MSG_CONFIRM 0 #endif -struct NetworkConfig { +struct NetworkConfig +{ NetId network {0}; ssize_t max_req_per_sec {0}; ssize_t max_peer_req_per_sec {0}; bool is_client {false}; }; -class DhtProtocolException : public DhtException { +class DhtProtocolException : public DhtException +{ public: // sent to another peer (http-like). static const constexpr uint16_t NON_AUTHORITATIVE_INFORMATION {203}; /* incomplete request packet. */ static const constexpr uint16_t UNAUTHORIZED {401}; /* incorrect tokens. */ static const constexpr uint16_t NOT_FOUND {404}; /* storage not found */ // for internal use (custom). - static const constexpr uint16_t INVALID_TID_SIZE {421}; /* id was truncated. */ - static const constexpr uint16_t UNKNOWN_TID {422}; /* unknown tid */ - static const constexpr uint16_t WRONG_NODE_INFO_BUF_LEN {423}; /* node info length is incorrect */ + static const constexpr uint16_t INVALID_TID_SIZE {421}; /* id was truncated. */ + static const constexpr uint16_t UNKNOWN_TID {422}; /* unknown tid */ + static const constexpr uint16_t WRONG_NODE_INFO_BUF_LEN {423}; /* node info length is incorrect */ static const std::string GET_NO_INFOHASH; /* received "get" request with no infohash */ static const std::string LISTEN_NO_INFOHASH; /* got "listen" request without infohash */ @@ -72,8 +59,12 @@ public: static const std::string STORAGE_NOT_FOUND; /* got access request for an unknown storage */ static const std::string PUT_INVALID_ID; /* invalid id in "put" request */ - DhtProtocolException(uint16_t code, const std::string& msg="", InfoHash failing_node_id={}) - : DhtException(msg), msg(msg), code(code), failing_node_id(failing_node_id) {} + DhtProtocolException(uint16_t code, const std::string& msg = "", InfoHash failing_node_id = {}) + : DhtException(msg) + , msg(msg) + , code(code) + , failing_node_id(failing_node_id) + {} const std::string& getMsg() const { return msg; } uint16_t getCode() const { return code; } @@ -90,7 +81,8 @@ struct ParsedMessage; /** * Answer for a request. */ -struct RequestAnswer { +struct RequestAnswer +{ Blob ntoken {}; Value::Id vid {}; std::vector> values {}; @@ -175,12 +167,7 @@ private: * @param token (type: Blob) security token. * @param rid (type: uint16_t) request id. */ - std::function, - const InfoHash&, - const Blob&, - Tid, - const Query&, - int)> onListen {}; + std::function, const InfoHash&, const Blob&, Tid, const Query&, int)> onListen {}; /** * Called on announce request. * @@ -190,11 +177,8 @@ private: * @param values (type: std::vector>) values to store. * @param created (type: time_point) time when the value was created. */ - std::function, - const InfoHash&, - const Blob&, - const std::vector>&, - const time_point&)> onAnnounce {}; + std::function, const InfoHash&, const Blob&, const std::vector>&, const time_point&)> + onAnnounce {}; /** * Called on refresh request. * @@ -203,32 +187,28 @@ private: * @param token (type: Blob) security token. * @param vid (type: Value::id) the value id. */ - std::function, - const InfoHash&, - const Blob&, - const Value::Id&)> onRefresh {}; + std::function, const InfoHash&, const Blob&, const Value::Id&)> onRefresh {}; public: using RequestCb = std::function; using RequestErrorCb = std::function; using RequestExpiredCb = std::function; - NetworkEngine( - InfoHash& myid, - NetworkConfig config, - std::unique_ptr&& sock, - const Sp& log, - std::mt19937_64& rd, - Scheduler& scheduler, - decltype(NetworkEngine::onError)&& onError, - decltype(NetworkEngine::onNewNode)&& onNewNode, - decltype(NetworkEngine::onReportedAddr)&& onReportedAddr, - decltype(NetworkEngine::onPing)&& onPing, - decltype(NetworkEngine::onFindNode)&& onFindNode, - decltype(NetworkEngine::onGetValues)&& onGetValues, - decltype(NetworkEngine::onListen)&& onListen, - decltype(NetworkEngine::onAnnounce)&& onAnnounce, - decltype(NetworkEngine::onRefresh)&& onRefresh); + NetworkEngine(InfoHash& myid, + NetworkConfig config, + std::unique_ptr&& sock, + const Sp& log, + std::mt19937_64& rd, + Scheduler& scheduler, + decltype(NetworkEngine::onError)&& onError, + decltype(NetworkEngine::onNewNode)&& onNewNode, + decltype(NetworkEngine::onReportedAddr)&& onReportedAddr, + decltype(NetworkEngine::onPing)&& onPing, + decltype(NetworkEngine::onFindNode)&& onFindNode, + decltype(NetworkEngine::onGetValues)&& onGetValues, + decltype(NetworkEngine::onListen)&& onListen, + decltype(NetworkEngine::onAnnounce)&& onAnnounce, + decltype(NetworkEngine::onRefresh)&& onRefresh); ~NetworkEngine(); @@ -251,15 +231,32 @@ public: * @param values The values to send. * @param version If version = 1, a request will be used to answer to the listener */ - void tellListener(const Sp& n, Tid socket_id, const InfoHash& hash, want_t want, const Blob& ntoken, - std::vector>&& nodes, std::vector>&& nodes6, - std::vector>&& values, const Query& q, int version); + void tellListener(const Sp& n, + Tid socket_id, + const InfoHash& hash, + want_t want, + const Blob& ntoken, + std::vector>&& nodes, + std::vector>&& nodes6, + std::vector>&& values, + const Query& q, + int version); - void tellListenerRefreshed(const Sp& n, Tid socket_id, const InfoHash& hash, const Blob& ntoken, const std::vector& values, int version); - void tellListenerExpired(const Sp& n, Tid socket_id, const InfoHash& hash, const Blob& ntoken, const std::vector& values, int version); + void tellListenerRefreshed(const Sp& n, + Tid socket_id, + const InfoHash& hash, + const Blob& ntoken, + const std::vector& values, + int version); + void tellListenerExpired(const Sp& n, + Tid socket_id, + const InfoHash& hash, + const Blob& ntoken, + const std::vector& values, + int version); bool isRunning(sa_family_t af) const; - inline want_t want () const { return dht_socket->hasIPv4() and dht_socket->hasIPv6() ? (WANT4 | WANT6) : -1; } + inline want_t want() const { return dht_socket->hasIPv4() and dht_socket->hasIPv6() ? (WANT4 | WANT6) : -1; } void connectivityChanged(sa_family_t); @@ -276,8 +273,7 @@ public: * * @return the request with information concerning its success. */ - Sp - sendPing(const Sp& n, RequestCb&& on_done, RequestExpiredCb&& on_expired); + Sp sendPing(const Sp& n, RequestCb&& on_done, RequestExpiredCb&& on_expired); /** * Send a "ping" request to a given node. @@ -289,11 +285,11 @@ public: * * @return the request with information concerning its success. */ - Sp - sendPing(SockAddr&& sa, RequestCb&& on_done, RequestExpiredCb&& on_expired) { + Sp sendPing(SockAddr&& sa, RequestCb&& on_done, RequestExpiredCb&& on_expired) + { return sendPing(std::make_shared(InfoHash::zero(), std::move(sa), rd), - std::forward(on_done), - std::forward(on_expired)); + std::forward(on_done), + std::forward(on_expired)); } /** @@ -416,11 +412,11 @@ public: * @return the request with information concerning its success. */ void sendUpdateValues(const Sp& n, - const InfoHash& infohash, - std::vector>&& values, - time_point created, - const Blob& token, - size_t sid); + const InfoHash& infohash, + std::vector>&& values, + time_point created, + const Blob& token, + size_t sid); Sp sendUpdateValues(const Sp& n, const InfoHash& infohash, std::vector>::iterator begin, @@ -438,44 +434,38 @@ public: * @param fromlen The length of the corresponding sockaddr structure. * @param now The time to adjust the clock in the network engine. */ - void processMessage(const uint8_t *buf, size_t buflen, SockAddr addr); + void processMessage(const uint8_t* buf, size_t buflen, SockAddr addr); - Sp insertNode(const InfoHash& id, const SockAddr& addr) { + Sp insertNode(const InfoHash& id, const SockAddr& addr) + { auto n = cache.getNode(id, addr, scheduler.time(), 0); onNewNode(n, 0); return n; } - std::vector getNodeMessageStats(bool in) { + std::vector getNodeMessageStats(bool in) + { auto& st = in ? in_stats : out_stats; - std::vector stats {st.ping, st.find, st.get, st.listen, st.put}; + std::vector stats {st.ping, st.find, st.get, st.listen, st.put}; st = {}; return stats; } void blacklistNode(const Sp& n); - std::vector> getCachedNodes(const InfoHash& id, sa_family_t sa_f, size_t count) { + std::vector> getCachedNodes(const InfoHash& id, sa_family_t sa_f, size_t count) + { return cache.getCachedNodes(id, sa_f, count); } - size_t getNodeCacheSize() const { - return cache.size(); - } - size_t getNodeCacheSize(sa_family_t af) const { - return cache.size(af); - } + size_t getNodeCacheSize() const { return cache.size(); } + size_t getNodeCacheSize(sa_family_t af) const { return cache.size(af); } - size_t getRateLimiterSize() const { - return address_rate_limiter.size(); - } + size_t getRateLimiterSize() const { return address_rate_limiter.size(); } - size_t getPartialCount() const { - return partial_messages.size(); - } + size_t getPartialCount() const { return partial_messages.size(); } private: - struct PartialMessage; /*************** @@ -515,23 +505,26 @@ private: */ void sendRequest(const Sp& request); - struct MessageStats { - unsigned ping {0}; - unsigned find {0}; - unsigned get {0}; - unsigned put {0}; - unsigned listen {0}; - unsigned refresh {0}; - unsigned updateValue {0}; + struct MessageStats + { + unsigned ping {0}; + unsigned find {0}; + unsigned get {0}; + unsigned put {0}; + unsigned listen {0}; + unsigned refresh {0}; + unsigned updateValue {0}; }; - // basic wrapper for socket sendto function - int send(const SockAddr& addr, const char *buf, size_t len, bool confirmed = false); + int send(const SockAddr& addr, const char* buf, size_t len, bool confirmed = false); void sendValueParts(Tid tid, const std::vector& svals, const SockAddr& addr); - std::vector packValueHeader(msgpack::sbuffer&, std::vector>::const_iterator, std::vector>::const_iterator) const; - std::vector packValueHeader(msgpack::sbuffer& buf, const std::vector>& values) const { + std::vector packValueHeader(msgpack::sbuffer&, + std::vector>::const_iterator, + std::vector>::const_iterator) const; + std::vector packValueHeader(msgpack::sbuffer& buf, const std::vector>& values) const + { return packValueHeader(buf, values.begin(), values.end()); } void maintainRxBuffer(Tid tid); @@ -543,29 +536,22 @@ private: void sendPong(const SockAddr& addr, Tid tid); /* answer to findnodes/getvalues request */ void sendNodesValues(const SockAddr& addr, - Tid tid, - const Blob& nodes, - const Blob& nodes6, - const std::vector>& st, - const Query& query, - const Blob& token); + Tid tid, + const Blob& nodes, + const Blob& nodes6, + const std::vector>& st, + const Query& query, + const Blob& token); Blob bufferNodes(sa_family_t af, const InfoHash& id, std::vector>& nodes); - std::pair bufferNodes(sa_family_t af, - const InfoHash& id, - want_t want, - std::vector>& nodes, - std::vector>& nodes6); + std::pair bufferNodes( + sa_family_t af, const InfoHash& id, want_t want, std::vector>& nodes, std::vector>& nodes6); /* answer to a listen request */ void sendListenConfirmation(const SockAddr& addr, Tid tid); /* answer to put request */ void sendValueAnnounced(const SockAddr& addr, Tid, Value::Id); /* answer in case of error */ - void sendError(const SockAddr& addr, - Tid tid, - uint16_t code, - const std::string& message, - bool include_id=false); + void sendError(const SockAddr& addr, Tid tid, uint16_t code, const std::string& message, bool include_id = false); void deserializeNodes(ParsedMessage& msg, const SockAddr& from); diff --git a/include/opendht/network_utils.h b/include/opendht/network_utils.h index 32fc9088..c3b5886a 100644 --- a/include/opendht/network_utils.h +++ b/include/opendht/network_utils.h @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" diff --git a/include/opendht/node.h b/include/opendht/node.h index 0a00b017..8b5b6135 100644 --- a/include/opendht/node.h +++ b/include/opendht/node.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "infohash.h" // includes socket structures @@ -36,28 +21,28 @@ struct RequestAnswer; using Tid = uint32_t; using SocketCb = std::function&, net::RequestAnswer&&)>; -struct Socket { +struct Socket +{ Socket() {} - Socket(SocketCb&& on_receive) : - on_receive(std::move(on_receive)) {} + Socket(SocketCb&& on_receive) + : on_receive(std::move(on_receive)) + {} SocketCb on_receive {}; }; -struct Node { +struct Node +{ const InfoHash id; - Node(const InfoHash& id, const SockAddr& addr, std::mt19937_64& rd, bool client=false); - Node(const InfoHash& id, SockAddr&& addr, std::mt19937_64& rd, bool client=false); + Node(const InfoHash& id, const SockAddr& addr, std::mt19937_64& rd, bool client = false); + Node(const InfoHash& id, SockAddr&& addr, std::mt19937_64& rd, bool client = false); Node(const InfoHash& id, const sockaddr* sa, socklen_t salen, std::mt19937_64& rd) - : Node(id, SockAddr(sa, salen), rd) {} + : Node(id, SockAddr(sa, salen), rd) + {} - const InfoHash& getId() const { - return id; - } + const InfoHash& getId() const { return id; } const SockAddr& getAddr() const { return addr; } - std::string getAddrStr() const { - return addr.toString(); - } + std::string getAddrStr() const { return addr.toString(); } bool isClient() const { return is_client; } bool isIncoming() { return time > reply_time; } @@ -70,7 +55,8 @@ struct Node { * to MAX_AUTH_ERRORS errors are accepted in order to let the node recover. * Upon this limit, the node expires. */ - void authError() { + void authError() + { if (++auth_errors > MAX_AUTH_ERRORS) setExpired(); } @@ -81,14 +67,11 @@ struct Node { bool isPendingMessage() const; size_t getPendingMessageCount() const; - bool isOld(const time_point& now) const { - return time + NODE_EXPIRE_TIME < now; - } - bool isRemovable(const time_point& now) const { - return isExpired() and isOld(now); - } + bool isOld(const time_point& now) const { return time + NODE_EXPIRE_TIME < now; } + bool isRemovable(const time_point& now) const { return isExpired() and isOld(now); } - NodeExport exportNode() const { + NodeExport exportNode() const + { NodeExport ne; ne.id = id; ne.addr = addr; @@ -128,21 +111,26 @@ struct Node { /** * Resets the state of the node so it's not expired anymore. */ - void reset() { expired_ = false; reply_time = time_point::min(); } + void reset() + { + expired_ = false; + reply_time = time_point::min(); + } /** * Generates a new request id, skipping the invalid id. * * @return the new id. */ - Tid getNewTid() { + Tid getNewTid() + { ++transaction_id; return transaction_id ? transaction_id : ++transaction_id; } std::string toString() const; - OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const Node& h); + OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& s, const Node& h); static constexpr const std::chrono::minutes NODE_GOOD_TIME {120}; @@ -158,8 +146,8 @@ private: SockAddr addr; bool is_client {false}; - time_point time {time_point::min()}; /* last time eared about */ - time_point reply_time {time_point::min()}; /* time of last correct reply received */ + time_point time {time_point::min()}; /* last time eared about */ + time_point reply_time {time_point::min()}; /* time of last correct reply received */ unsigned auth_errors {0}; bool expired_ {false}; Tid transaction_id; @@ -169,4 +157,4 @@ private: std::map> sockets_; }; -} +} // namespace dht diff --git a/include/opendht/node_cache.h b/include/opendht/node_cache.h index 567c73ea..1a716534 100644 --- a/include/opendht/node_cache.h +++ b/include/opendht/node_cache.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "node.h" @@ -24,16 +9,13 @@ namespace dht { -struct NodeCache { - size_t size(sa_family_t family) const { - return cache(family).count(); - } - size_t size() const { - return size(AF_INET) + size(AF_INET6); - } +struct NodeCache +{ + size_t size(sa_family_t family) const { return cache(family).count(); } + size_t size() const { return size(AF_INET) + size(AF_INET6); } Sp getNode(const InfoHash& id, sa_family_t family); - Sp getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client=false); + Sp getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client = false); std::vector> getCachedNodes(const InfoHash& id, sa_family_t sa_f, size_t count) const; /** @@ -43,19 +25,23 @@ struct NodeCache { */ void clearBadNodes(sa_family_t family = 0); - NodeCache(std::mt19937_64& r) : rd(r) {}; + NodeCache(std::mt19937_64& r) + : rd(r) {}; ~NodeCache(); private: - class NodeMap : private std::map> { + class NodeMap : private std::map> + { public: Sp getNode(const InfoHash& id); - Sp getNode(const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client, std::mt19937_64& rd); + Sp getNode( + const InfoHash& id, const SockAddr&, time_point now, bool confirmed, bool client, std::mt19937_64& rd); std::vector> getCachedNodes(const InfoHash& id, size_t count) const; void clearBadNodes(); void setExpired(); void cleanup(); size_t count() const { return size(); } + private: size_t cleanup_counter {0}; }; @@ -67,4 +53,4 @@ private: std::mt19937_64& rd; }; -} +} // namespace dht diff --git a/include/opendht/node_export.h b/include/opendht/node_export.h index 3691e6b4..66704dc8 100644 --- a/include/opendht/node_export.h +++ b/include/opendht/node_export.h @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" @@ -25,11 +11,12 @@ namespace dht { using namespace std::literals; -struct OPENDHT_PUBLIC NodeExport { +struct OPENDHT_PUBLIC NodeExport +{ InfoHash id; SockAddr addr; - template + template void msgpack_pack(Packer& pk) const { pk.pack_map(2); @@ -37,12 +24,12 @@ struct OPENDHT_PUBLIC NodeExport { pk.pack(id); pk.pack("addr"sv); pk.pack_bin(addr.getLength()); - pk.pack_bin_body((const char*)addr.get(), (size_t)addr.getLength()); + pk.pack_bin_body((const char*) addr.get(), (size_t) addr.getLength()); } void msgpack_unpack(msgpack::object o); - OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const NodeExport& h); + OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& s, const NodeExport& h); }; -} +} // namespace dht diff --git a/include/opendht/peer_discovery.h b/include/opendht/peer_discovery.h index 25a5af1f..3ed3cd0f 100644 --- a/include/opendht/peer_discovery.h +++ b/include/opendht/peer_discovery.h @@ -1,21 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * Vsevolod Ivanov - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" @@ -37,11 +21,11 @@ class OPENDHT_PUBLIC PeerDiscovery { public: static constexpr in_port_t DEFAULT_PORT = 8888; - using ServiceDiscoveredCallback = std::function; + using ServiceDiscoveredCallback = std::function; PeerDiscovery(in_port_t port = DEFAULT_PORT, - std::shared_ptr ioContext = {}, - std::shared_ptr logger = {}); + std::shared_ptr ioContext = {}, + std::shared_ptr logger = {}); ~PeerDiscovery(); /** @@ -50,21 +34,21 @@ public: */ void startDiscovery(std::string_view type, ServiceDiscoveredCallback callback); - template - void startDiscovery(std::string_view type, std::function cb) { - startDiscovery(type, [cb](msgpack::object &&ob, SockAddr &&addr) { - cb(ob.as(), std::move(addr)); - }); + template + void startDiscovery(std::string_view type, std::function cb) + { + startDiscovery(type, [cb](msgpack::object&& ob, SockAddr&& addr) { cb(ob.as(), std::move(addr)); }); } /** * startPublish - Keeping sending data until node is joinned or stop is called */ - void startPublish(std::string_view type, const msgpack::sbuffer &pack_buf); - void startPublish(sa_family_t domain, std::string_view type, const msgpack::sbuffer &pack_buf); + void startPublish(std::string_view type, const msgpack::sbuffer& pack_buf); + void startPublish(sa_family_t domain, std::string_view type, const msgpack::sbuffer& pack_buf); - template - void startPublish(std::string_view type, const T &object) { + template + void startPublish(std::string_view type, const T& object) + { msgpack::sbuffer buf; msgpack::pack(buf, object); startPublish(type, buf); diff --git a/include/opendht/proxy.h b/include/opendht/proxy.h index bc1ac699..02db700d 100644 --- a/include/opendht/proxy.h +++ b/include/opendht/proxy.h @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include @@ -22,9 +8,9 @@ namespace dht { namespace proxy { constexpr const std::chrono::hours OP_TIMEOUT {24}; // one day -constexpr const std::chrono::hours OP_MARGIN {2}; // two hours +constexpr const std::chrono::hours OP_MARGIN {2}; // two hours using ListenToken = uint64_t; -} -} +} // namespace proxy +} // namespace dht diff --git a/include/opendht/rate_limiter.h b/include/opendht/rate_limiter.h index 941629b3..8a81c201 100644 --- a/include/opendht/rate_limiter.h +++ b/include/opendht/rate_limiter.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "utils.h" @@ -22,20 +7,25 @@ namespace dht { -class RateLimiter { +class RateLimiter +{ public: RateLimiter(size_t quota, const duration& period = std::chrono::seconds(1)) - : quota_(quota), period_(period) {} + : quota_(quota) + , period_(period) + {} /** Clear outdated records and return current quota usage */ - size_t maintain(const time_point& now) { + size_t maintain(const time_point& now) + { auto limit = now - period_; while (not records.empty() and records.front() < limit) records.pop(); return records.size(); } /** Return false if quota is reached, insert record and return true otherwise. */ - bool limit(const time_point& now) { + bool limit(const time_point& now) + { if (quota_ == std::numeric_limits::max()) return true; if (maintain(now) >= quota_) @@ -43,13 +33,12 @@ public: records.emplace(now); return true; } - bool empty() const { - return records.empty(); - } + bool empty() const { return records.empty(); } + private: const size_t quota_; const duration period_; std::queue records {}; }; -} +} // namespace dht diff --git a/include/opendht/rng.h b/include/opendht/rng.h index 40790cfc..7c688f00 100644 --- a/include/opendht/rng.h +++ b/include/opendht/rng.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include @@ -26,14 +11,16 @@ namespace dht { namespace crypto { -/** +/** * Generate a seeded random engine. */ -template -auto getSeededRandomEngine() -> typename std::enable_if::type { +template +auto +getSeededRandomEngine() -> typename std::enable_if::type +{ std::array random_data; constexpr auto gen = [](std::random_device& source) -> typename T::result_type { - for (unsigned j=0; j<64; j++) { + for (unsigned j = 0; j < 64; j++) { try { return source(); } catch (...) { @@ -42,14 +29,13 @@ auto getSeededRandomEngine() -> typename std::enable_if::type { } throw std::runtime_error("Can't generate random number"); }; - for (unsigned i=0; i<8; i++) { + for (unsigned i = 0; i < 8; i++) { try { std::random_device source; for (auto& r : random_data) r = gen(source); - std::seed_seq seed( - (std::seed_seq::result_type*)random_data.data(), - (std::seed_seq::result_type*)(random_data.data() + random_data.size())); + std::seed_seq seed((std::seed_seq::result_type*) random_data.data(), + (std::seed_seq::result_type*) (random_data.data() + random_data.size())); return T(seed); } catch (...) { std::this_thread::sleep_for(std::chrono::microseconds(500)); @@ -61,14 +47,16 @@ auto getSeededRandomEngine() -> typename std::enable_if::type { /** * Generate a random engine from another source. */ -template -auto getDerivedRandomEngine(T& source) -> typename std::enable_if::type { +template +auto +getDerivedRandomEngine(T& source) -> typename std::enable_if::type +{ std::array random_data; std::generate(random_data.begin(), random_data.end(), std::ref(source)); - std::seed_seq seed( - (std::seed_seq::result_type*)random_data.data(), - (std::seed_seq::result_type*)(random_data.data() + random_data.size())); + std::seed_seq seed((std::seed_seq::result_type*) random_data.data(), + (std::seed_seq::result_type*) (random_data.data() + random_data.size())); return T(seed); } -}} // dht::crypto +} // namespace crypto +} // namespace dht diff --git a/include/opendht/routing_table.h b/include/opendht/routing_table.h index 93854376..82bff9e3 100644 --- a/include/opendht/routing_table.h +++ b/include/opendht/routing_table.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "node.h" @@ -26,28 +11,37 @@ namespace net { class NetworkEngine; } -struct Bucket { - Bucket() : cached() {} +struct Bucket +{ + Bucket() + : cached() + {} Bucket(sa_family_t af, const InfoHash& f = {}, time_point t = time_point::min()) - : af(af), first(f), time(t), cached() {} + : af(af) + , first(f) + , time(t) + , cached() + {} sa_family_t af {0}; InfoHash first {}; time_point time {time_point::min()}; /* time of last reply in this bucket */ std::list> nodes {}; - Sp cached; /* the address of a likely candidate */ + Sp cached; /* the address of a likely candidate */ /** Return a random node in a bucket. */ Sp randomNode(std::mt19937_64& rd); void sendCachedPing(net::NetworkEngine& ne); - void connectivityChanged() { + void connectivityChanged() + { time = time_point::min(); for (auto& node : nodes) node->setTime(time_point::min()); } }; -class RoutingTable : public std::list { +class RoutingTable : public std::list +{ public: using std::list::list; @@ -64,25 +58,26 @@ public: /** * Return true if the id is in the bucket's range. */ - inline bool contains(const RoutingTable::const_iterator& bucket, const InfoHash& id) const { + inline bool contains(const RoutingTable::const_iterator& bucket, const InfoHash& id) const + { return InfoHash::cmp(bucket->first, id) <= 0 - && (std::next(bucket) == end() || InfoHash::cmp(id, std::next(bucket)->first) < 0); + && (std::next(bucket) == end() || InfoHash::cmp(id, std::next(bucket)->first) < 0); } /** * Return true if the table has no bucket ore one empty buket. */ - inline bool isEmpty() const { - return empty() || (size() == 1 && front().nodes.empty()); - } + inline bool isEmpty() const { return empty() || (size() == 1 && front().nodes.empty()); } - void connectivityChanged(const time_point& now) { + void connectivityChanged(const time_point& now) + { grow_time = now; for (auto& b : *this) b.connectivityChanged(); } - bool onNewNode(const Sp& node, int comfirm, const time_point& now, const InfoHash& myid, net::NetworkEngine& ne); + bool onNewNode( + const Sp& node, int comfirm, const time_point& now, const InfoHash& myid, net::NetworkEngine& ne); /** * Return a random id in the bucket's range. @@ -97,4 +92,4 @@ public: bool split(const RoutingTable::iterator& b); }; -} +} // namespace dht diff --git a/include/opendht/scheduler.h b/include/opendht/scheduler.h index 3f947598..25f5d4c9 100644 --- a/include/opendht/scheduler.h +++ b/include/opendht/scheduler.h @@ -1,21 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "utils.h" @@ -31,10 +15,15 @@ namespace dht { * @details * Maintains the timings upon which to execute a job. */ -class Scheduler { +class Scheduler +{ public: - struct Job { - Job(std::function&& f, time_point t) : do_(std::move(f)), t_(t) {} + struct Job + { + Job(std::function&& f, time_point t) + : do_(std::move(f)) + , t_(t) + {} std::function do_; const time_point t_; void cancel() { do_ = {}; } @@ -48,7 +37,8 @@ public: * * @return pointer to the newly scheduled job. */ - Sp add(time_point t, std::function&& job_func) { + Sp add(time_point t, std::function&& job_func) + { auto job = std::make_shared(std::move(job_func), t); if (t != time_point::max()) timers.emplace(std::move(t), job); @@ -61,7 +51,8 @@ public: * @param job The job to edit. * @param t The time at which the job shall be rescheduled. */ - void edit(Sp& job, time_point t) { + void edit(Sp& job, time_point t) + { if (not job) return; // std::function move doesn't garantee to leave the object empty. @@ -71,7 +62,8 @@ public: job = add(t, std::move(task)); } - bool cancel(Sp& job) { + bool cancel(Sp& job) + { if (job) { job->cancel(); for (auto r = timers.equal_range(job->t_); r.first != r.second; ++r.first) { @@ -90,7 +82,8 @@ public: * * @return The time for the next job to run. */ - time_point run() { + time_point run() + { while (not timers.empty()) { auto timer = timers.begin(); /* @@ -110,9 +103,7 @@ public: return getNextJobTime(); } - inline time_point getNextJobTime() const { - return timers.empty() ? time_point::max() : timers.begin()->first; - } + inline time_point getNextJobTime() const { return timers.empty() ? time_point::max() : timers.begin()->first; } /** * Accessors for the common time reference used for synchronizing @@ -127,4 +118,4 @@ private: std::multimap> timers {}; /* the jobs ordered by time */ }; -} +} // namespace dht diff --git a/include/opendht/securedht.h b/include/opendht/securedht.h index 86112075..ab592da3 100644 --- a/include/opendht/securedht.h +++ b/include/opendht/securedht.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "dht.h" @@ -27,9 +12,9 @@ namespace dht { -class OPENDHT_PUBLIC SecureDht final : public DhtInterface { +class OPENDHT_PUBLIC SecureDht final : public DhtInterface +{ public: - typedef std::function SignatureCheckCallback; using Config = SecureDhtConfig; @@ -38,7 +23,7 @@ public: { auto c = conf.node_config; if (not c.node_id and conf.id.second) - c.node_id = InfoHash::get("node:"+conf.id.second->getId().toString()); + c.node_id = InfoHash::get("node:" + conf.id.second->getId().toString()); return c; } @@ -48,36 +33,37 @@ public: * id: the identity to use for the crypto layer and to compute * our own hash on the Dht. */ - SecureDht(std::unique_ptr dht, Config config, IdentityAnnouncedCb iacb = {}, const std::shared_ptr& l = {}); + SecureDht(std::unique_ptr dht, + Config config, + IdentityAnnouncedCb iacb = {}, + const std::shared_ptr& l = {}); virtual ~SecureDht(); - InfoHash getId() const { - return key_ ? key_->getPublicKey().getId() : InfoHash(); - } - PkId getLongId() const { - return key_ ? key_->getPublicKey().getLongId() : PkId(); - } - Sp getPublicKey() const { - return key_ ? key_->getSharedPublicKey() : Sp{}; - } + InfoHash getId() const { return key_ ? key_->getPublicKey().getId() : InfoHash(); } + PkId getLongId() const { return key_ ? key_->getPublicKey().getLongId() : PkId(); } + Sp getPublicKey() const { return key_ ? key_->getSharedPublicKey() : Sp {}; } ValueType secureType(ValueType&& type); - ValueType secureType(const ValueType& type) { + ValueType secureType(const ValueType& type) + { ValueType tmp_type = type; return secureType(std::move(tmp_type)); } - void registerType(const ValueType& type) override { + void registerType(const ValueType& type) override + { if (dht_) dht_->registerType(secureType(type)); } - void registerType(ValueType&& type) { + void registerType(ValueType&& type) + { if (dht_) dht_->registerType(secureType(std::forward(type))); } - void registerInsecureType(const ValueType& type) { + void registerInsecureType(const ValueType& type) + { if (dht_) dht_->registerType(type); } @@ -87,14 +73,29 @@ public: * If the signature is unable to be checked, or if the data is unable to be decrypted, it is not returned. * Public, non-signed & non-encrypted data is retransmitted as-is. */ - void get(const InfoHash& id, GetCallback cb, DoneCallback donecb={}, Value::Filter&& = {}, Where&& w = {}) override; - void get(const InfoHash& id, GetCallback cb, DoneCallbackSimple donecb={}, Value::Filter&& f = {}, Where&& w = {}) override { + void get(const InfoHash& id, GetCallback cb, DoneCallback donecb = {}, Value::Filter&& = {}, Where&& w = {}) override; + void get(const InfoHash& id, + GetCallback cb, + DoneCallbackSimple donecb = {}, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(id, cb, bindDoneCb(donecb), std::forward(f), std::forward(w)); } - void get(const InfoHash& key, GetCallbackSimple cb, DoneCallback donecb={}, Value::Filter&& f={}, Where&& w = {}) override { + void get(const InfoHash& key, + GetCallbackSimple cb, + DoneCallback donecb = {}, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(key, bindGetCb(cb), donecb, std::forward(f), std::forward(w)); } - void get(const InfoHash& key, GetCallbackSimple cb, DoneCallbackSimple donecb, Value::Filter&& f={}, Where&& w = {}) override { + void get(const InfoHash& key, + GetCallbackSimple cb, + DoneCallbackSimple donecb, + Value::Filter&& f = {}, + Where&& w = {}) override + { get(key, bindGetCb(cb), bindDoneCb(donecb), std::forward(f), std::forward(w)); } @@ -102,7 +103,8 @@ public: * Will take ownership of the value, sign it using our private key and put it in the DHT. */ void putSigned(const InfoHash& hash, Sp val, DoneCallback callback, bool permanent = false); - void putSigned(const InfoHash& hash, Value&& v, DoneCallback callback, bool permanent = false) { + void putSigned(const InfoHash& hash, Value&& v, DoneCallback callback, bool permanent = false) + { putSigned(hash, std::make_shared(std::move(v)), callback, permanent); } @@ -111,16 +113,24 @@ public: * and put it in the DHT. * The operation will be immediate if the recipient' public key is known (otherwise it will be retrived first). */ - void putEncrypted(const InfoHash& hash, const InfoHash& to, Sp val, DoneCallback callback, bool permanent = false); + void putEncrypted( + const InfoHash& hash, const InfoHash& to, Sp val, DoneCallback callback, bool permanent = false); [[deprecated("Use the shared_ptr version instead")]] - void putEncrypted(const InfoHash& hash, const InfoHash& to, Value&& v, DoneCallback callback, bool permanent = false) { + void putEncrypted(const InfoHash& hash, const InfoHash& to, Value&& v, DoneCallback callback, bool permanent = false) + { putEncrypted(hash, to, std::make_shared(std::move(v)), callback, permanent); } - void putEncrypted(const InfoHash& hash, const crypto::PublicKey& to, Sp val, DoneCallback callback, bool permanent = false); + void putEncrypted(const InfoHash& hash, + const crypto::PublicKey& to, + Sp val, + DoneCallback callback, + bool permanent = false); [[deprecated("Use the shared_ptr version instead")]] - void putEncrypted(const InfoHash& hash, const crypto::PublicKey& to, Value&& v, DoneCallback callback, bool permanent = false) { + void putEncrypted( + const InfoHash& hash, const crypto::PublicKey& to, Value&& v, DoneCallback callback, bool permanent = false) + { putEncrypted(hash, to, std::make_shared(std::move(v)), callback, permanent); } @@ -154,201 +164,142 @@ public: * The search key used is the public key ID, so there may be multiple certificates retured, signed with * the same private key. */ - void setLocalCertificateStore(CertificateStoreQueryLegacy&& query_method) { + void setLocalCertificateStore(CertificateStoreQueryLegacy&& query_method) + { localQueryMethodLegacy_ = std::move(query_method); } - void setLocalCertificateStore(CertificateStoreQuery&& query_method) { - localQueryMethod_ = std::move(query_method); - } - void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { - dht_->setOnPublicAddressChanged(cb); - } + void setLocalCertificateStore(CertificateStoreQuery&& query_method) { localQueryMethod_ = std::move(query_method); } + void setOnPublicAddressChanged(PublicAddressChangedCb cb) override { dht_->setOnPublicAddressChanged(cb); } /** * SecureDht to Dht proxy */ - void shutdown(ShutdownCallback cb, bool stop = false) override { - dht_->shutdown(cb, stop); - } - void dumpTables() const override { - dht_->dumpTables(); - } + void shutdown(ShutdownCallback cb, bool stop = false) override { dht_->shutdown(cb, stop); } + void dumpTables() const override { dht_->dumpTables(); } inline const InfoHash& getNodeId() const override { return dht_->getNodeId(); } - std::pair getStoreSize() const override { - return dht_->getStoreSize(); - } - std::string getStorageLog() const override { - return dht_->getStorageLog(); - } - std::string getStorageLog(const InfoHash& h) const override { - return dht_->getStorageLog(h); - } - void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) override { - dht_->setStorageLimit(limit); - } - size_t getStorageLimit() const override { - return dht_->getStorageLimit(); - } + std::pair getStoreSize() const override { return dht_->getStoreSize(); } + std::string getStorageLog() const override { return dht_->getStorageLog(); } + std::string getStorageLog(const InfoHash& h) const override { return dht_->getStorageLog(h); } + void setStorageLimit(size_t limit = DEFAULT_STORAGE_LIMIT) override { dht_->setStorageLimit(limit); } + size_t getStorageLimit() const override { return dht_->getStorageLimit(); } - std::vector exportNodes() const override { - return dht_->exportNodes(); - } - std::vector exportValues() const override { - return dht_->exportValues(); - } - void importValues(const std::vector& v) override { - dht_->importValues(v); - } - NodeStats getNodesStats(sa_family_t af) const override { - return dht_->getNodesStats(af); - } - std::vector getNodeMessageStats(bool in = false) override { - return dht_->getNodeMessageStats(in); - } - std::string getRoutingTablesLog(sa_family_t af) const override { - return dht_->getRoutingTablesLog(af); - } - std::string getSearchesLog(sa_family_t af) const override { - return dht_->getSearchesLog(af); - } - std::string getSearchLog(const InfoHash& h, sa_family_t af = AF_UNSPEC) const override { + std::vector exportNodes() const override { return dht_->exportNodes(); } + std::vector exportValues() const override { return dht_->exportValues(); } + void importValues(const std::vector& v) override { dht_->importValues(v); } + NodeStats getNodesStats(sa_family_t af) const override { return dht_->getNodesStats(af); } + std::vector getNodeMessageStats(bool in = false) override { return dht_->getNodeMessageStats(in); } + std::string getRoutingTablesLog(sa_family_t af) const override { return dht_->getRoutingTablesLog(af); } + std::string getSearchesLog(sa_family_t af) const override { return dht_->getSearchesLog(af); } + std::string getSearchLog(const InfoHash& h, sa_family_t af = AF_UNSPEC) const override + { return dht_->getSearchLog(h, af); } - std::vector getPublicAddress(sa_family_t family = 0) override { - return dht_->getPublicAddress(family); - } - time_point periodic(const uint8_t *buf, size_t buflen, SockAddr sa, const time_point& now) override { + std::vector getPublicAddress(sa_family_t family = 0) override { return dht_->getPublicAddress(family); } + time_point periodic(const uint8_t* buf, size_t buflen, SockAddr sa, const time_point& now) override + { return dht_->periodic(buf, buflen, std::move(sa), now); } - time_point periodic(const uint8_t *buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override { + time_point periodic( + const uint8_t* buf, size_t buflen, const sockaddr* from, socklen_t fromlen, const time_point& now) override + { return dht_->periodic(buf, buflen, from, fromlen, now); } - NodeStatus updateStatus(sa_family_t af) override { - return dht_->updateStatus(af); - } - NodeStatus getStatus(sa_family_t af) const override { - return dht_->getStatus(af); - } - NodeStatus getStatus() const override { - return dht_->getStatus(); - } - net::DatagramSocket* getSocket() const override { - return dht_->getSocket(); - }; - bool isRunning(sa_family_t af = 0) const override { - return dht_->isRunning(af); - } - const ValueType& getType(ValueType::Id type_id) const override { - return dht_->getType(type_id); - } - void addBootstrap(const std::string& host, const std::string& service) override { + NodeStatus updateStatus(sa_family_t af) override { return dht_->updateStatus(af); } + NodeStatus getStatus(sa_family_t af) const override { return dht_->getStatus(af); } + NodeStatus getStatus() const override { return dht_->getStatus(); } + net::DatagramSocket* getSocket() const override { return dht_->getSocket(); }; + bool isRunning(sa_family_t af = 0) const override { return dht_->isRunning(af); } + const ValueType& getType(ValueType::Id type_id) const override { return dht_->getType(type_id); } + void addBootstrap(const std::string& host, const std::string& service) override + { dht_->addBootstrap(host, service); } - void clearBootstrap() override { - dht_->clearBootstrap(); - } - void insertNode(const InfoHash& id, const SockAddr& sa) override { - dht_->insertNode(id, sa); - } - void insertNode(const NodeExport& n) override { - dht_->insertNode(n); - } - void pingNode(SockAddr sa, DoneCallbackSimple&& cb={}) override { - dht_->pingNode(std::move(sa), std::move(cb)); - } - void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override { + void clearBootstrap() override { dht_->clearBootstrap(); } + void insertNode(const InfoHash& id, const SockAddr& sa) override { dht_->insertNode(id, sa); } + void insertNode(const NodeExport& n) override { dht_->insertNode(n); } + void pingNode(SockAddr sa, DoneCallbackSimple&& cb = {}) override { dht_->pingNode(std::move(sa), std::move(cb)); } + void query(const InfoHash& key, QueryCallback cb, DoneCallback done_cb = {}, Query&& q = {}) override + { dht_->query(key, cb, done_cb, std::move(q)); } - void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override { + void query(const InfoHash& key, QueryCallback cb, DoneCallbackSimple done_cb = {}, Query&& q = {}) override + { dht_->query(key, cb, done_cb, std::move(q)); } - std::vector> getLocal(const InfoHash& key, const Value::Filter& f = {}) const override { + std::vector> getLocal(const InfoHash& key, const Value::Filter& f = {}) const override + { return dht_->getLocal(key, f); } - Sp getLocalById(const InfoHash& key, Value::Id vid) const override { - return dht_->getLocalById(key, vid); - } + Sp getLocalById(const InfoHash& key, Value::Id vid) const override { return dht_->getLocalById(key, vid); } void put(const InfoHash& key, - Sp v, - DoneCallback cb=nullptr, - time_point created=time_point::max(), - bool permanent = false) override + Sp v, + DoneCallback cb = nullptr, + time_point created = time_point::max(), + bool permanent = false) override { dht_->put(key, v, cb, created, permanent); } void put(const InfoHash& key, - const Sp& v, - DoneCallbackSimple cb, - time_point created=time_point::max(), - bool permanent = false) override + const Sp& v, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) override { dht_->put(key, v, cb, created, permanent); } void put(const InfoHash& key, - Value&& v, - DoneCallback cb=nullptr, - time_point created=time_point::max(), - bool permanent = false) override + Value&& v, + DoneCallback cb = nullptr, + time_point created = time_point::max(), + bool permanent = false) override { dht_->put(key, std::move(v), cb, created, permanent); } void put(const InfoHash& key, - Value&& v, - DoneCallbackSimple cb, - time_point created=time_point::max(), - bool permanent = false) override + Value&& v, + DoneCallbackSimple cb, + time_point created = time_point::max(), + bool permanent = false) override { dht_->put(key, std::move(v), cb, created, permanent); } - std::vector> getPut(const InfoHash& h) const override { - return dht_->getPut(h); - } - Sp getPut(const InfoHash& h, const Value::Id& vid) const override { - return dht_->getPut(h, vid); - } - bool cancelPut(const InfoHash& h, const Value::Id& vid) override { - return dht_->cancelPut(h, vid); - } + std::vector> getPut(const InfoHash& h) const override { return dht_->getPut(h); } + Sp getPut(const InfoHash& h, const Value::Id& vid) const override { return dht_->getPut(h, vid); } + bool cancelPut(const InfoHash& h, const Value::Id& vid) override { return dht_->cancelPut(h, vid); } - size_t listen(const InfoHash& key, ValueCallback, Value::Filter={}, Where={}) override; + size_t listen(const InfoHash& key, ValueCallback, Value::Filter = {}, Where = {}) override; size_t listen(const InfoHash& key, GetCallback cb, Value::Filter = {}, Where w = {}) override; - size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f={}, Where w = {}) override { + size_t listen(const InfoHash& key, GetCallbackSimple cb, Value::Filter f = {}, Where w = {}) override + { return listen(key, bindGetCb(cb), f, w); } - bool cancelListen(const InfoHash& h, size_t token) override { - return dht_->cancelListen(h, token); - } - void connectivityChanged(sa_family_t af) override { - dht_->connectivityChanged(af); - } - void connectivityChanged() override { - dht_->connectivityChanged(); - } + bool cancelListen(const InfoHash& h, size_t token) override { return dht_->cancelListen(h, token); } + void connectivityChanged(sa_family_t af) override { dht_->connectivityChanged(af); } + void connectivityChanged() override { dht_->connectivityChanged(); } - void forwardAllMessages(bool forward) { - forward_all_ = forward; - } + void forwardAllMessages(bool forward) { forward_all_ = forward; } - void setPushNotificationToken(const std::string& token = "") override { - dht_->setPushNotificationToken(token); - } + void setPushNotificationToken(const std::string& token = "") override { dht_->setPushNotificationToken(token); } /** * Call linked callback with push_notification * @param notification to process */ - PushNotificationResult pushNotificationReceived(const std::map& notification) override { + PushNotificationResult pushNotificationReceived(const std::map& notification) override + { return dht_->pushNotificationReceived(notification); } - void setLogger(const Logger& logger) override { + void setLogger(const Logger& logger) override + { DhtInterface::setLogger(logger); dht_->setLogger(logger); } - void setLogger(const std::shared_ptr& logger) override { + void setLogger(const std::shared_ptr& logger) override + { DhtInterface::setLogger(logger); dht_->setLogger(logger); } @@ -356,7 +307,8 @@ public: /** * Only print logs related to the given InfoHash (if given), or disable filter (if zeroes). */ - void setLogFilter(const InfoHash& f) override { + void setLogFilter(const InfoHash& f) override + { DhtInterface::setLogFilter(f); dht_->setLogFilter(f); } @@ -391,23 +343,27 @@ private: bool enableCache_ {false}; }; -const ValueType CERTIFICATE_TYPE = { - 8, "Certificate", std::chrono::hours(24 * 7), - // A certificate can only be stored at its public key ID. - [](InfoHash id, Sp& v, const InfoHash&, const SockAddr&) { - try { - crypto::Certificate crt(v->data); - // TODO check certificate signature - return crt.getPublicKey().getId() == id || InfoHash::get(crt.getPublicKey().getLongId()) == id; - } catch (const std::exception& e) {} - return false; - }, - [](InfoHash, const Sp& o, Sp& n, const InfoHash&, const SockAddr&) { - try { - return crypto::Certificate(o->data).getPublicKey().getLongId() == crypto::Certificate(n->data).getPublicKey().getLongId(); - } catch (const std::exception& e) {} - return false; - } -}; +const ValueType CERTIFICATE_TYPE = {8, + "Certificate", + std::chrono::hours(24 * 7), + // A certificate can only be stored at its public key ID. + [](InfoHash id, Sp& v, const InfoHash&, const SockAddr&) { + try { + crypto::Certificate crt(v->data); + // TODO check certificate signature + return crt.getPublicKey().getId() == id + || InfoHash::get(crt.getPublicKey().getLongId()) == id; + } catch (const std::exception& e) { + } + return false; + }, + [](InfoHash, const Sp& o, Sp& n, const InfoHash&, const SockAddr&) { + try { + return crypto::Certificate(o->data).getPublicKey().getLongId() + == crypto::Certificate(n->data).getPublicKey().getLongId(); + } catch (const std::exception& e) { + } + return false; + }}; -} +} // namespace dht diff --git a/include/opendht/sockaddr.h b/include/opendht/sockaddr.h index d22c14c6..ef16a1b3 100644 --- a/include/opendht/sockaddr.h +++ b/include/opendht/sockaddr.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" @@ -58,30 +43,34 @@ OPENDHT_PUBLIC std::string print_addr(const sockaddr_storage& ss, socklen_t ssle /** * A Socket Address (sockaddr*), with abstraction for IPv4, IPv6 address families. */ -class OPENDHT_PUBLIC SockAddr { +class OPENDHT_PUBLIC SockAddr +{ public: SockAddr() {} - SockAddr(const SockAddr& o) { - set(o.get(), o.getLength()); - } - SockAddr(SockAddr&& o) noexcept : addr(std::move(o.addr)), len(o.len) { + SockAddr(const SockAddr& o) { set(o.get(), o.getLength()); } + SockAddr(SockAddr&& o) noexcept + : addr(std::move(o.addr)) + , len(o.len) + { o.len = 0; } /** * Build from existing address. */ - SockAddr(const sockaddr* sa, socklen_t length) { + SockAddr(const sockaddr* sa, socklen_t length) + { if (length > static_cast(sizeof(sockaddr_storage))) throw std::runtime_error("Socket address length is too large"); set(sa, length); } - SockAddr(const sockaddr* sa) { + SockAddr(const sockaddr* sa) + { socklen_t len = 0; if (sa) { if (sa->sa_family == AF_INET) len = sizeof(sockaddr_in); - else if(sa->sa_family == AF_INET6) + else if (sa->sa_family == AF_INET6) len = sizeof(sockaddr_in6); else throw std::runtime_error("Unknown address family"); @@ -92,34 +81,37 @@ public: /** * Build from an existing sockaddr_storage structure. */ - SockAddr(const sockaddr_storage& ss, socklen_t len) : SockAddr((const sockaddr*)&ss, len) {} + SockAddr(const sockaddr_storage& ss, socklen_t len) + : SockAddr((const sockaddr*) &ss, len) + {} static std::vector resolve(const std::string& host, const std::string& service = {}); - bool operator<(const SockAddr& o) const { + bool operator<(const SockAddr& o) const + { if (len != o.len) return len < o.len; - return std::memcmp((const uint8_t*)get(), (const uint8_t*)o.get(), len) < 0; + return std::memcmp((const uint8_t*) get(), (const uint8_t*) o.get(), len) < 0; } - bool equals(const SockAddr& o) const { - return len == o.len - && std::memcmp((const uint8_t*)get(), (const uint8_t*)o.get(), len) == 0; + bool equals(const SockAddr& o) const + { + return len == o.len && std::memcmp((const uint8_t*) get(), (const uint8_t*) o.get(), len) == 0; } - SockAddr& operator=(const SockAddr& o) { + SockAddr& operator=(const SockAddr& o) + { set(o.get(), o.getLength()); return *this; } - SockAddr& operator=(SockAddr&& o) { + SockAddr& operator=(SockAddr&& o) + { len = o.len; o.len = 0; addr = std::move(o.addr); return *this; } - std::string toString() const { - return print_addr(get(), getLength()); - } + std::string toString() const { return print_addr(get(), getLength()); } /** * Returns the address family or AF_UNSPEC if the address is not set. @@ -131,9 +123,10 @@ public: * in which case the sockaddr structure is cleared to zero, * and set the address family field (sa_family). */ - void setFamily(sa_family_t af) { + void setFamily(sa_family_t af) + { socklen_t new_length; - switch(af) { + switch (af) { case AF_INET: new_length = sizeof(sockaddr_in); break; @@ -145,8 +138,10 @@ public: } if (new_length != len) { len = new_length; - if (len) addr.reset((sockaddr*)::calloc(len, 1)); - else addr.reset(); + if (len) + addr.reset((sockaddr*) ::calloc(len, 1)); + else + addr.reset(); } if (len) addr->sa_family = af; @@ -155,9 +150,10 @@ public: /** * Set address to any */ - void setAny() { + void setAny() + { auto family = getFamily(); - switch(family) { + switch (family) { case AF_INET: getIPv4().sin_addr.s_addr = htonl(INADDR_ANY); break; @@ -170,9 +166,10 @@ public: /** * Set address to loopback. */ - void setLoopback() { + void setLoopback() + { auto family = getFamily(); - switch(family) { + switch (family) { case AF_INET: getIPv4().sin_addr.s_addr = htonl(INADDR_LOOPBACK); break; @@ -186,8 +183,9 @@ public: * Retreive the port (in host byte order) or 0 if the address is not * of a supported family. */ - in_port_t getPort() const { - switch(getFamily()) { + in_port_t getPort() const + { + switch (getFamily()) { case AF_INET: return ntohs(getIPv4().sin_port); case AF_INET6: @@ -200,8 +198,9 @@ public: * Set the port. The address must be of a supported family. * @param p The port in host byte order. */ - void setPort(in_port_t p) { - switch(getFamily()) { + void setPort(in_port_t p) + { + switch (getFamily()) { case AF_INET: getIPv4().sin_port = htons(p); break; @@ -226,9 +225,7 @@ public: /** * An address is defined to be true if its length is not zero. */ - explicit operator bool() const noexcept { - return len; - } + explicit operator bool() const noexcept { return len; } /** * Returns the address to the managed sockaddr structure. @@ -242,24 +239,17 @@ public: */ sockaddr* get() { return addr.get(); } - inline const sockaddr_in& getIPv4() const { - return *reinterpret_cast(get()); - } - inline const sockaddr_in6& getIPv6() const { - return *reinterpret_cast(get()); - } - inline sockaddr_in& getIPv4() { - return *reinterpret_cast(get()); - } - inline sockaddr_in6& getIPv6() { - return *reinterpret_cast(get()); - } + inline const sockaddr_in& getIPv4() const { return *reinterpret_cast(get()); } + inline const sockaddr_in6& getIPv6() const { return *reinterpret_cast(get()); } + inline sockaddr_in& getIPv4() { return *reinterpret_cast(get()); } + inline sockaddr_in6& getIPv6() { return *reinterpret_cast(get()); } - /** + /** * Releases the ownership of the managed object, if any. * The caller is responsible for deleting the object with free(). */ - inline sockaddr* release() { + inline sockaddr* release() + { len = 0; return addr.release(); } @@ -284,56 +274,65 @@ public: * A comparator to classify IP addresses, only considering the * first 64 bits in IPv6. */ - struct ipCmp { - bool operator()(const SockAddr& a, const SockAddr& b) const { + struct ipCmp + { + bool operator()(const SockAddr& a, const SockAddr& b) const + { if (a.len != b.len) return a.len < b.len; socklen_t start, len; - switch(a.getFamily()) { - case AF_INET: - start = offsetof(sockaddr_in, sin_addr); - len = sizeof(in_addr); - break; - case AF_INET6: - start = offsetof(sockaddr_in6, sin6_addr); - // don't consider more than 64 bits (IPv6) - len = 8; - break; - default: - start = 0; - len = a.len; - break; + switch (a.getFamily()) { + case AF_INET: + start = offsetof(sockaddr_in, sin_addr); + len = sizeof(in_addr); + break; + case AF_INET6: + start = offsetof(sockaddr_in6, sin6_addr); + // don't consider more than 64 bits (IPv6) + len = 8; + break; + default: + start = 0; + len = a.len; + break; } - return std::memcmp((uint8_t*)a.get()+start, - (uint8_t*)b.get()+start, len) < 0; + return std::memcmp((uint8_t*) a.get() + start, (uint8_t*) b.get() + start, len) < 0; } }; - friend std::ostream& operator<< (std::ostream& s, const SockAddr& h) { + friend std::ostream& operator<<(std::ostream& s, const SockAddr& h) + { print_addr(s, h.get(), h.getLength()); return s; } private: - struct free_delete { void operator()(void* p) { ::free(p); } }; + struct free_delete + { + void operator()(void* p) { ::free(p); } + }; std::unique_ptr addr {}; socklen_t len {0}; - void set(const sockaddr* sa, socklen_t length) { + void set(const sockaddr* sa, socklen_t length) + { if (len != length) { len = length; - if (len) addr.reset((sockaddr*)::malloc(len)); - else addr.reset(); + if (len) + addr.reset((sockaddr*) ::malloc(len)); + else + addr.reset(); } if (len) - std::memcpy((uint8_t*)get(), (const uint8_t*)sa, len); + std::memcpy((uint8_t*) get(), (const uint8_t*) sa, len); } - }; OPENDHT_PUBLIC bool operator==(const SockAddr& a, const SockAddr& b); -} +} // namespace dht #if FMT_VERSION >= 90000 -template <> struct fmt::formatter : ostream_formatter {}; +template<> +struct fmt::formatter : ostream_formatter +{}; #endif \ No newline at end of file diff --git a/include/opendht/thread_pool.h b/include/opendht/thread_pool.h index a6a90a1e..85d731c2 100644 --- a/include/opendht/thread_pool.h +++ b/include/opendht/thread_pool.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" @@ -29,7 +14,8 @@ namespace dht { -class OPENDHT_PUBLIC ThreadPool { +class OPENDHT_PUBLIC ThreadPool +{ public: static ThreadPool& computation(); static ThreadPool& io(); @@ -41,7 +27,8 @@ public: void run(std::function&& cb); template - std::future get(std::function&& cb) { + std::future get(std::function&& cb) + { auto ret = std::make_shared>(); run([cb = std::move(cb), ret]() mutable { try { @@ -49,13 +36,15 @@ public: } catch (...) { try { ret->set_exception(std::current_exception()); - } catch(...) {} + } catch (...) { + } } }); return ret->get_future(); } template - std::shared_future getShared(std::function&& cb) { + std::shared_future getShared(std::function&& cb) + { return get(std::move(cb)); } @@ -79,10 +68,12 @@ private: void threadEnded(std::thread&); }; -class OPENDHT_PUBLIC Executor : public std::enable_shared_from_this { +class OPENDHT_PUBLIC Executor : public std::enable_shared_from_this +{ public: Executor(ThreadPool& pool, unsigned maxConcurrent = 1) - : threadPool_(pool), maxConcurrent_(maxConcurrent) + : threadPool_(pool) + , maxConcurrent_(maxConcurrent) {} void run(std::function&& task); @@ -98,32 +89,31 @@ private: void schedule(); }; -class OPENDHT_PUBLIC ExecutionContext { +class OPENDHT_PUBLIC ExecutionContext +{ public: ExecutionContext(ThreadPool& pool) - : threadPool_(pool), state_(std::make_shared()) + : threadPool_(pool) + , state_(std::make_shared()) {} - ~ExecutionContext() { - state_->destroy(); - } + ~ExecutionContext() { state_->destroy(); } /** Wait for ongoing tasks to complete execution and drop other pending tasks */ - void stop() { - state_->destroy(false); - } + void stop() { state_->destroy(false); } - void run(std::function&& task) { + void run(std::function&& task) + { std::lock_guard lock(state_->mtx); - if (state_->shutdown_) return; + if (state_->shutdown_) + return; state_->pendingTasks++; - threadPool_.get().run([task = std::move(task), state = state_] { - state->run(task); - }); + threadPool_.get().run([task = std::move(task), state = state_] { state->run(task); }); } private: - struct SharedState { + struct SharedState + { std::mutex mtx {}; std::condition_variable cv {}; unsigned pendingTasks {0}; @@ -133,9 +123,11 @@ private: /** When true, prevents scheduled tasks to be executed */ std::atomic_bool destroyed {false}; - void destroy(bool wait = true) { + void destroy(bool wait = true) + { std::unique_lock lock(mtx); - if (destroyed) return; + if (destroyed) + return; if (wait) { cv.wait(lock, [this] { return pendingTasks == 0 && ongoingTasks == 0; }); } @@ -146,14 +138,16 @@ private: destroyed = true; } - void run(const std::function& task) { + void run(const std::function& task) + { { std::lock_guard lock(mtx); pendingTasks--; ongoingTasks++; } - if (destroyed) return; - task(); + if (destroyed) + return; + task(); { std::lock_guard lock(mtx); ongoingTasks--; @@ -165,4 +159,4 @@ private: std::shared_ptr state_; }; -} +} // namespace dht diff --git a/include/opendht/utils.h b/include/opendht/utils.h index 261f415b..3c4a7bd3 100644 --- a/include/opendht/utils.h +++ b/include/opendht/utils.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "def.h" @@ -138,8 +123,7 @@ print_time_relative(TimePoint now, TimePoint d) return "never"s; if (d == now) return "now"s; - return (d > now) ? concat("in "sv, print_duration(d - now)) - : concat(print_duration(now - d), " ago"sv); + return (d > now) ? concat("in "sv, print_duration(d - now)) : concat(print_duration(now - d), " ago"sv); } template diff --git a/include/opendht/value.h b/include/opendht/value.h index ae0d3e70..90cc2bdd 100644 --- a/include/opendht/value.h +++ b/include/opendht/value.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "infohash.h" @@ -69,7 +54,8 @@ struct Query; * @param form_addr: network address of the incoming request. * @param from_len: network address lendth of the incoming request. */ -using StorePolicy = std::function& value, const InfoHash& from, const SockAddr& addr)>; +using StorePolicy + = std::function& value, const InfoHash& from, const SockAddr& addr)>; /** * An edition policy is applied once to every incoming value storage requests, @@ -85,37 +71,52 @@ using StorePolicy = std::function& val * @param form_addr: network address of the incoming request. * @param from_len: network address lendth of the incoming request. */ -using EditPolicy = std::function& old_val, std::shared_ptr& new_val, const InfoHash& from, const SockAddr& addr)>; +using EditPolicy = std::function& old_val, + std::shared_ptr& new_val, + const InfoHash& from, + const SockAddr& addr)>; static constexpr const size_t MAX_VALUE_SIZE {1024 * 64}; static constexpr const duration DEFAULT_VALUE_EXPIRATION {std::chrono::minutes(10)}; -struct ValueType { +struct ValueType +{ typedef uint16_t Id; - OPENDHT_PUBLIC static bool DEFAULT_STORE_POLICY(InfoHash, const std::shared_ptr& v, const InfoHash&, const SockAddr&); - static inline bool DEFAULT_EDIT_POLICY(InfoHash, const std::shared_ptr&, std::shared_ptr&, const InfoHash&, const SockAddr&) { + OPENDHT_PUBLIC static bool DEFAULT_STORE_POLICY(InfoHash, + const std::shared_ptr& v, + const InfoHash&, + const SockAddr&); + static inline bool DEFAULT_EDIT_POLICY( + InfoHash, const std::shared_ptr&, std::shared_ptr&, const InfoHash&, const SockAddr&) + { return false; } - ValueType () {} + ValueType() {} - ValueType (Id id, std::string name, duration e = DEFAULT_VALUE_EXPIRATION) - : id(id), name(name), expiration(e) {} + ValueType(Id id, std::string name, duration e = DEFAULT_VALUE_EXPIRATION) + : id(id) + , name(name) + , expiration(e) + {} - ValueType (Id id, std::string name, duration e, StorePolicy sp, EditPolicy ep = DEFAULT_EDIT_POLICY) - : id(id), name(name), expiration(e), storePolicy(sp), editPolicy(ep) {} + ValueType(Id id, std::string name, duration e, StorePolicy sp, EditPolicy ep = DEFAULT_EDIT_POLICY) + : id(id) + , name(name) + , expiration(e) + , storePolicy(sp) + , editPolicy(ep) + {} virtual ~ValueType() {} - bool operator==(const ValueType& o) { - return id == o.id; - } + bool operator==(const ValueType& o) { return id == o.id; } // Generic value type OPENDHT_PUBLIC static const ValueType USER_DATA; - Id id {0}; std::string name {}; duration expiration {DEFAULT_VALUE_EXPIRATION}; @@ -123,15 +124,16 @@ struct ValueType { EditPolicy editPolicy {DEFAULT_EDIT_POLICY}; }; -class TypeStore { +class TypeStore +{ public: - void registerType(const ValueType& type) { - types[type.id] = type; - } - const ValueType& getType(ValueType::Id type_id) const { + void registerType(const ValueType& type) { types[type.id] = type; } + const ValueType& getType(ValueType::Id type_id) const + { const auto& t_it = types.find(type_id); return (t_it == types.end()) ? ValueType::USER_DATA : t_it->second; } + private: std::map types {}; }; @@ -155,43 +157,56 @@ struct OPENDHT_PUBLIC Value SeqNum, /* Value::seq */ UserType, /* Value::user_type */ - COUNT /* the total number of fields */ + COUNT /* the total number of fields */ }; typedef uint64_t Id; static const constexpr Id INVALID_ID {0}; - class Filter : public std::function { + class Filter : public std::function + { public: Filter() {} template - Filter(Functor f) : std::function::function(f) {} + Filter(Functor f) + : std::function::function(f) + {} - inline Filter chain(Filter&& f2) { + inline Filter chain(Filter&& f2) + { auto f1 = *this; return chain(std::move(f1), std::move(f2)); } - inline Filter chainOr(Filter&& f2) { + inline Filter chainOr(Filter&& f2) + { auto f1 = *this; return chainOr(std::move(f1), std::move(f2)); } - static inline Filter chain(Filter&& f1, Filter&& f2) { - if (not f1) return std::move(f2); - if (not f2) return std::move(f1); + static inline Filter chain(Filter&& f1, Filter&& f2) + { + if (not f1) + return std::move(f2); + if (not f2) + return std::move(f1); return [f1 = std::move(f1), f2 = std::move(f2)](const Value& v) { return f1(v) and f2(v); }; } - static inline Filter chain(const Filter& f1, const Filter& f2) { - if (not f1) return f2; - if (not f2) return f1; - return [f1,f2](const Value& v) { + static inline Filter chain(const Filter& f1, const Filter& f2) + { + if (not f1) + return f2; + if (not f2) + return f1; + return [f1, f2](const Value& v) { return f1(v) and f2(v); }; } - static inline Filter chainAll(std::vector&& set) { - if (set.empty()) return {}; + static inline Filter chainAll(std::vector&& set) + { + if (set.empty()) + return {}; return [set = std::move(set)](const Value& v) { for (const auto& f : set) if (f and not f(v)) @@ -199,21 +214,31 @@ struct OPENDHT_PUBLIC Value return true; }; } - static inline Filter chain(std::initializer_list l) { + static inline Filter chain(std::initializer_list l) + { return chainAll(std::vector(l.begin(), l.end())); } - static inline Filter chainOr(Filter&& f1, Filter&& f2) { - if (not f1 or not f2) return {}; - return [f1=std::move(f1),f2=std::move(f2)](const Value& v) { + static inline Filter chainOr(Filter&& f1, Filter&& f2) + { + if (not f1 or not f2) + return {}; + return [f1 = std::move(f1), f2 = std::move(f2)](const Value& v) { return f1(v) or f2(v); }; } - static inline Filter notFilter(Filter&& f) { - if (not f) return [](const Value&) { return false; }; - return [f = std::move(f)](const Value& v) { return not f(v); }; + static inline Filter notFilter(Filter&& f) + { + if (not f) + return [](const Value&) { + return false; + }; + return [f = std::move(f)](const Value& v) { + return not f(v); + }; } - std::vector> filter(const std::vector>& values) { - if (not (*this)) + std::vector> filter(const std::vector>& values) + { + if (not(*this)) return values; std::vector> ret; for (const auto& v : values) @@ -225,50 +250,53 @@ struct OPENDHT_PUBLIC Value /* Sneaky functions disguised in classes */ - static inline Filter AllFilter() { - return {}; - } + static inline Filter AllFilter() { return {}; } - static inline Filter TypeFilter(const ValueType& t) { + static inline Filter TypeFilter(const ValueType& t) + { return [tid = t.id](const Value& v) { return v.type == tid; }; } - static inline Filter TypeFilter(const ValueType::Id& tid) { + static inline Filter TypeFilter(const ValueType::Id& tid) + { return [tid](const Value& v) { return v.type == tid; }; } - static inline Filter IdFilter(const Id id) { + static inline Filter IdFilter(const Id id) + { return [id](const Value& v) { return v.id == id; }; } - static inline Filter RecipientFilter(const InfoHash& r) { + static inline Filter RecipientFilter(const InfoHash& r) + { return [r](const Value& v) { return v.recipient == r; }; } - static inline Filter OwnerFilter(const crypto::PublicKey& pk) { - return OwnerFilter(pk.getId()); - } + static inline Filter OwnerFilter(const crypto::PublicKey& pk) { return OwnerFilter(pk.getId()); } - static inline Filter OwnerFilter(const InfoHash& pkh) { + static inline Filter OwnerFilter(const InfoHash& pkh) + { return [pkh](const Value& v) { return v.owner and v.owner->getId() == pkh; }; } - static inline Filter SeqNumFilter(uint16_t seq_no) { + static inline Filter SeqNumFilter(uint16_t seq_no) + { return [seq_no](const Value& v) { return v.seq == seq_no; }; } - static inline Filter UserTypeFilter(std::string ut) { + static inline Filter UserTypeFilter(std::string ut) + { return [ut = std::move(ut)](const Value& v) { return v.user_type == ut; }; @@ -284,42 +312,36 @@ struct OPENDHT_PUBLIC Value virtual Value packValue() const = 0; }; - template + template class Serializable : public Base { public: using Base::Base; - virtual const ValueType& getType() const { - return Derived::TYPE; - } + virtual const ValueType& getType() const { return Derived::TYPE; } - virtual void unpackValue(const Value& v) { - auto msg = msgpack::unpack((const char*)v.data.data(), v.data.size()); + virtual void unpackValue(const Value& v) + { + auto msg = msgpack::unpack((const char*) v.data.data(), v.data.size()); msg.get().convert(*static_cast(this)); } - virtual Value packValue() const { - return Value {getType(), static_cast(*this)}; - } + virtual Value packValue() const { return Value {getType(), static_cast(*this)}; } }; - template ::value, T>::type* = nullptr> + template::value, T>::type* = nullptr> static Value pack(const T& obj) { return obj.packValue(); } - template ::value, T>::type* = nullptr> + template::value, T>::type* = nullptr> static Value pack(const T& obj) { return {ValueType::USER_DATA.id, packMsg(obj)}; } - template ::value, T>::type* = nullptr> + template::value, T>::type* = nullptr> static T unpack(const Value& v) { T msg; @@ -327,25 +349,20 @@ struct OPENDHT_PUBLIC Value return msg; } - template ::value, T>::type* = nullptr> + template::value, T>::type* = nullptr> static T unpack(const Value& v) { return unpackMsg(v.data); } - template + template T unpack() { return unpack(*this); } - inline bool isEncrypted() const { - return not cypher.empty(); - } - inline bool isSigned() const { - return owner and not signature.empty(); - } + inline bool isEncrypted() const { return not cypher.empty(); } + inline bool isSigned() const { return owner and not signature.empty(); } /** * Sign the value using the provided private key. @@ -358,13 +375,9 @@ struct OPENDHT_PUBLIC Value * Check that the value is signed and that the signature matches. * If true, the owner field will contain the signer public key. */ - inline bool checkSignature() const { - return isSigned() and owner->checkSignature(getToSign(), signature); - } + inline bool checkSignature() const { return isSigned() and owner->checkSignature(getToSign(), signature); } - inline std::shared_ptr getOwner() const { - return owner; - } + inline std::shared_ptr getOwner() const { return owner; } /** * Sign the value with from and returns the encrypted version for to. @@ -373,15 +386,26 @@ struct OPENDHT_PUBLIC Value Value() {} - Value (Id id) : id(id) {} + Value(Id id) + : id(id) + {} /** Generic constructor */ Value(ValueType::Id t, const Blob& data, Id id = INVALID_ID) - : id(id), type(t), data(data) {} + : id(id) + , type(t) + , data(data) + {} Value(ValueType::Id t, Blob&& data, Id id = INVALID_ID) - : id(id), type(t), data(std::move(data)) {} + : id(id) + , type(t) + , data(std::move(data)) + {} Value(ValueType::Id t, const uint8_t* dat_ptr, size_t dat_len, Id id = INVALID_ID) - : id(id), type(t), data(dat_ptr, dat_ptr+dat_len) {} + : id(id) + , type(t) + , data(dat_ptr, dat_ptr + dat_len) + {} #ifdef OPENDHT_JSONCPP /** @@ -391,87 +415,98 @@ struct OPENDHT_PUBLIC Value Value(const Json::Value& json); #endif - template + template Value(ValueType::Id t, const Type& d, Id id = INVALID_ID) - : id(id), type(t), data(packMsg(d)) {} + : id(id) + , type(t) + , data(packMsg(d)) + {} - template + template Value(const ValueType& t, const Type& d, Id id = INVALID_ID) - : id(id), type(t.id), data(packMsg(d)) {} + : id(id) + , type(t.id) + , data(packMsg(d)) + {} /** Custom user data constructor */ - Value(const Blob& userdata) : data(userdata) {} - Value(Blob&& userdata) : data(std::move(userdata)) {} - Value(const uint8_t* dat_ptr, size_t dat_len) : data(dat_ptr, dat_ptr+dat_len) {} + Value(const Blob& userdata) + : data(userdata) + {} + Value(Blob&& userdata) + : data(std::move(userdata)) + {} + Value(const uint8_t* dat_ptr, size_t dat_len) + : data(dat_ptr, dat_ptr + dat_len) + {} Value(Value&& o) noexcept - : id(o.id), owner(std::move(o.owner)), recipient(o.recipient), - type(o.type), data(std::move(o.data)), user_type(std::move(o.user_type)), seq(o.seq) - , signature(std::move(o.signature)), cypher(std::move(o.cypher)) - , priority(o.priority) {} + : id(o.id) + , owner(std::move(o.owner)) + , recipient(o.recipient) + , type(o.type) + , data(std::move(o.data)) + , user_type(std::move(o.user_type)) + , seq(o.seq) + , signature(std::move(o.signature)) + , cypher(std::move(o.cypher)) + , priority(o.priority) + {} - template + template Value(const Type& vs) - : Value(pack(vs)) {} + : Value(pack(vs)) + {} /** * Unpack a serialized value */ - Value(const msgpack::object& o) { - msgpack_unpack(o); - } + Value(const msgpack::object& o) { msgpack_unpack(o); } /** * Returns true if value contents are equals (not considering the value ID) */ - inline bool contentEquals(const Value& o) const { - return isEncrypted() ? cypher == o.cypher : - ((owner == o.owner || (owner and o.owner and *owner == *o.owner)) - && type == o.type - && data == o.data - && user_type == o.user_type - && signature == o.signature); + inline bool contentEquals(const Value& o) const + { + return isEncrypted() ? cypher == o.cypher + : ((owner == o.owner || (owner and o.owner and *owner == *o.owner)) && type == o.type + && data == o.data && user_type == o.user_type && signature == o.signature); } - inline bool operator== (const Value& o) const { - return id == o.id and contentEquals(o); - } - inline bool operator!= (const Value& o) const { - return !(*this == o); - } + inline bool operator==(const Value& o) const { return id == o.id and contentEquals(o); } + inline bool operator!=(const Value& o) const { return !(*this == o); } - inline void setRecipient(const InfoHash& r) { - recipient = r; - } + inline void setRecipient(const InfoHash& r) { recipient = r; } - inline void setCypher(Blob&& c) { - cypher = std::move(c); - } + inline void setCypher(Blob&& c) { cypher = std::move(c); } /** * Pack part of the data to be signed (must always be done the same way) */ - inline Blob getToSign() const { + inline Blob getToSign() const + { msgpack::sbuffer buffer; msgpack::packer pk(&buffer); msgpack_pack_to_sign(pk); - return {buffer.data(), buffer.data()+buffer.size()}; + return {buffer.data(), buffer.data() + buffer.size()}; } /** * Pack part of the data to be encrypted */ - inline Blob getToEncrypt() const { + inline Blob getToEncrypt() const + { msgpack::sbuffer buffer; msgpack::packer pk(&buffer); msgpack_pack_to_encrypt(pk); - return {buffer.data(), buffer.data()+buffer.size()}; + return {buffer.data(), buffer.data() + buffer.size()}; } /** print value for debugging */ - OPENDHT_PUBLIC friend std::ostream& operator<< (std::ostream& s, const Value& v); + OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& s, const Value& v); - inline std::string toString() const { + inline std::string toString() const + { std::ostringstream ss; ss << *this; return ss.str(); @@ -492,88 +527,100 @@ struct OPENDHT_PUBLIC Value /** Return the size in bytes used by this value in memory (minimum). */ size_t size() const; - template + template void msgpack_pack_to_sign(Packer& pk) const { bool has_owner = owner && *owner; - pk.pack_map((user_type.empty()?0:1) + (has_owner?(recipient ? 5 : 4):2)); + pk.pack_map((user_type.empty() ? 0 : 1) + (has_owner ? (recipient ? 5 : 4) : 2)); if (has_owner) { // isSigned - pk.pack(VALUE_KEY_SEQ); pk.pack(seq); - pk.pack(VALUE_KEY_OWNER); owner->msgpack_pack(pk); + pk.pack(VALUE_KEY_SEQ); + pk.pack(seq); + pk.pack(VALUE_KEY_OWNER); + owner->msgpack_pack(pk); if (recipient) { - pk.pack(VALUE_KEY_TO); pk.pack(recipient); + pk.pack(VALUE_KEY_TO); + pk.pack(recipient); } } - pk.pack(VALUE_KEY_TYPE); pk.pack(type); - pk.pack(VALUE_KEY_DATA); pk.pack_bin(data.size()); - pk.pack_bin_body((const char*)data.data(), data.size()); + pk.pack(VALUE_KEY_TYPE); + pk.pack(type); + pk.pack(VALUE_KEY_DATA); + pk.pack_bin(data.size()); + pk.pack_bin_body((const char*) data.data(), data.size()); if (not user_type.empty()) { - pk.pack(VALUE_KEY_USERTYPE); pk.pack(user_type); + pk.pack(VALUE_KEY_USERTYPE); + pk.pack(user_type); } } - template + template void msgpack_pack_to_encrypt(Packer& pk) const { if (isEncrypted()) { pk.pack_bin(cypher.size()); - pk.pack_bin_body((const char*)cypher.data(), cypher.size()); + pk.pack_bin_body((const char*) cypher.data(), cypher.size()); } else { pk.pack_map(isSigned() ? 2 : 1); - pk.pack(VALUE_KEY_BODY); msgpack_pack_to_sign(pk); + pk.pack(VALUE_KEY_BODY); + msgpack_pack_to_sign(pk); if (isSigned()) { - pk.pack(VALUE_KEY_SIGNATURE); pk.pack_bin(signature.size()); - pk.pack_bin_body((const char*)signature.data(), signature.size()); + pk.pack(VALUE_KEY_SIGNATURE); + pk.pack_bin(signature.size()); + pk.pack_bin_body((const char*) signature.data(), signature.size()); } } } - template + template void msgpack_pack(Packer& pk) const { - pk.pack_map(2 + (priority?1:0)); - pk.pack(VALUE_KEY_ID); pk.pack(id); - pk.pack(VALUE_KEY_DAT); msgpack_pack_to_encrypt(pk); + pk.pack_map(2 + (priority ? 1 : 0)); + pk.pack(VALUE_KEY_ID); + pk.pack(id); + pk.pack(VALUE_KEY_DAT); + msgpack_pack_to_encrypt(pk); if (priority) { - pk.pack(VALUE_KEY_PRIO); pk.pack(priority); + pk.pack(VALUE_KEY_PRIO); + pk.pack(priority); } } - template + template void msgpack_pack_fields(const std::set& fields, Packer& pk) const { for (const auto& field : fields) switch (field) { - case Value::Field::Id: - pk.pack(static_cast(id)); - break; - case Value::Field::ValueType: - pk.pack(static_cast(type)); - break; - case Value::Field::OwnerPk: - if (owner) - owner->msgpack_pack(pk); - else - InfoHash().msgpack_pack(pk); - break; - case Value::Field::SeqNum: - pk.pack(static_cast(seq)); - break; - case Value::Field::UserType: - pk.pack(user_type); - break; - default: - break; + case Value::Field::Id: + pk.pack(static_cast(id)); + break; + case Value::Field::ValueType: + pk.pack(static_cast(type)); + break; + case Value::Field::OwnerPk: + if (owner) + owner->msgpack_pack(pk); + else + InfoHash().msgpack_pack(pk); + break; + case Value::Field::SeqNum: + pk.pack(static_cast(seq)); + break; + case Value::Field::UserType: + pk.pack(user_type); + break; + default: + break; } } void msgpack_unpack(const msgpack::object& o); void msgpack_unpack_body(const msgpack::object& o); - Blob getPacked() const { + Blob getPacked() const + { msgpack::sbuffer buffer; msgpack::packer pk(&buffer); pk.pack(*this); - return {buffer.data(), buffer.data()+buffer.size()}; + return {buffer.data(), buffer.data() + buffer.size()}; } void msgpack_unpack_fields(const std::set& fields, const msgpack::object& o, unsigned offset); @@ -625,12 +672,8 @@ struct OPENDHT_PUBLIC Value */ unsigned priority {0}; - inline bool isSignatureChecked() const { - return signatureChecked; - } - inline bool isDecrypted() const { - return decrypted; - } + inline bool isSignatureChecked() const { return signatureChecked; } + inline bool isDecrypted() const { return decrypted; } bool checkSignature(); Sp decrypt(const crypto::PrivateKey& key); @@ -654,9 +697,18 @@ using ValuesExport = std::pair; struct OPENDHT_PUBLIC FieldValue { FieldValue() {} - FieldValue(Value::Field f, uint64_t int_value) : field(f), intValue(int_value) {} - FieldValue(Value::Field f, InfoHash hash_value) : field(f), hashValue(hash_value) {} - FieldValue(Value::Field f, Blob blob_value) : field(f), blobValue(std::move(blob_value)) {} + FieldValue(Value::Field f, uint64_t int_value) + : field(f) + , intValue(int_value) + {} + FieldValue(Value::Field f, InfoHash hash_value) + : field(f) + , hashValue(hash_value) + {} + FieldValue(Value::Field f, Blob blob_value) + : field(f) + , blobValue(std::move(blob_value)) + {} bool operator==(const FieldValue& fd) const; @@ -666,35 +718,38 @@ struct OPENDHT_PUBLIC FieldValue InfoHash getHash() const { return hashValue; } Blob getBlob() const { return blobValue; } - template - void msgpack_pack(Packer& p) const { + template + void msgpack_pack(Packer& p) const + { p.pack_map(2); - p.pack("f"sv); p.pack(static_cast(field)); + p.pack("f"sv); + p.pack(static_cast(field)); p.pack("v"sv); switch (field) { - case Value::Field::Id: - case Value::Field::ValueType: - p.pack(intValue); - break; - case Value::Field::OwnerPk: - p.pack(hashValue); - break; - case Value::Field::UserType: - p.pack_bin(blobValue.size()); - p.pack_bin_body((const char*)blobValue.data(), blobValue.size()); - break; - default: - throw msgpack::type_error(); + case Value::Field::Id: + case Value::Field::ValueType: + p.pack(intValue); + break; + case Value::Field::OwnerPk: + p.pack(hashValue); + break; + case Value::Field::UserType: + p.pack_bin(blobValue.size()); + p.pack_bin_body((const char*) blobValue.data(), blobValue.size()); + break; + default: + throw msgpack::type_error(); } } - void msgpack_unpack(const msgpack::object& msg) { + void msgpack_unpack(const msgpack::object& msg) + { hashValue = {}; blobValue.clear(); if (auto f = findMapValue(msg, "f"sv)) - field = (Value::Field)f->as(); + field = (Value::Field) f->as(); else throw msgpack::type_error(); @@ -703,18 +758,18 @@ struct OPENDHT_PUBLIC FieldValue throw msgpack::type_error(); else switch (field) { - case Value::Field::Id: - case Value::Field::ValueType: - intValue = v->as(); - break; - case Value::Field::OwnerPk: - hashValue = v->as(); - break; - case Value::Field::UserType: - blobValue = unpackBlob(*v); - break; - default: - throw msgpack::type_error(); + case Value::Field::Id: + case Value::Field::ValueType: + intValue = v->as(); + break; + case Value::Field::OwnerPk: + hashValue = v->as(); + break; + case Value::Field::UserType: + blobValue = unpackBlob(*v); + break; + default: + throw msgpack::type_error(); } } @@ -737,7 +792,7 @@ private: */ struct OPENDHT_PUBLIC Select { - Select() { } + Select() {} Select(std::string_view q_str); bool isSatisfiedBy(const Select& os) const; @@ -749,7 +804,8 @@ struct OPENDHT_PUBLIC Select * * @return the resulting Select instance. */ - Select& field(Value::Field field) { + Select& field(Value::Field field) + { if (std::find(fieldSelection_.begin(), fieldSelection_.end(), field) == fieldSelection_.end()) fieldSelection_.emplace_back(field); return *this; @@ -760,17 +816,17 @@ struct OPENDHT_PUBLIC Select * * @return the set of fields. */ - std::set getSelection() const { - return {fieldSelection_.begin(), fieldSelection_.end()}; - } + std::set getSelection() const { return {fieldSelection_.begin(), fieldSelection_.end()}; } - template - void msgpack_pack(Packer& pk) const { pk.pack(fieldSelection_); } - void msgpack_unpack(const msgpack::object& o) { - fieldSelection_ = o.as(); + template + void msgpack_pack(Packer& pk) const + { + pk.pack(fieldSelection_); } + void msgpack_unpack(const msgpack::object& o) { fieldSelection_ = o.as(); } - std::string toString() const { + std::string toString() const + { std::ostringstream ss; ss << *this; return ss.str(); @@ -779,6 +835,7 @@ struct OPENDHT_PUBLIC Select bool empty() const { return fieldSelection_.empty(); } OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& s, const dht::Select& q); + private: std::vector fieldSelection_ {}; }; @@ -792,7 +849,7 @@ private: */ struct OPENDHT_PUBLIC Where { - Where() { } + Where() {} Where(std::string_view q_str); bool isSatisfiedBy(const Where& where) const; @@ -804,7 +861,8 @@ struct OPENDHT_PUBLIC Where * * @return the resulting Where instance. */ - Where&& id(Value::Id id) { + Where&& id(Value::Id id) + { FieldValue fv {Value::Field::Id, id}; if (std::find(filters_.begin(), filters_.end(), fv) == filters_.end()) filters_.emplace_back(std::move(fv)); @@ -818,7 +876,8 @@ struct OPENDHT_PUBLIC Where * * @return the resulting Where instance. */ - Where&& valueType(ValueType::Id type) { + Where&& valueType(ValueType::Id type) + { FieldValue fv {Value::Field::ValueType, type}; if (std::find(filters_.begin(), filters_.end(), fv) == filters_.end()) filters_.emplace_back(std::move(fv)); @@ -832,7 +891,8 @@ struct OPENDHT_PUBLIC Where * * @return the resulting Where instance. */ - Where&& owner(InfoHash owner_pk_hash) { + Where&& owner(InfoHash owner_pk_hash) + { FieldValue fv {Value::Field::OwnerPk, owner_pk_hash}; if (std::find(filters_.begin(), filters_.end(), fv) == filters_.end()) filters_.emplace_back(std::move(fv)); @@ -846,7 +906,8 @@ struct OPENDHT_PUBLIC Where * * @return the resulting Where instance. */ - Where&& seq(uint16_t seq_no) { + Where&& seq(uint16_t seq_no) + { FieldValue fv {Value::Field::SeqNum, seq_no}; if (std::find(filters_.begin(), filters_.end(), fv) == filters_.end()) filters_.emplace_back(std::move(fv)); @@ -860,8 +921,11 @@ struct OPENDHT_PUBLIC Where * * @return the resulting Where instance. */ - Where&& userType(std::string_view user_type) { - FieldValue fv {Value::Field::UserType, Blob {user_type.begin(), user_type.end()}}; + Where&& userType(std::string_view user_type) + { + FieldValue fv { + Value::Field::UserType, Blob {user_type.begin(), user_type.end()} + }; if (std::find(filters_.begin(), filters_.end(), fv) == filters_.end()) filters_.emplace_back(std::move(fv)); return std::move(*this); @@ -872,7 +936,8 @@ struct OPENDHT_PUBLIC Where * * @return the resulting Value::Filter. */ - Value::Filter getFilter() const { + Value::Filter getFilter() const + { if (filters_.empty()) return {}; if (filters_.size() == 1) @@ -886,22 +951,25 @@ struct OPENDHT_PUBLIC Where return Value::Filter::chainAll(std::move(fset)); } - template - void msgpack_pack(Packer& pk) const { pk.pack(filters_); } - void msgpack_unpack(const msgpack::object& o) { + template + void msgpack_pack(Packer& pk) const + { + pk.pack(filters_); + } + void msgpack_unpack(const msgpack::object& o) + { filters_.clear(); filters_ = o.as(); } - std::string toString() const { + std::string toString() const + { std::ostringstream ss; ss << *this; return ss.str(); } - bool empty() const { - return filters_.empty(); - } + bool empty() const { return filters_.empty(); } OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& s, const dht::Where& q); @@ -921,7 +989,10 @@ struct OPENDHT_PUBLIC Query { static const std::string QUERY_PARSE_ERROR; - Query(Select s = {}, Where w = {}, bool none = false) : select(std::move(s)), where(std::move(w)), none(none) { }; + Query(Select s = {}, Where w = {}, bool none = false) + : select(std::move(s)) + , where(std::move(w)) + , none(none) {}; /** * Initializes a query based on a SQL-ish formatted string. The abstract @@ -936,13 +1007,14 @@ struct OPENDHT_PUBLIC Query * - $string$: a simple string WITHOUT SPACES. * - $integer$: a simple integer. */ - Query(std::string_view q_str) { + Query(std::string_view q_str) + { auto pos_W = q_str.find("WHERE"); auto pos_w = q_str.find("where"); auto pos = std::min(pos_W != std::string_view::npos ? pos_W : q_str.size(), pos_w != std::string_view::npos ? pos_w : q_str.size()); select = q_str.substr(0, pos); - where = q_str.substr(pos, q_str.size()-pos); + where = q_str.substr(pos, q_str.size() - pos); } /** @@ -950,22 +1022,27 @@ struct OPENDHT_PUBLIC Query */ bool isSatisfiedBy(const Query& q) const; - template - void msgpack_pack(Packer& pk) const { + template + void msgpack_pack(Packer& pk) const + { pk.pack_map(2); - pk.pack(std::string("s")); pk.pack(select); /* packing field selectors */ - pk.pack(std::string("w")); pk.pack(where); /* packing filters */ + pk.pack(std::string("s")); + pk.pack(select); /* packing field selectors */ + pk.pack(std::string("w")); + pk.pack(where); /* packing filters */ } void msgpack_unpack(const msgpack::object& o); - std::string toString() const { + std::string toString() const + { std::ostringstream ss; ss << *this; return ss.str(); } - friend std::ostream& operator<<(std::ostream& s, const dht::Query& q) { + friend std::ostream& operator<<(std::ostream& s, const dht::Query& q) + { return s << "Query[" << q.select << " " << q.where << "]"; } @@ -981,7 +1058,8 @@ struct OPENDHT_PUBLIC Query * This structures is meant to manipulate a subset of fields normally contained * in Value. */ -struct OPENDHT_PUBLIC FieldValueIndex { +struct OPENDHT_PUBLIC FieldValueIndex +{ FieldValueIndex() {} FieldValueIndex(const Value& v, const Select& s = {}); /** @@ -994,61 +1072,50 @@ struct OPENDHT_PUBLIC FieldValueIndex { OPENDHT_PUBLIC friend std::ostream& operator<<(std::ostream& os, const FieldValueIndex& fvi); - void msgpack_unpack_fields(const std::set& fields, - const msgpack::object& o, - unsigned offset); + void msgpack_unpack_fields(const std::set& fields, const msgpack::object& o, unsigned offset); std::map index {}; }; -template ::value, T>::type* = nullptr> +template::value, T>::type* = nullptr> Value::Filter getFilterSet(Value::Filter f) { - return Value::Filter::chain({ - Value::TypeFilter(T::TYPE), - T::getFilter(), - f - }); + return Value::Filter::chain({Value::TypeFilter(T::TYPE), T::getFilter(), f}); } -template ::value, T>::type* = nullptr> +template::value, T>::type* = nullptr> Value::Filter getFilterSet(Value::Filter f) { return f; } -template ::value, T>::type* = nullptr> +template::value, T>::type* = nullptr> Value::Filter getFilterSet() { - return Value::Filter::chain({ - Value::TypeFilter(T::TYPE), - T::getFilter() - }); + return Value::Filter::chain({Value::TypeFilter(T::TYPE), T::getFilter()}); } -template ::value, T>::type* = nullptr> +template::value, T>::type* = nullptr> Value::Filter getFilterSet() { return {}; } -template +template std::vector -unpackVector(const std::vector>& vals) { +unpackVector(const std::vector>& vals) +{ std::vector ret; ret.reserve(vals.size()); for (const auto& v : vals) { try { ret.emplace_back(Value::unpack(*v)); - } catch (const std::exception&) {} + } catch (const std::exception&) { + } } return ret; } @@ -1057,6 +1124,6 @@ unpackVector(const std::vector>& vals) { uint64_t unpackId(const Json::Value& json, const std::string& key); #endif -} +} // namespace dht MSGPACK_ADD_ENUM(dht::Value::Field) diff --git a/meson.build b/meson.build index 8d1ed563..31262676 100644 --- a/meson.build +++ b/meson.build @@ -3,6 +3,8 @@ project( 'c', 'cpp', 'cython', + license: 'MIT', + license_files: 'LICENSE', version: '3.6.2', meson_version: '>=1.1.0', default_options: ['cpp_std=c++17', 'warning_level=3'], @@ -117,11 +119,7 @@ opendht = library( ) # Install library headers. -install_subdir( - 'include', - install_dir: get_option('includedir'), - strip_directory: true -) +install_subdir('include', install_dir: get_option('includedir'), strip_directory: true) conf_data.set('VERSION', meson.project_version()) conf_data.set('prefix', get_option('prefix')) @@ -152,10 +150,7 @@ if get_option('c').enabled() install: true, ) - install_headers( - 'c/opendht_c.h', - subdir: 'opendht' - ) + install_headers('c/opendht_c.h', subdir: 'opendht') configure_file( input: 'opendht-c.pc.in', diff --git a/python/README.md b/python/README.md index 71f0bf53..bf9745ec 100644 --- a/python/README.md +++ b/python/README.md @@ -86,4 +86,4 @@ For more information, examples and documentation, or to repport issues, visit: h Copyright (c) 2014-2026 Savoir-faire Linux Inc. -OpenDHT 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. +OpenDHT is released under the MIT License. See [LICENSE](LICENSE) for details. diff --git a/python/opendht.pyx b/python/opendht.pyx index 884263c3..48fcc61b 100644 --- a/python/opendht.pyx +++ b/python/opendht.pyx @@ -6,19 +6,7 @@ # cython: language_level=3 # # Copyright (c) 2014-2026 Savoir-faire Linux Inc. -# -# 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 . +# SPDX-License-Identifier: MIT from libcpp.map cimport map as map from libcpp cimport bool diff --git a/python/opendht/aio.py b/python/opendht/aio.py index ea14c456..b5d9ec34 100644 --- a/python/opendht/aio.py +++ b/python/opendht/aio.py @@ -1,17 +1,5 @@ # Copyright (c) 2014-2026 Savoir-faire Linux Inc. -# -# 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 . +# SPDX-License-Identifier: MIT from __future__ import annotations import asyncio diff --git a/python/opendht_cpp.pxd b/python/opendht_cpp.pxd index 6fa1e8de..c2ffd909 100644 --- a/python/opendht_cpp.pxd +++ b/python/opendht_cpp.pxd @@ -1,17 +1,5 @@ # Copyright (c) 2014-2026 Savoir-faire Linux Inc. -# -# 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 . +# SPDX-License-Identifier: MIT from libc.stdint cimport uint8_t, uint16_t, uint32_t, uint64_t from libcpp cimport bool, nullptr_t, nullptr diff --git a/python/setup.py.in b/python/setup.py.in index 03417861..0b5a1bd0 100644 --- a/python/setup.py.in +++ b/python/setup.py.in @@ -1,17 +1,5 @@ # Copyright (c) 2014-2026 Savoir-faire Linux Inc. -# -# 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 . +# SPDX-License-Identifier: MIT from setuptools import setup, Extension, find_packages from setuptools.command.build_ext import build_ext as _build_ext @@ -52,7 +40,7 @@ setup(name="opendht", long_description_content_type="text/markdown", url='https://github.com/savoirfairelinux/opendht', author="Adrien Beraud ", - license="GPL-3.0-or-later", + license="MIT", classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', diff --git a/python/tools/benchmark.py b/python/tools/benchmark.py index 7c896c1f..8b3ddc4d 100755 --- a/python/tools/benchmark.py +++ b/python/tools/benchmark.py @@ -1,19 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2014-2026 Savoir-faire Linux Inc. -# -# 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 . +# SPDX-License-Identifier: MIT import os import sys diff --git a/python/tools/dht/network.py b/python/tools/dht/network.py index 54a480d4..a759b450 100755 --- a/python/tools/dht/network.py +++ b/python/tools/dht/network.py @@ -1,19 +1,5 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright (c) 2015-2026 Savoir-faire Linux Inc. -# -# 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 . +# Copyright (c) 2014-2026 Savoir-faire Linux Inc. +# SPDX-License-Identifier: MIT import os import sys diff --git a/python/tools/dht/virtual_network_builder.py b/python/tools/dht/virtual_network_builder.py index 667287db..55585037 100755 --- a/python/tools/dht/virtual_network_builder.py +++ b/python/tools/dht/virtual_network_builder.py @@ -1,19 +1,5 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -# Copyright (c) 2015-2026 Savoir-faire Linux Inc. -# -# 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 . +# Copyright (c) 2014-2026 Savoir-faire Linux Inc. +# SPDX-License-Identifier: MIT import argparse import os import subprocess diff --git a/python/tools/dhtcluster.py b/python/tools/dhtcluster.py index 3b09e1b8..01d5b9ce 100755 --- a/python/tools/dhtcluster.py +++ b/python/tools/dhtcluster.py @@ -1,20 +1,7 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2014-2026 Savoir-faire Linux Inc. -# Author(s): Adrien Béraud -# -# 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 . +# SPDX-License-Identifier: MIT import os, sys, time, cmd import signal diff --git a/python/tools/http_server.py b/python/tools/http_server.py index 1e7cf2f4..b21c3252 100755 --- a/python/tools/http_server.py +++ b/python/tools/http_server.py @@ -1,18 +1,6 @@ #!/usr/bin/env python3 -# Copyright (c) 2016-2026 Savoir-faire Linux Inc. -# -# 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 . +# Copyright (c) 2014-2026 Savoir-faire Linux Inc. +# SPDX-License-Identifier: MIT from twisted.web import server, resource from twisted.internet import reactor, endpoints diff --git a/python/tools/network_monitor.py b/python/tools/network_monitor.py index 6df4d321..ffc5825e 100755 --- a/python/tools/network_monitor.py +++ b/python/tools/network_monitor.py @@ -1,18 +1,6 @@ #!/usr/bin/env python3 -# Copyright (c) 2015-2026 Savoir-faire Linux Inc. -# -# 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 . +# Copyright (c) 2014-2026 Savoir-faire Linux Inc. +# SPDX-License-Identifier: MIT import time import argparse diff --git a/python/tools/pingpong.py b/python/tools/pingpong.py index 9326ec99..f708d8d6 100755 --- a/python/tools/pingpong.py +++ b/python/tools/pingpong.py @@ -1,18 +1,6 @@ #!/usr/bin/env python3 -# Copyright (c) 2015-2026 Savoir-faire Linux Inc. -# -# 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 . +# Copyright (c) 2014-2026 Savoir-faire Linux Inc. +# SPDX-License-Identifier: MIT import asyncio import time diff --git a/python/tools/scanner.py b/python/tools/scanner.py index 217d5ed8..0f6b9d8a 100755 --- a/python/tools/scanner.py +++ b/python/tools/scanner.py @@ -1,18 +1,6 @@ #!/usr/bin/env python3 # Copyright (c) 2014-2026 Savoir-faire Linux Inc. -# -# 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 . +# SPDX-License-Identifier: MIT import time, sys, os from pprint import pprint diff --git a/resources/LICENSE.txt b/resources/LICENSE.txt new file mode 100644 index 00000000..b8afa8de --- /dev/null +++ b/resources/LICENSE.txt @@ -0,0 +1,7 @@ +Copyright (c) 2014-2026 Savoir-faire Linux Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/rust/examples/dhtnode.rs b/rust/examples/dhtnode.rs index f0620af2..40aa6852 100644 --- a/rust/examples/dhtnode.rs +++ b/rust/examples/dhtnode.rs @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT extern crate opendht; use std::{ thread, time }; diff --git a/rust/src/blob.rs b/rust/src/blob.rs index 9f74f7da..0614a38d 100644 --- a/rust/src/blob.rs +++ b/rust/src/blob.rs @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT use crate::ffi::*; @@ -21,16 +7,12 @@ pub use crate::ffi::Blob; impl Blob { pub fn data(&self) -> DataView { - unsafe { - dht_blob_get_data(self) - } + unsafe { dht_blob_get_data(self) } } } impl Drop for Blob { fn drop(&mut self) { - unsafe { - dht_blob_delete(&mut *self) - } + unsafe { dht_blob_delete(&mut *self) } } -} \ No newline at end of file +} diff --git a/rust/src/crypto.rs b/rust/src/crypto.rs index 26866188..264839bb 100644 --- a/rust/src/crypto.rs +++ b/rust/src/crypto.rs @@ -1,95 +1,72 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #![allow(dead_code)] pub use crate::ffi::*; use std::ffi::CString; +use std::fs::File; use std::io; use std::io::prelude::*; -use std::fs::File; use std::ptr; impl PublicKey { pub fn new(data: &str) -> Box { - unsafe { - Box::from_raw(dht_publickey_import(data.as_ptr(), data.len())) - } + unsafe { Box::from_raw(dht_publickey_import(data.as_ptr(), data.len())) } } pub fn unpack(&mut self, data: Vec) -> i32 { - unsafe { - dht_publickey_unpack(&mut *self, data.as_ptr(), data.len()) - } + unsafe { dht_publickey_unpack(&mut *self, data.as_ptr(), data.len()) } } pub fn pack(&mut self, data: &str) -> i32 { let data = CString::new(data).unwrap(); - unsafe { - dht_publickey_pack(&mut *self, - data.as_ptr(), - data.as_bytes().len()) - } + unsafe { dht_publickey_pack(&mut *self, data.as_ptr(), data.as_bytes().len()) } } pub fn id(&self) -> InfoHash { - unsafe { - dht_publickey_get_id(self) - } + unsafe { dht_publickey_get_id(self) } } pub fn long_id(&self) -> PkId { - unsafe { - dht_publickey_get_long_id(self) - } + unsafe { dht_publickey_get_long_id(self) } } pub fn check_signature(&self, data: &str, signature: &str) -> bool { let data = CString::new(data).unwrap(); let signature = CString::new(signature).unwrap(); unsafe { - dht_publickey_check_signature(self, - data.as_ptr(), data.as_bytes().len(), - signature.as_ptr(), signature.as_bytes().len()) + dht_publickey_check_signature( + self, + data.as_ptr(), + data.as_bytes().len(), + signature.as_ptr(), + signature.as_bytes().len(), + ) } } pub fn encrypt(&self, data: &str) -> Box { let data = CString::new(data).unwrap(); unsafe { - Box::from_raw(dht_publickey_encrypt(self, - data.as_ptr(), data.as_bytes().len())) + Box::from_raw(dht_publickey_encrypt( + self, + data.as_ptr(), + data.as_bytes().len(), + )) } } } impl Drop for PublicKey { fn drop(&mut self) { - unsafe { - dht_publickey_delete(&mut *self) - } + unsafe { dht_publickey_delete(&mut *self) } } } impl PrivateKey { pub fn new(key_length_bits: u32) -> Box { - unsafe { - Box::from_raw(dht_privatekey_generate(key_length_bits)) - } + unsafe { Box::from_raw(dht_privatekey_generate(key_length_bits)) } } pub fn import(file: &str, password: &str) -> io::Result> { @@ -101,24 +78,22 @@ impl PrivateKey { pub fn from_bytes(buffer: &Vec, password: &str) -> Box { unsafe { - Box::from_raw(dht_privatekey_import((&*buffer).as_ptr(), buffer.len(), - password.as_ptr() as *const i8)) + Box::from_raw(dht_privatekey_import( + (&*buffer).as_ptr(), + buffer.len(), + password.as_ptr() as *const i8, + )) } } pub fn public_key(&self) -> Box { - unsafe { - Box::from_raw(dht_privatekey_get_publickey(self)) - } + unsafe { Box::from_raw(dht_privatekey_get_publickey(self)) } } - } impl Drop for PrivateKey { fn drop(&mut self) { - unsafe { - dht_privatekey_delete(&mut *self) - } + unsafe { dht_privatekey_delete(&mut *self) } } } @@ -131,63 +106,45 @@ impl DhtCertificate { } pub fn from_bytes(buffer: &Vec) -> Box { - unsafe { - Box::from_raw(dht_certificate_import((&*buffer).as_ptr(), buffer.len())) - } + unsafe { Box::from_raw(dht_certificate_import((&*buffer).as_ptr(), buffer.len())) } } pub fn from_slice(buffer: &str) -> Box { - unsafe { - Box::from_raw(dht_certificate_import((&*buffer).as_ptr(), buffer.len())) - } + unsafe { Box::from_raw(dht_certificate_import((&*buffer).as_ptr(), buffer.len())) } } pub fn id(&self) -> InfoHash { - unsafe { - dht_certificate_get_id(&*self) - } + unsafe { dht_certificate_get_id(&*self) } } pub fn long_id(&self) -> PkId { - unsafe { - dht_certificate_get_long_id(&*self) - } + unsafe { dht_certificate_get_long_id(&*self) } } pub fn publickey(&self) -> Box { - unsafe { - Box::from_raw(dht_certificate_get_publickey(&*self)) - } + unsafe { Box::from_raw(dht_certificate_get_publickey(&*self)) } } } impl Drop for DhtCertificate { fn drop(&mut self) { - unsafe { - dht_certificate_delete(&mut *self) - } + unsafe { dht_certificate_delete(&mut *self) } } } impl DhtIdentity { pub fn new(common_name: &str) -> DhtIdentity { - unsafe { - DhtIdentity::generate(common_name, Box::from_raw(ptr::null_mut())) - } + unsafe { DhtIdentity::generate(common_name, Box::from_raw(ptr::null_mut())) } } pub fn generate(common_name: &str, ca: Box) -> DhtIdentity { let common_name = CString::new(common_name).unwrap(); - unsafe { - dht_identity_generate(common_name.as_ptr(), &*ca) - } + unsafe { dht_identity_generate(common_name.as_ptr(), &*ca) } } } impl Drop for DhtIdentity { fn drop(&mut self) { - unsafe { - dht_identity_delete(&mut *self) - } + unsafe { dht_identity_delete(&mut *self) } } -} \ No newline at end of file +} diff --git a/rust/src/dhtrunner.rs b/rust/src/dhtrunner.rs index 6e659597..443c501f 100644 --- a/rust/src/dhtrunner.rs +++ b/rust/src/dhtrunner.rs @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #![allow(dead_code)] @@ -22,11 +8,10 @@ use std::ffi::CString; use std::ptr; pub use crate::ffi::*; -use std::net::SocketAddr; use os_socketaddr::OsSocketAddr; +use std::net::SocketAddr; impl DhtRunnerConfig { - pub fn new() -> Box { let mut config: Box = Box::new(DhtRunnerConfig { dht_config: DhtSecureConfig { @@ -92,25 +77,21 @@ impl DhtRunnerConfig { self.dht_config.id.privatekey = Box::into_raw(privatekey); self.dht_config.id.certificate = Box::into_raw(certificate); } - } -impl DhtNodeConfig -{ +impl DhtNodeConfig { pub fn set_persist_path(&mut self, persist_path: &str) { self.persist_path = CString::new(persist_path).unwrap().into_raw(); } } -struct GetHandler<'a> -{ - get_cb: &'a mut(dyn FnMut(Box) -> bool), - done_cb: &'a mut(dyn FnMut(bool)) +struct GetHandler<'a> { + get_cb: &'a mut (dyn FnMut(Box) -> bool), + done_cb: &'a mut (dyn FnMut(bool)), } -impl<'a> GetHandler<'a> -{ - fn get_cb(&mut self, v: Box) -> bool{ +impl<'a> GetHandler<'a> { + fn get_cb(&mut self, v: Box) -> bool { (self.get_cb)(v) } @@ -119,7 +100,7 @@ impl<'a> GetHandler<'a> } } -extern fn get_handler_cb(v: *mut Value, ptr: *mut c_void) -> bool { +extern "C" fn get_handler_cb(v: *mut Value, ptr: *mut c_void) -> bool { if ptr.is_null() { return true; } @@ -129,52 +110,48 @@ extern fn get_handler_cb(v: *mut Value, ptr: *mut c_void) -> bool { } } -extern fn done_handler_cb(ok: bool, ptr: *mut c_void) { +extern "C" fn done_handler_cb(ok: bool, ptr: *mut c_void) { unsafe { let handler = Box::from_raw(ptr as *mut GetHandler); (*handler.done_cb)(ok) } } -struct PutHandler<'a> -{ - done_cb: &'a mut(dyn FnMut(bool)) +struct PutHandler<'a> { + done_cb: &'a mut (dyn FnMut(bool)), } -impl<'a> PutHandler<'a> -{ +impl<'a> PutHandler<'a> { fn done_cb(&mut self, ok: bool) { (self.done_cb)(ok) } } -extern fn put_handler_done(ok: bool, ptr: *mut c_void) { +extern "C" fn put_handler_done(ok: bool, ptr: *mut c_void) { unsafe { let handler = Box::from_raw(ptr as *mut PutHandler); (*handler.done_cb)(ok) } } -struct ListenHandler<'a> -{ - cb: &'a mut(dyn FnMut(Box, bool) -> bool) +struct ListenHandler<'a> { + cb: &'a mut (dyn FnMut(Box, bool) -> bool), } -impl<'a> ListenHandler<'a> -{ +impl<'a> ListenHandler<'a> { fn cb(&mut self, v: Box, expired: bool) -> bool { (self.cb)(v, expired) } } -extern fn listen_handler(v: *mut Value, expired: bool, ptr: *mut c_void) -> bool { +extern "C" fn listen_handler(v: *mut Value, expired: bool, ptr: *mut c_void) -> bool { unsafe { let handler = ptr as *mut ListenHandler; (*handler).cb((*v).boxed(), expired) } } -extern fn listen_handler_done(ptr: *mut c_void) { +extern "C" fn listen_handler_done(ptr: *mut c_void) { unsafe { Box::from_raw(ptr as *mut ListenHandler); } @@ -182,83 +159,79 @@ extern fn listen_handler_done(ptr: *mut c_void) { impl DhtRunner { pub fn new() -> Box { - unsafe { - Box::from_raw(dht_runner_new()) - } + unsafe { Box::from_raw(dht_runner_new()) } } pub fn run(&mut self, port: u16) { - unsafe { - dht_runner_run(&mut *self, port) - } + unsafe { dht_runner_run(&mut *self, port) } } pub fn run_config(&mut self, port: u16, config: Box) { - unsafe { - dht_runner_run_config(&mut *self, port, &*config) - } + unsafe { dht_runner_run_config(&mut *self, port, &*config) } } pub fn bootstrap(&mut self, host: &str, service: u16) { unsafe { - dht_runner_bootstrap(&mut *self, + dht_runner_bootstrap( + &mut *self, CString::new(host).unwrap().into_raw(), - CString::new(service.to_string()).unwrap().into_raw()) + CString::new(service.to_string()).unwrap().into_raw(), + ) } } pub fn node_id(&self) -> InfoHash { - unsafe { - dht_runner_get_node_id(&*self) - } + unsafe { dht_runner_get_node_id(&*self) } } pub fn id(&self) -> InfoHash { - unsafe { - dht_runner_get_id(&*self) - } + unsafe { dht_runner_get_id(&*self) } } - pub fn get<'a>(&mut self, h: &InfoHash, - get_cb: &'a mut(dyn FnMut(Box) -> bool), - done_cb: &'a mut(dyn FnMut(bool))) { - let handler = Box::new(GetHandler { - get_cb, - done_cb, - }); + pub fn get<'a>( + &mut self, + h: &InfoHash, + get_cb: &'a mut (dyn FnMut(Box) -> bool), + done_cb: &'a mut (dyn FnMut(bool)), + ) { + let handler = Box::new(GetHandler { get_cb, done_cb }); let handler = Box::into_raw(handler) as *mut c_void; - unsafe { - dht_runner_get(&mut *self, h, get_handler_cb, done_handler_cb, handler) - } + unsafe { dht_runner_get(&mut *self, h, get_handler_cb, done_handler_cb, handler) } } - pub fn put<'a>(&mut self, h: &InfoHash, v: Box, - done_cb: &'a mut(dyn FnMut(bool)), permanent: bool) { - let handler = Box::new(PutHandler { - done_cb, - }); + pub fn put<'a>( + &mut self, + h: &InfoHash, + v: Box, + done_cb: &'a mut (dyn FnMut(bool)), + permanent: bool, + ) { + let handler = Box::new(PutHandler { done_cb }); let handler = Box::into_raw(handler) as *mut c_void; - unsafe { - dht_runner_put(&mut *self, h, &*v, put_handler_done, handler, permanent) - } + unsafe { dht_runner_put(&mut *self, h, &*v, put_handler_done, handler, permanent) } } - pub fn put_signed<'a>(&mut self, h: &InfoHash, v: Box, - done_cb: &'a mut(dyn FnMut(bool)), permanent: bool) { - let handler = Box::new(PutHandler { - done_cb, - }); + pub fn put_signed<'a>( + &mut self, + h: &InfoHash, + v: Box, + done_cb: &'a mut (dyn FnMut(bool)), + permanent: bool, + ) { + let handler = Box::new(PutHandler { done_cb }); let handler = Box::into_raw(handler) as *mut c_void; - unsafe { - dht_runner_put_signed(&mut *self, h, &*v, put_handler_done, handler, permanent) - } + unsafe { dht_runner_put_signed(&mut *self, h, &*v, put_handler_done, handler, permanent) } } - pub fn put_encrypted<'a>(&mut self, h: &InfoHash, to: &InfoHash, v: Box, - done_cb: &'a mut(dyn FnMut(bool)), permanent: bool) { - let handler = Box::new(PutHandler { - done_cb, - }); + pub fn put_encrypted<'a>( + &mut self, + h: &InfoHash, + to: &InfoHash, + v: Box, + done_cb: &'a mut (dyn FnMut(bool)), + permanent: bool, + ) { + let handler = Box::new(PutHandler { done_cb }); let handler = Box::into_raw(handler) as *mut c_void; unsafe { dht_runner_put_encrypted(&mut *self, h, to, &*v, put_handler_done, handler, permanent) @@ -266,35 +239,37 @@ impl DhtRunner { } pub fn cancel_put<'a>(&mut self, h: &InfoHash, vid: u64) { - unsafe { - dht_runner_cancel_put(&mut *self, h, vid) - } + unsafe { dht_runner_cancel_put(&mut *self, h, vid) } } - pub fn listen<'a>(&mut self, h: &InfoHash, - cb: &'a mut(dyn FnMut(Box, bool) -> bool)) -> Box { - let handler = Box::new(ListenHandler { - cb, - }); + pub fn listen<'a>( + &mut self, + h: &InfoHash, + cb: &'a mut (dyn FnMut(Box, bool) -> bool), + ) -> Box { + let handler = Box::new(ListenHandler { cb }); let handler = Box::into_raw(handler) as *mut c_void; unsafe { - Box::from_raw(dht_runner_listen(&mut *self, h, listen_handler, listen_handler_done, handler)) + Box::from_raw(dht_runner_listen( + &mut *self, + h, + listen_handler, + listen_handler_done, + handler, + )) } } pub fn cancel_listen(&mut self, h: &InfoHash, token: Box) { - unsafe { - dht_runner_cancel_listen(&mut *self, h, &*token) - } + unsafe { dht_runner_cancel_listen(&mut *self, h, &*token) } } - pub fn shutdown(&mut self, - done_cb: extern fn(bool, *mut c_void), - cb_user_data: *mut c_void) - { - unsafe { - dht_runner_shutdown(&mut *self, done_cb, cb_user_data) - } + pub fn shutdown( + &mut self, + done_cb: extern "C" fn(bool, *mut c_void), + cb_user_data: *mut c_void, + ) { + unsafe { dht_runner_shutdown(&mut *self, done_cb, cb_user_data) } } pub fn public_addresses(&self) -> Vec { @@ -306,7 +281,8 @@ impl DhtRunner { if sock.is_some() { result.push(sock.unwrap()); } - addresses = (addresses as usize + std::mem::size_of::<*mut OsSocketAddr>()) as *mut *mut OsSocketAddr; + addresses = (addresses as usize + std::mem::size_of::<*mut OsSocketAddr>()) + as *mut *mut OsSocketAddr; } } result @@ -315,16 +291,12 @@ impl DhtRunner { impl Drop for DhtRunner { fn drop(&mut self) { - unsafe { - dht_runner_delete(&mut *self) - } + unsafe { dht_runner_delete(&mut *self) } } } impl Drop for OpToken { fn drop(&mut self) { - unsafe { - dht_op_token_delete(&mut *self) - } + unsafe { dht_op_token_delete(&mut *self) } } -} \ No newline at end of file +} diff --git a/rust/src/ffi.rs b/rust/src/ffi.rs index 4bfc489b..4e4b50e8 100644 --- a/rust/src/ffi.rs +++ b/rust/src/ffi.rs @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #![allow(dead_code)] diff --git a/rust/src/infohash.rs b/rust/src/infohash.rs index 02fb292c..3968f24c 100644 --- a/rust/src/infohash.rs +++ b/rust/src/infohash.rs @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT use crate::ffi::*; use std::ffi::CStr; @@ -24,9 +10,7 @@ pub use crate::ffi::InfoHash; impl InfoHash { pub fn new() -> InfoHash { - InfoHash { - d: [0; 20] - } + InfoHash { d: [0; 20] } } pub fn random() -> InfoHash { @@ -64,19 +48,17 @@ impl InfoHash { } pub fn is_zero(&self) -> bool { - unsafe { - dht_infohash_is_zero(self) - } + unsafe { dht_infohash_is_zero(self) } } } impl fmt::Display for InfoHash { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { unsafe { - let self_str = CStr::from_ptr( - dht_infohash_print(self) - ).to_str().unwrap_or(""); + let self_str = CStr::from_ptr(dht_infohash_print(self)) + .to_str() + .unwrap_or(""); write!(f, "{}", self_str) } } -} \ No newline at end of file +} diff --git a/rust/src/lib.rs b/rust/src/lib.rs index dd6160a1..eef4abd6 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT extern crate libc; extern crate os_socketaddr; diff --git a/rust/src/pkid.rs b/rust/src/pkid.rs index db8ac6a5..a662b93f 100644 --- a/rust/src/pkid.rs +++ b/rust/src/pkid.rs @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT use crate::ffi::*; use std::ffi::CStr; diff --git a/rust/src/value.rs b/rust/src/value.rs index 40e0a932..9b4a0da1 100644 --- a/rust/src/value.rs +++ b/rust/src/value.rs @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #![allow(dead_code)] use crate::ffi::*; diff --git a/src/base64.cpp b/src/base64.cpp index 9134566e..713fd26b 100644 --- a/src/base64.cpp +++ b/src/base64.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "base64.h" #include "utils.h" diff --git a/src/base64.h b/src/base64.h index 536875ba..6527a59b 100644 --- a/src/base64.h +++ b/src/base64.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include diff --git a/src/callbacks.cpp b/src/callbacks.cpp index b7d5b7b5..e18406ea 100644 --- a/src/callbacks.cpp +++ b/src/callbacks.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" @@ -23,11 +9,11 @@ namespace dht { - GetCallbackSimple bindGetCb(GetCallbackRaw raw_cb, void* user_data) { - if (not raw_cb) return {}; + if (not raw_cb) + return {}; return [=](const std::shared_ptr& value) { return raw_cb(value, user_data); }; @@ -36,8 +22,9 @@ bindGetCb(GetCallbackRaw raw_cb, void* user_data) GetCallback bindGetCb(GetCallbackSimple cb) { - if (not cb) return {}; - return [cb=std::move(cb)](const std::vector>& values) { + if (not cb) + return {}; + return [cb = std::move(cb)](const std::vector>& values) { for (const auto& v : values) if (not cb(v)) return false; @@ -48,7 +35,8 @@ bindGetCb(GetCallbackSimple cb) ValueCallback bindValueCb(ValueCallbackRaw raw_cb, void* user_data) { - if (not raw_cb) return {}; + if (not raw_cb) + return {}; return [=](const std::vector>& values, bool expired) { for (const auto& v : values) if (not raw_cb(v, expired, user_data)) @@ -60,13 +48,16 @@ bindValueCb(ValueCallbackRaw raw_cb, void* user_data) ShutdownCallback bindShutdownCb(ShutdownCallbackRaw shutdown_cb_raw, void* user_data) { - return [=]() { shutdown_cb_raw(user_data); }; + return [=]() { + shutdown_cb_raw(user_data); + }; } DoneCallback bindDoneCb(DoneCallbackSimple donecb) { - if (not donecb) return {}; + if (not donecb) + return {}; using namespace std::placeholders; return std::bind(std::move(donecb), _1); } @@ -74,15 +65,18 @@ bindDoneCb(DoneCallbackSimple donecb) DoneCallback bindDoneCb(DoneCallbackRaw raw_cb, void* user_data) { - if (not raw_cb) return {}; + if (not raw_cb) + return {}; return [=](bool success, const std::vector>& nodes) { - raw_cb(success, (std::vector>*)&nodes, user_data); + raw_cb(success, (std::vector>*) &nodes, user_data); }; } DoneCallbackSimple -bindDoneCbSimple(DoneCallbackSimpleRaw raw_cb, void* user_data) { - if (not raw_cb) return {}; +bindDoneCbSimple(DoneCallbackSimpleRaw raw_cb, void* user_data) +{ + if (not raw_cb) + return {}; return [=](bool success) { raw_cb(success, user_data); }; @@ -92,7 +86,8 @@ std::string NodeStats::toString() const { std::ostringstream ss; - ss << "Known nodes: " << good_nodes << " good, " << dubious_nodes << " dubious, " << incoming_nodes << " incoming." << std::endl; + ss << "Known nodes: " << good_nodes << " good, " << dubious_nodes << " dubious, " << incoming_nodes << " incoming." + << std::endl; ss << searches << " searches, " << node_cache_size << " total cached nodes" << std::endl; if (table_depth > 1) { ss << "Routing table depth: " << table_depth << std::endl; @@ -159,5 +154,4 @@ NodeInfo::NodeInfo(const Json::Value& v) #endif - -} +} // namespace dht diff --git a/src/compat/msvc/unistd.h b/src/compat/msvc/unistd.h index 3214f413..067681ca 100644 --- a/src/compat/msvc/unistd.h +++ b/src/compat/msvc/unistd.h @@ -1,21 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #ifndef __STRICT_ANSI__ @@ -26,9 +10,9 @@ #include #include -#define R_OK 4 -#define W_OK 2 -#define F_OK 0 +#define R_OK 4 +#define W_OK 2 +#define F_OK 0 #ifndef STDIN_FILENO #define STDIN_FILENO 0 @@ -43,7 +27,7 @@ #endif #define srandom srand -#define random rand +#define random rand #define inline __inline typedef int mode_t; diff --git a/src/compat/os_cert.cpp b/src/compat/os_cert.cpp index e633dd5e..8793b044 100644 --- a/src/compat/os_cert.cpp +++ b/src/compat/os_cert.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "os_cert.h" #include "logger.h" @@ -34,7 +20,7 @@ namespace dht { namespace http { PEMCache::PEMCache(const std::shared_ptr& l) - : logger(l) + : logger(l) { #ifdef _WIN32 PCCERT_CONTEXT pContext = NULL; @@ -59,8 +45,7 @@ PEMCache::PEMCache(const std::shared_ptr& l) if ((osStatus = SecTrustCopyAnchorCertificates(&result)) != 0) { if (logger) { CFStringRef statusString = SecCopyErrorMessageString(osStatus, NULL); - logger->d("Error enumerating certificates: %s", - CFStringGetCStringPtr(statusString, kCFStringEncodingASCII)); + logger->d("Error enumerating certificates: %s", CFStringGetCStringPtr(statusString, kCFStringEncodingASCII)); CFRelease(statusString); } if (result != NULL) { diff --git a/src/compat/os_cert.h b/src/compat/os_cert.h index 0f120591..4b48b9ba 100644 --- a/src/compat/os_cert.h +++ b/src/compat/os_cert.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "logger.h" @@ -33,7 +18,7 @@ class PEMCache { PEMCache(const std::shared_ptr& l); - using X509Ptr = std::unique_ptr; + using X509Ptr = std::unique_ptr; std::vector pems_; std::shared_ptr logger; @@ -46,5 +31,5 @@ public: void fillX509Store(SSL_CTX* ctx); }; -} +} // namespace http } // namespace dht diff --git a/src/crypto.cpp b/src/crypto.cpp index c7ffdfb8..ffec6742 100644 --- a/src/crypto.cpp +++ b/src/crypto.cpp @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * Vsevolod Ivanov - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "crypto.h" #include "rng.h" diff --git a/src/default_types.cpp b/src/default_types.cpp index 0a0c91b3..fbb6e5e5 100644 --- a/src/default_types.cpp +++ b/src/default_types.cpp @@ -1,25 +1,12 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "default_types.h" namespace dht { -std::ostream& operator<< (std::ostream& s, const DhtMessage& v) +std::ostream& +operator<<(std::ostream& s, const DhtMessage& v) { s << "DhtMessage: service " << v.service << std::endl; return s; @@ -32,26 +19,25 @@ DhtMessage::storePolicy(InfoHash h, std::shared_ptr& v, const InfoHash& f auto msg = unpackMsg(v->data); if (msg.service.empty()) return false; - } catch (const std::exception& e) {} + } catch (const std::exception& e) { + } return ValueType::DEFAULT_STORE_POLICY(h, v, f, sa); } Value::Filter DhtMessage::ServiceFilter(const std::string& s) { - return Value::Filter::chain( - Value::TypeFilter(TYPE), - [s](const Value& v) { - try { - return unpackMsg(v.data).service == s; - } catch (const std::exception& e) { - return false; - } + return Value::Filter::chain(Value::TypeFilter(TYPE), [s](const Value& v) { + try { + return unpackMsg(v.data).service == s; + } catch (const std::exception& e) { + return false; } - ); + }); } -std::ostream& operator<< (std::ostream& s, const IpServiceAnnouncement& v) +std::ostream& +operator<<(std::ostream& s, const IpServiceAnnouncement& v) { if (v.addr) { s << "Peer: "; @@ -76,30 +62,24 @@ IpServiceAnnouncement::storePolicy(InfoHash h, std::shared_ptr& v, const // argument v is modified (not the value). v = std::make_shared(IpServiceAnnouncement::TYPE, sa_addr, v->id); return ValueType::DEFAULT_STORE_POLICY(h, v, f, sa); - } catch (const std::exception& e) {} + } catch (const std::exception& e) { + } return false; } const ValueType DhtMessage::TYPE(1, "DHT message", std::chrono::minutes(5), DhtMessage::storePolicy); -const ValueType IpServiceAnnouncement::TYPE(2, "Internet Service Announcement", std::chrono::minutes(15), IpServiceAnnouncement::storePolicy); +const ValueType IpServiceAnnouncement::TYPE(2, + "Internet Service Announcement", + std::chrono::minutes(15), + IpServiceAnnouncement::storePolicy); const ValueType ImMessage::TYPE = {3, "IM message", std::chrono::minutes(5)}; -const ValueType TrustRequest::TYPE = {4, "Certificate trust request", std::chrono::hours(24*7)}; +const ValueType TrustRequest::TYPE = {4, "Certificate trust request", std::chrono::hours(24 * 7)}; const ValueType IceCandidates::TYPE = {5, "ICE candidates", std::chrono::minutes(1)}; -const std::array, 5> -DEFAULT_TYPES -{{ - ValueType::USER_DATA, - DhtMessage::TYPE, - ImMessage::TYPE, - IceCandidates::TYPE, - TrustRequest::TYPE -}}; +const std::array, 5> DEFAULT_TYPES { + {ValueType::USER_DATA, DhtMessage::TYPE, ImMessage::TYPE, IceCandidates::TYPE, TrustRequest::TYPE} +}; -const std::array, 1> -DEFAULT_INSECURE_TYPES -{{ - IpServiceAnnouncement::TYPE -}}; +const std::array, 1> DEFAULT_INSECURE_TYPES {{IpServiceAnnouncement::TYPE}}; -} +} // namespace dht diff --git a/src/dht.cpp b/src/dht.cpp index 3e72c22d..5988930e 100644 --- a/src/dht.cpp +++ b/src/dht.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "dht.h" #include "rng.h" @@ -91,7 +77,8 @@ Dht::shutdown(ShutdownCallback cb, bool stop) r.second.done_cb(false, {}); sr.second->callbacks.clear(); for (const auto& a : sr.second->announce) { - for (auto& cb : a.callbacks) cb(false, {}); + for (auto& cb : a.callbacks) + cb(false, {}); } sr.second->announce.clear(); sr.second->listeners.clear(); @@ -101,7 +88,8 @@ Dht::shutdown(ShutdownCallback cb, bool stop) } if (not maintain_storage) { - if (cb) cb(); + if (cb) + cb(); return; } @@ -112,7 +100,9 @@ Dht::shutdown(ShutdownCallback cb, bool stop) --*remaining; if (logger_) logger_->w("Shutting down node: %u ops remaining", *remaining); - if (!*remaining && cb) { cb(); } + if (!*remaining && cb) { + cb(); + } }; for (auto& str : store) @@ -122,12 +112,16 @@ Dht::shutdown(ShutdownCallback cb, bool stop) logger_->w("Shutting down node: after storage, %u ops", *remaining); if (!*remaining) { - if (cb) cb(); + if (cb) + cb(); } } bool -Dht::isRunning(sa_family_t af) const { return network_engine.isRunning(af); } +Dht::isRunning(sa_family_t af) const +{ + return network_engine.isRunning(af); +} /* Every bucket contains an unordered list of nodes. */ const Sp @@ -135,7 +129,8 @@ Dht::findNode(const InfoHash& id, sa_family_t af) const { if (const Bucket* b = findBucket(id, af)) for (const auto& n : b->nodes) - if (n->id == id) return n; + if (n->id == id) + return n; return {}; } @@ -164,7 +159,7 @@ Dht::getPublicAddress(sa_family_t family) return ret; } auto& reported_addr = dht(family).reported_addr; - ret.reserve(!family ? reported_addr.size() : reported_addr.size()/2); + ret.reserve(!family ? reported_addr.size() : reported_addr.size() / 2); for (const auto& addr : reported_addr) if (!family || family == addr.second.getFamily()) ret.emplace_back(addr.second); @@ -175,7 +170,8 @@ bool Dht::trySearchInsert(const Sp& node) { const auto& now = scheduler.time(); - if (not node) return false; + if (not node) + return false; auto& srs = searches(node->getFamily()); auto closest = srs.lower_bound(node->id); @@ -208,7 +204,7 @@ Dht::reportedAddr(const SockAddr& addr) { auto& reported_addr = dht(addr.getFamily()).reported_addr; auto firstBefore = reported_addr.empty() ? nullptr : reported_addr.begin()->second.get(); - auto it = std::find_if(reported_addr.begin(), reported_addr.end(), [&](const ReportedAddr& a){ + auto it = std::find_if(reported_addr.begin(), reported_addr.end(), [&](const ReportedAddr& a) { return a.second == addr; }); if (it == reported_addr.end()) { @@ -281,17 +277,16 @@ Dht::expireSearches() logger_->d(srp.first, "[search %s] Removing search", srp.first.toString().c_str()); sr.clear(); return b; - } else { return false; } + } else { + return false; + } }; erase_if(dht4.searches, expired); erase_if(dht6.searches, expired); } void -Dht::searchNodeGetDone(const net::Request& req, - net::RequestAnswer&& answer, - std::weak_ptr ws, - Sp query) +Dht::searchNodeGetDone(const net::Request& req, net::RequestAnswer&& answer, std::weak_ptr ws, Sp query) { const auto& now = scheduler.time(); if (auto sr = ws.lock()) { @@ -318,10 +313,7 @@ Dht::searchNodeGetDone(const net::Request& req, } void -Dht::searchNodeGetExpired(const net::Request& status, - bool over, - std::weak_ptr ws, - Sp query) +Dht::searchNodeGetExpired(const net::Request& status, bool over, std::weak_ptr ws, Sp query) { if (auto sr = ws.lock()) { if (auto srn = sr->getNode(status.node)) { @@ -333,19 +325,23 @@ Dht::searchNodeGetExpired(const net::Request& status, } } -void Dht::paginate(std::weak_ptr ws, Sp query, SearchNode* n) { +void +Dht::paginate(std::weak_ptr ws, Sp query, SearchNode* n) +{ auto sr = ws.lock(); - if (not sr) return; + if (not sr) + return; auto select_q = std::make_shared(Select {}.field(Value::Field::Id), query ? query->where : Where {}); - auto onSelectDone = [this,ws,query](const net::Request& status, - net::RequestAnswer&& answer) mutable { + auto onSelectDone = [this, ws, query](const net::Request& status, net::RequestAnswer&& answer) mutable { // Retrieve search auto sr = ws.lock(); - if (not sr) return; + if (not sr) + return; const auto& id = sr->id; // Retrieve search node auto sn = sr->getNode(status.node); - if (not sn) return; + if (not sn) + return; // backward compatibility if (answer.fields.empty()) { searchNodeGetDone(status, std::move(answer), ws, query); @@ -354,24 +350,32 @@ void Dht::paginate(std::weak_ptr ws, Sp query, SearchNode* n) { for (const auto& fvi : answer.fields) { try { auto vid = fvi->index.at(Value::Field::Id).getInt(); - if (vid == Value::INVALID_ID) continue; + if (vid == Value::INVALID_ID) + continue; auto query_for_vid = std::make_shared(Select {}, Where {}.id(vid)); sn->pagination_queries[query].push_back(query_for_vid); if (logger_) - logger_->d(id, sn->node->id, "[search %s] [node %s] Sending %s", - id.toString().c_str(), sn->node->toString().c_str(), query_for_vid->toString().c_str()); - sn->getStatus[query_for_vid] = network_engine.sendGetValues(status.node, - id, - *query_for_vid, - -1, - std::bind(&Dht::searchNodeGetDone, this, _1, _2, ws, query), - std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, query_for_vid) - ); + logger_->d(id, + sn->node->id, + "[search %s] [node %s] Sending %s", + id.toString().c_str(), + sn->node->toString().c_str(), + query_for_vid->toString().c_str()); + sn->getStatus[query_for_vid] = network_engine.sendGetValues( + status.node, + id, + *query_for_vid, + -1, + std::bind(&Dht::searchNodeGetDone, this, _1, _2, ws, query), + std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, query_for_vid)); } catch (const std::out_of_range&) { if (logger_) - logger_->e(id, sn->node->id, "[search %s] [node %s] Received non-id field in response to "\ - "'SELECT id' request…", - id.toString().c_str(), sn->node->toString().c_str()); + logger_->e(id, + sn->node->id, + "[search %s] [node %s] Received non-id field in response to " + "'SELECT id' request…", + id.toString().c_str(), + sn->node->toString().c_str()); } } }; @@ -379,15 +383,14 @@ void Dht::paginate(std::weak_ptr ws, Sp query, SearchNode* n) { n->pagination_queries[query].push_back(select_q); if (logger_) - logger_->d(sr->id, n->node->id, "[search %s] [node %s] Sending %s", - sr->id.toString().c_str(), n->node->toString().c_str(), select_q->toString().c_str()); - n->getStatus[select_q] = network_engine.sendGetValues(n->node, - sr->id, - *select_q, - -1, - onSelectDone, - std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, select_q) - ); + logger_->d(sr->id, + n->node->id, + "[search %s] [node %s] Sending %s", + sr->id.toString().c_str(), + n->node->toString().c_str(), + select_q->toString().c_str()); + n->getStatus[select_q] = network_engine.sendGetValues( + n->node, sr->id, *select_q, -1, onSelectDone, std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, select_q)); } Dht::SearchNode* @@ -404,9 +407,7 @@ Dht::searchSendGetValues(Sp sr, SearchNode* pn, bool update) do { /* for all requests to send */ SearchNode* n = nullptr; auto& query = sr->callbacks.empty() ? ANY_QUERY : cb->second.query; - const time_point up = (not sr->callbacks.empty() and update) - ? sr->getLastGetTime(*query) - : time_point::min(); + const time_point up = (not sr->callbacks.empty() and update) ? sr->getLastGetTime(*query) : time_point::min(); if (pn and pn->canGet(now, up, query)) { n = pn; @@ -426,11 +427,12 @@ Dht::searchSendGetValues(Sp sr, SearchNode* pn, bool update) /* if (logger_) logger_->d(sr->id, n->node->id, "[search %s] [node %s] Sending 'find_node'", sr->id.toString().c_str(), n->node->toString().c_str());*/ - n->getStatus[query] = network_engine.sendFindNode(n->node, - sr->id, - -1, - std::bind(&Dht::searchNodeGetDone, this, _1, _2, ws, query), - std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, query)); + n->getStatus[query] = network_engine + .sendFindNode(n->node, + sr->id, + -1, + std::bind(&Dht::searchNodeGetDone, this, _1, _2, ws, query), + std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, query)); } else { /* 'get' request */ if (not n) @@ -441,12 +443,13 @@ Dht::searchSendGetValues(Sp sr, SearchNode* pn, bool update) /* if (logger_) logger_->d(sr->id, n->node->id, "[search %s] [node %s] Sending 'get'", sr->id.toString().c_str(), n->node->toString().c_str());*/ - n->getStatus[query] = network_engine.sendGetValues(n->node, - sr->id, - *query, - -1, - std::bind(&Dht::searchNodeGetDone, this, _1, _2, ws, query), - std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, query)); + n->getStatus[query] + = network_engine.sendGetValues(n->node, + sr->id, + *query, + -1, + std::bind(&Dht::searchNodeGetDone, this, _1, _2, ws, query), + std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, query)); } else paginate(ws, query, n); } @@ -460,118 +463,164 @@ Dht::searchSendGetValues(Sp sr, SearchNode* pn, bool update) return nullptr; } -void Dht::searchSendAnnounceValue(const Sp& sr, unsigned syncLevel) { +void +Dht::searchSendAnnounceValue(const Sp& sr, unsigned syncLevel) +{ if (sr->announce.empty()) return; std::weak_ptr ws = sr; - auto onDone = [this,ws](const net::Request& req, net::RequestAnswer&& answer) - { /* when put done */ - if (auto sr = ws.lock()) { - onAnnounceDone(req.node, answer, sr); - scheduler.edit(sr->nextSearchStep, scheduler.time()); - } + auto onDone = [this, ws](const net::Request& req, + net::RequestAnswer&& answer) { /* when put done */ + if (auto sr = ws.lock()) { + onAnnounceDone(req.node, answer, sr); + scheduler.edit(sr->nextSearchStep, scheduler.time()); + } }; - auto onExpired = [this,ws](const net::Request&, bool over) - { /* when put expired */ - if (over) - if (auto sr = ws.lock()) - scheduler.edit(sr->nextSearchStep, scheduler.time()); + auto onExpired = [this, ws](const net::Request&, bool over) { /* when put expired */ + if (over) + if (auto sr = ws.lock()) + scheduler.edit(sr->nextSearchStep, + scheduler.time()); }; auto onSelectDone = - [this,ws,onDone,onExpired](const net::Request& req, net::RequestAnswer&& answer) mutable - { /* on probing done */ - auto sr = ws.lock(); - if (not sr) return; - const auto& now = scheduler.time(); - sr->insertNode(req.node, scheduler.time(), answer.ntoken); - auto sn = sr->getNode(req.node); - if (not sn) return; + [this, ws, onDone, onExpired]( + const net::Request& req, + net::RequestAnswer&& + answer) mutable { /* on probing done */ + auto sr = ws.lock(); + if (not sr) + return; + const auto& now = scheduler.time(); + sr->insertNode(req.node, scheduler.time(), answer.ntoken); + auto sn = sr->getNode(req.node); + if (not sn) + return; - if (not sn->isSynced(now)) { - /* Search is now unsynced. Let's call searchStep to sync again. */ - scheduler.edit(sr->nextSearchStep, now); - return; - } - for (auto& a : sr->announce) { - if (sn->getAnnounceTime(a.value->id) > now) - continue; - bool hasValue {false}; - uint16_t seq_no = 0; - try { - const auto& f = std::find_if(answer.fields.cbegin(), answer.fields.cend(), - [&a](const Sp& i){ - return i->index.at(Value::Field::Id).getInt() == a.value->id; - }); - if (f != answer.fields.cend() and *f) { - hasValue = true; - seq_no = static_cast((*f)->index.at(Value::Field::SeqNum).getInt()); - } - } catch (std::out_of_range&) { } + if (not sn->isSynced(now)) { + /* Search is now unsynced. Let's call searchStep to sync again. */ + scheduler.edit(sr->nextSearchStep, now); + return; + } + for (auto& a : sr->announce) { + if (sn->getAnnounceTime(a.value->id) > now) + continue; + bool hasValue {false}; + uint16_t seq_no = 0; + try { + const auto& f = std::find_if(answer.fields.cbegin(), + answer.fields.cend(), + [&a](const Sp& i) { + return i->index.at(Value::Field::Id).getInt() + == a.value->id; + }); + if (f != answer.fields.cend() and *f) { + hasValue = true; + seq_no = static_cast( + (*f)->index.at(Value::Field::SeqNum).getInt()); + } + } catch (std::out_of_range&) { + } - auto next_refresh_time = now + getType(a.value->type).expiration; - auto& acked = sn->acked[a.value->id]; - scheduler.cancel(acked.refresh); - /* only put the value if the node doesn't already have it */ - if (not hasValue or seq_no < a.value->seq) { - if (logger_) - logger_->d(sr->id, sn->node->id, "[search %s] [node %s] Sending 'put' (vid: %016" PRIx64 ")", - sr->id.toString().c_str(), sn->node->toString().c_str(), a.value->id); - auto created = a.permanent ? time_point::max() : a.created; - acked = { - network_engine.sendAnnounceValue(sn->node, sr->id, a.value, created, sn->token, onDone, onExpired), - next_refresh_time - }; - } else if (hasValue and a.permanent) { - if (logger_) - logger_->w(sr->id, sn->node->id, "[search %s] [node %s] Sending 'refresh' (vid: %016" PRIx64 ")", - sr->id.toString().c_str(), sn->node->toString().c_str(), a.value->id); - acked = { - network_engine.sendRefreshValue(sn->node, sr->id, a.value->id, sn->token, onDone, - [this, ws, node=sn->node, v=a.value, - onDone, - onExpired, - created = a.permanent ? time_point::max() : a.created, - next_refresh_time - ](const net::Request& /*req*/, net::DhtProtocolException&& e){ - if (e.getCode() == net::DhtProtocolException::NOT_FOUND) { - if (logger_) - logger_->e(node->id, "[node %s] Returned error 404: storage not found", node->toString().c_str()); - if (auto sr = ws.lock()) { - if (auto sn = sr->getNode(node)) { - sn->acked[v->id] = { - network_engine.sendAnnounceValue(sn->node, sr->id, v, created, sn->token, onDone, onExpired), - next_refresh_time - }; - scheduler.edit(sr->nextSearchStep, scheduler.time()); - return true; - } - } - } - return false; - }, onExpired), - next_refresh_time - }; - } else { - if (logger_) - logger_->w(sr->id, sn->node->id, "[search %s] [node %s] Already has value (vid: %016" PRIx64 "). Aborting.", - sr->id.toString().c_str(), sn->node->toString().c_str(), a.value->id); - auto ack_req = std::make_shared(net::Request::State::COMPLETED); - ack_req->reply_time = now; - acked = {std::move(ack_req), next_refresh_time}; + auto next_refresh_time = now + getType(a.value->type).expiration; + auto& acked = sn->acked[a.value->id]; + scheduler.cancel(acked.refresh); + /* only put the value if the node doesn't already have it */ + if (not hasValue or seq_no < a.value->seq) { + if (logger_) + logger_->d(sr->id, + sn->node->id, + "[search %s] [node %s] Sending 'put' (vid: %016" PRIx64 ")", + sr->id.toString().c_str(), + sn->node->toString().c_str(), + a.value->id); + auto created = a.permanent ? time_point::max() : a.created; + acked = {network_engine.sendAnnounceValue(sn->node, + sr->id, + a.value, + created, + sn->token, + onDone, + onExpired), + next_refresh_time}; + } else if (hasValue and a.permanent) { + if (logger_) + logger_->w(sr->id, + sn->node->id, + "[search %s] [node %s] Sending 'refresh' (vid: %016" PRIx64 + ")", + sr->id.toString().c_str(), + sn->node->toString().c_str(), + a.value->id); + acked = { + network_engine.sendRefreshValue( + sn->node, + sr->id, + a.value->id, + sn->token, + onDone, + [this, + ws, + node = sn->node, + v = a.value, + onDone, + onExpired, + created = a.permanent ? time_point::max() : a.created, + next_refresh_time](const net::Request& /*req*/, + net::DhtProtocolException&& e) { + if (e.getCode() == net::DhtProtocolException::NOT_FOUND) { + if (logger_) + logger_ + ->e(node->id, + "[node %s] Returned error 404: storage not found", + node->toString().c_str()); + if (auto sr = ws.lock()) { + if (auto sn = sr->getNode(node)) { + sn->acked[v->id] + = {network_engine.sendAnnounceValue(sn->node, + sr->id, + v, + created, + sn->token, + onDone, + onExpired), + next_refresh_time}; + scheduler.edit(sr->nextSearchStep, scheduler.time()); + return true; + } + } + } + return false; + }, + onExpired), + next_refresh_time}; + } else { + if (logger_) + logger_->w(sr->id, + sn->node->id, + "[search %s] [node %s] Already has value (vid: %016" PRIx64 + "). Aborting.", + sr->id.toString().c_str(), + sn->node->toString().c_str(), + a.value->id); + auto ack_req = std::make_shared(net::Request::State::COMPLETED); + ack_req->reply_time = now; + acked = {std::move(ack_req), next_refresh_time}; - /* step to clear announces */ - scheduler.edit(sr->nextSearchStep, now); - } - if (a.permanent) { - acked.refresh = scheduler.add(next_refresh_time - REANNOUNCE_MARGIN, std::bind(&Dht::searchStep, this, ws)); - } - } - }; + /* step to clear announces */ + scheduler.edit(sr->nextSearchStep, now); + } + if (a.permanent) { + acked.refresh = scheduler.add(next_refresh_time - REANNOUNCE_MARGIN, + std::bind(&Dht::searchStep, this, ws)); + } + } + }; - static const auto PROBE_QUERY = std::make_shared(Select {}.field(Value::Field::Id).field(Value::Field::SeqNum)); + static const auto PROBE_QUERY = std::make_shared( + Select {}.field(Value::Field::Id).field(Value::Field::SeqNum)); const auto& now = scheduler.time(); unsigned i = 0; @@ -592,12 +641,15 @@ void Dht::searchSendAnnounceValue(const Sp& sr, unsigned syncLevel) { sendQuery = true; } else { if (logger_) - logger_->w(sr->id, n.node->id, "[search %s] [node %s] Sending 'put' (vid: %016" PRIx64 ")", - sr->id.toString().c_str(), n.node->toString().c_str(), a.value->id); - n.acked[a.value->id] = { - network_engine.sendAnnounceValue(n.node, sr->id, a.value, a.created, n.token, onDone, onExpired), - now + getType(a.value->type).expiration - }; + logger_->w(sr->id, + n.node->id, + "[search %s] [node %s] Sending 'put' (vid: %016" PRIx64 ")", + sr->id.toString().c_str(), + n.node->toString().c_str(), + a.value->id); + n.acked[a.value->id] = {network_engine.sendAnnounceValue( + n.node, sr->id, a.value, a.created, n.token, onDone, onExpired), + now + getType(a.value->type).expiration}; } } } @@ -605,14 +657,18 @@ void Dht::searchSendAnnounceValue(const Sp& sr, unsigned syncLevel) { if (sendQuery) { n.probe_query = PROBE_QUERY; if (logger_) - logger_->d(sr->id, n.node->id, "[search %s] [node %s] Sending %s", - sr->id.toString().c_str(), n.node->toString().c_str(), n.probe_query->toString().c_str()); + logger_->d(sr->id, + n.node->id, + "[search %s] [node %s] Sending %s", + sr->id.toString().c_str(), + n.node->toString().c_str(), + n.probe_query->toString().c_str()); auto req = network_engine.sendGetValues(n.node, - sr->id, - *PROBE_QUERY, - -1, - onSelectDone, - std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, PROBE_QUERY)); + sr->id, + *PROBE_QUERY, + -1, + onSelectDone, + std::bind(&Dht::searchNodeGetExpired, this, _1, _2, ws, PROBE_QUERY)); n.getStatus[PROBE_QUERY] = std::move(req); } if (not n.candidate and ++i == syncLevel) @@ -636,22 +692,26 @@ Dht::searchSynchedNodeListen(const Sp& sr, SearchNode& n) // sr->id.toString().c_str(), n.node->toString().c_str()); if (r == n.listenStatus.end()) { - r = n.listenStatus.emplace(std::piecewise_construct, - std::forward_as_tuple(query), - std::forward_as_tuple( - l.second.get_cb, - l.second.sync_cb, - n.node->openSocket([this,ws,query](const Sp& node, net::RequestAnswer&& answer) mutable { - /* on new values */ - if (auto sr = ws.lock()) { - scheduler.edit(sr->nextSearchStep, scheduler.time()); - sr->insertNode(node, scheduler.time(), answer.ntoken); - if (auto sn = sr->getNode(node)) { - sn->onValues(query, std::move(answer), types, scheduler); - } - } - }))).first; - r->second.cacheExpirationJob = scheduler.add(time_point::max(), [this,ws,query,node=n.node]{ + r = n.listenStatus + .emplace(std::piecewise_construct, + std::forward_as_tuple(query), + std::forward_as_tuple(l.second.get_cb, + l.second.sync_cb, + n.node->openSocket([this, + ws, + query](const Sp& node, + net::RequestAnswer&& answer) mutable { + /* on new values */ + if (auto sr = ws.lock()) { + scheduler.edit(sr->nextSearchStep, scheduler.time()); + sr->insertNode(node, scheduler.time(), answer.ntoken); + if (auto sn = sr->getNode(node)) { + sn->onValues(query, std::move(answer), types, scheduler); + } + } + }))) + .first; + r->second.cacheExpirationJob = scheduler.add(time_point::max(), [this, ws, query, node = n.node] { if (auto sr = ws.lock()) { if (auto sn = sr->getNode(node)) { sn->expireValues(query, scheduler); @@ -659,28 +719,37 @@ Dht::searchSynchedNodeListen(const Sp& sr, SearchNode& n) } }); } - auto new_req = network_engine.sendListen(n.node, sr->id, *query, n.token, r->second.socketId, - [this,ws,query](const net::Request& req, net::RequestAnswer&& answer) mutable - { /* on done */ - if (auto sr = ws.lock()) { - scheduler.edit(sr->nextSearchStep, scheduler.time()); - if (auto sn = sr->getNode(req.node)) { - auto job = scheduler.add(sn->getListenTime(query, getListenExpiration()), std::bind(&Dht::searchStep, this, ws)); - sn->onListenSynced(query, true, std::move(job)); - } - onListenDone(req.node, answer, sr); - } + auto new_req = network_engine.sendListen( + n.node, + sr->id, + *query, + n.token, + r->second.socketId, + [this, + ws, + query](const net::Request& req, + net::RequestAnswer&& + answer) mutable { /* on done */ + if (auto sr = ws.lock()) { + scheduler.edit(sr->nextSearchStep, scheduler.time()); + if (auto sn = sr->getNode(req.node)) { + auto job = scheduler.add(sn->getListenTime(query, + getListenExpiration()), + std::bind(&Dht::searchStep, this, ws)); + sn->onListenSynced(query, true, std::move(job)); + } + onListenDone(req.node, answer, sr); + } }, - [this,ws,query](const net::Request& req, bool over) mutable - { /* on request expired */ - if (auto sr = ws.lock()) { - scheduler.edit(sr->nextSearchStep, scheduler.time()); - if (over) - if (auto sn = sr->getNode(req.node)) - sn->listenStatus.erase(query); - } - } - ); + [this, ws, query](const net::Request& req, bool over) mutable { /* on request expired */ + if (auto sr = ws.lock()) { + scheduler.edit(sr->nextSearchStep, + scheduler.time()); + if (over) + if (auto sn = sr->getNode(req.node)) + sn->listenStatus.erase(query); + } + }); // Here the request may have failed and the CachedListenStatus removed r = n.listenStatus.find(query); if (r != n.listenStatus.end()) { @@ -695,7 +764,8 @@ void Dht::searchStep(std::weak_ptr ws) { auto sr = ws.lock(); - if (not sr or sr->expired or sr->done) return; + if (not sr or sr->expired or sr->done) + return; const auto& now = scheduler.time(); auto level = sr->syncLevel(now); @@ -708,12 +778,12 @@ Dht::searchStep(std::weak_ptr ws) sr->id.toString().c_str(), sr->af == AF_INET ? '4' : '6', req_count);*/ sr->step_time = now; - if (sr->refill_time + Node::NODE_EXPIRE_TIME < now and sr->nodes.size()-sr->getNumberOfBadNodes() < SEARCH_NODES) + if (sr->refill_time + Node::NODE_EXPIRE_TIME < now and sr->nodes.size() - sr->getNumberOfBadNodes() < SEARCH_NODES) refill(*sr); /* Check if the first TARGET_NODES (8) live nodes have replied. */ if (sr->isSynced(now)) { - if (not (sr->callbacks.empty() and sr->announce.empty())) { + if (not(sr->callbacks.empty() and sr->announce.empty())) { // search is synced but some (newer) get operations are not complete // Call callbacks when done std::vector completed_gets; @@ -722,8 +792,7 @@ Dht::searchStep(std::weak_ptr ws) sr->setDone(b->second); completed_gets.emplace_back(std::move(b->second)); b = sr->callbacks.erase(b); - } - else + } else ++b; } // clear corresponding queries @@ -779,11 +848,10 @@ Dht::searchStep(std::weak_ptr ws) searchSendAnnounceValue(sr, syncLevel); } - while (sr->currentlySolicitedNodeCount() < MAX_REQUESTED_SEARCH_NODES and searchSendGetValues(sr)); + while (sr->currentlySolicitedNodeCount() < MAX_REQUESTED_SEARCH_NODES and searchSendGetValues(sr)) + ; - - if (sr->getNumberOfConsecutiveBadNodes() >= std::min(sr->nodes.size(), SEARCH_MAX_BAD_NODES)) - { + if (sr->getNumberOfConsecutiveBadNodes() >= std::min(sr->nodes.size(), SEARCH_MAX_BAD_NODES)) { if (logger_) logger_->w(sr->id, "[search %s IPv%c] Expired", sr->id.toString().c_str(), sr->af == AF_INET ? '4' : '6'); sr->expire(); @@ -794,7 +862,9 @@ Dht::searchStep(std::weak_ptr ws) /* dumpSearch(*sr, std::cout); */ } -unsigned Dht::refill(Dht::Search& sr) { +unsigned +Dht::refill(Dht::Search& sr) +{ const auto& now = scheduler.time(); sr.refill_time = now; /* we search for up to SEARCH_NODES good nodes. */ @@ -802,8 +872,10 @@ unsigned Dht::refill(Dht::Search& sr) { if (cached_nodes.empty()) { if (logger_) - logger_->e(sr.id, "[search %s IPv%c] No nodes from cache while refilling search", - sr.id.toString().c_str(), (sr.af == AF_INET) ? '4' : '6'); + logger_->e(sr.id, + "[search %s IPv%c] No nodes from cache while refilling search", + sr.id.toString().c_str(), + (sr.af == AF_INET) ? '4' : '6'); return 0; } @@ -814,15 +886,23 @@ unsigned Dht::refill(Dht::Search& sr) { ++inserted; } if (logger_) - logger_->d(sr.id, "[search %s IPv%c] Refilled search with %u nodes from node cache", - sr.id.toString().c_str(), (sr.af == AF_INET) ? '4' : '6', inserted); + logger_->d(sr.id, + "[search %s IPv%c] Refilled search with %u nodes from node cache", + sr.id.toString().c_str(), + (sr.af == AF_INET) ? '4' : '6', + inserted); return inserted; } - /* Start a search. */ Sp -Dht::search(const InfoHash& id, sa_family_t af, GetCallback gcb, QueryCallback qcb, DoneCallback dcb, Value::Filter f, const Sp& q) +Dht::search(const InfoHash& id, + sa_family_t af, + GetCallback gcb, + QueryCallback qcb, + DoneCallback dcb, + Value::Filter f, + const Sp& q) { if (!isRunning(af)) { if (logger_) @@ -845,7 +925,7 @@ Dht::search(const InfoHash& id, sa_family_t af, GetCallback gcb, QueryCallback q sr = std::make_shared(); srs.emplace(id, sr); } else { - for (auto it = srs.begin(); it!=srs.end();) { + for (auto it = srs.begin(); it != srs.end();) { auto& s = *it->second; if ((s.done or s.expired) and s.announce.empty() and s.listeners.empty()) { sr = it->second; @@ -854,7 +934,10 @@ Dht::search(const InfoHash& id, sa_family_t af, GetCallback gcb, QueryCallback q } if (not sr) { if (logger_) - logger_->e(id, "[search %s IPv%c] Maximum number of searches reached!", id.toString().c_str(), (af == AF_INET) ? '4' : '6'); + logger_->e(id, + "[search %s IPv%c] Maximum number of searches reached!", + id.toString().c_str(), + (af == AF_INET) ? '4' : '6'); return {}; } } @@ -865,8 +948,9 @@ Dht::search(const InfoHash& id, sa_family_t af, GetCallback gcb, QueryCallback q sr->done = false; sr->expired = false; sr->nodes.clear(); - sr->nodes.reserve(SEARCH_NODES+1); - sr->nextSearchStep = scheduler.add(time_point::max(), std::bind(&Dht::searchStep, this, std::weak_ptr(sr))); + sr->nodes.reserve(SEARCH_NODES + 1); + sr->nextSearchStep = scheduler.add(time_point::max(), + std::bind(&Dht::searchStep, this, std::weak_ptr(sr))); if (logger_) logger_->w(id, "[search %s IPv%c] New search", id.toString().c_str(), (af == AF_INET) ? '4' : '6'); if (search_id == 0) @@ -880,12 +964,8 @@ Dht::search(const InfoHash& id, sa_family_t af, GetCallback gcb, QueryCallback q } void -Dht::announce(const InfoHash& id, - sa_family_t af, - Sp value, - DoneCallback callback, - time_point created, - bool permanent) +Dht::announce( + const InfoHash& id, sa_family_t af, Sp value, DoneCallback callback, time_point created, bool permanent) { auto& srs = searches(af); auto srp = srs.find(id); @@ -902,9 +982,10 @@ Dht::listenTo(const InfoHash& id, sa_family_t af, ValueCallback cb, Value::Filte { if (!isRunning(af)) return 0; - // logger__ERR("[search %s IPv%c] Search_time is now in %lfs", sr->id.toString().c_str(), (sr->af == AF_INET) ? '4' : '6', print_duration(tm-clock::now())); + // logger__ERR("[search %s IPv%c] Search_time is now in %lfs", sr->id.toString().c_str(), (sr->af == AF_INET) ? '4' + // : '6', print_duration(tm-clock::now())); - //logger__WARN("listenTo %s", id.toString().c_str()); + // logger__WARN("listenTo %s", id.toString().c_str()); auto& srs = searches(af); auto srp = srs.find(id); Sp sr = (srp == srs.end()) ? search(id, af) : srp->second; @@ -926,11 +1007,9 @@ Dht::listen(const InfoHash& id, ValueCallback cb, Value::Filter f, Where where) scheduler.syncTime(); auto token = ++listener_token; - auto gcb = OpValueCache::cacheCallback(std::move(cb), [this, id, token]{ - cancelListen(id, token); - }); + auto gcb = OpValueCache::cacheCallback(std::move(cb), [this, id, token] { cancelListen(id, token); }); - auto query = std::make_shared(Select{}, std::move(where)); + auto query = std::make_shared(Select {}, std::move(where)); auto filter = Value::Filter::chain(std::move(f), query->where.getFilter()); auto st = store.find(id); if (st == store.end() && store.size() < max_store_keys) @@ -972,7 +1051,7 @@ Dht::cancelListen(const InfoHash& id, size_t token) if (st != store.end()) st->second.cancelListen(tokenlocal); } - auto searches_cancel_listen = [this,&id](std::map>& srs, size_t token) { + auto searches_cancel_listen = [this, &id](std::map>& srs, size_t token) { if (token) { auto srp = srs.find(id); if (srp != srs.end()) @@ -985,19 +1064,25 @@ Dht::cancelListen(const InfoHash& id, size_t token) return true; } -struct OpStatus { - struct Status { +struct OpStatus +{ + struct Status + { bool done {false}; bool ok {false}; - Status(bool done=false, bool ok=false) : done(done), ok(ok) {} + Status(bool done = false, bool ok = false) + : done(done) + , ok(ok) + {} }; Status status; Status status4; Status status6; }; -template -struct GetStatus : public OpStatus { +template +struct GetStatus : public OpStatus +{ T values; std::vector> nodes; }; @@ -1013,7 +1098,7 @@ Dht::put(const InfoHash& id, Sp val, DoneCallback callback, time_point cr return; } if (val->id == Value::INVALID_ID) - val->id = std::uniform_int_distribution{1}(rd); + val->id = std::uniform_int_distribution {1}(rd); scheduler.syncTime(); const auto& now = scheduler.time(); created = std::min(now, created); @@ -1030,24 +1115,38 @@ Dht::put(const InfoHash& id, Sp val, DoneCallback callback, time_point cr op.status.done = true; } }; - announce(id, AF_INET, val, [=](bool ok4, const std::vector>& nodes) { - if (logger_) - logger_->d(id, "Announce done IPv4 %d", ok4); - auto& o = *op; - o.status4 = {true, ok4}; - donecb(nodes, o); - }, created, permanent); - announce(id, AF_INET6, val, [=](bool ok6, const std::vector>& nodes) { - if (logger_) - logger_->d(id, "Announce done IPv6 %d", ok6); - auto& o = *op; - o.status6 = {true, ok6}; - donecb(nodes, o); - }, created, permanent); + announce( + id, + AF_INET, + val, + [=](bool ok4, const std::vector>& nodes) { + if (logger_) + logger_->d(id, "Announce done IPv4 %d", ok4); + auto& o = *op; + o.status4 = {true, ok4}; + donecb(nodes, o); + }, + created, + permanent); + announce( + id, + AF_INET6, + val, + [=](bool ok6, const std::vector>& nodes) { + if (logger_) + logger_->d(id, "Announce done IPv6 %d", ok6); + auto& o = *op; + o.status6 = {true, ok6}; + donecb(nodes, o); + }, + created, + permanent); } -template -void doneCallbackWrapper(DoneCallback dcb, const std::vector>& nodes, GetStatus& op) { +template +void +doneCallbackWrapper(DoneCallback dcb, const std::vector>& nodes, GetStatus& op) +{ if (op.status.done) return; op.nodes.insert(op.nodes.end(), nodes.begin(), nodes.end()); @@ -1059,9 +1158,10 @@ void doneCallbackWrapper(DoneCallback dcb, const std::vector>& nodes, G } } -template -bool callbackWrapper(Cb get_cb, DoneCallback done_cb, const std::vector>& values, - Av add_values, Cv cache_values, GetStatus& op) +template +bool +callbackWrapper( + Cb get_cb, DoneCallback done_cb, const std::vector>& values, Av add_values, Cv cache_values, GetStatus& op) { if (op.status.done) return false; @@ -1089,19 +1189,25 @@ Dht::get(const InfoHash& id, GetCallback getcb, DoneCallback donecb, Value::Filt auto op = std::make_shared>>>(); auto gcb = [getcb, donecb, op](const std::vector>& vals) { auto& o = *op; - return callbackWrapper(getcb, donecb, vals, [&o](const std::vector>& values) { - std::vector> newvals {}; - for (const auto& v : values) { - auto it = o.values.find(v->id); - if (it == o.values.cend() or (it->second != v && !(*it->second == *v))) { - newvals.push_back(v); + return callbackWrapper( + getcb, + donecb, + vals, + [&o](const std::vector>& values) { + std::vector> newvals {}; + for (const auto& v : values) { + auto it = o.values.find(v->id); + if (it == o.values.cend() or (it->second != v && !(*it->second == *v))) { + newvals.push_back(v); + } } - } - return newvals; - }, [&o](const std::vector>& newvals) { - for (const auto& v : newvals) - o.values[v->id] = v; - }, o); + return newvals; + }, + [&o](const std::vector>& newvals) { + for (const auto& v : newvals) + o.values[v->id] = v; + }, + o); }; auto q = std::make_shared(Select {}, std::move(where)); @@ -1110,19 +1216,34 @@ Dht::get(const InfoHash& id, GetCallback getcb, DoneCallback donecb, Value::Filt /* Try to answer this search locally. */ gcb(getLocal(id, f)); - Dht::search(id, AF_INET, gcb, {}, [=](bool ok, const std::vector>& nodes) { - //logger__WARN("DHT done IPv4"); - op->status4 = {true, ok}; - doneCallbackWrapper(donecb, nodes, *op); - }, f, q); - Dht::search(id, AF_INET6, gcb, {}, [=](bool ok, const std::vector>& nodes) { - //logger__WARN("DHT done IPv6"); - op->status6 = {true, ok}; - doneCallbackWrapper(donecb, nodes, *op); - }, f, q); + Dht::search( + id, + AF_INET, + gcb, + {}, + [=](bool ok, const std::vector>& nodes) { + // logger__WARN("DHT done IPv4"); + op->status4 = {true, ok}; + doneCallbackWrapper(donecb, nodes, *op); + }, + f, + q); + Dht::search( + id, + AF_INET6, + gcb, + {}, + [=](bool ok, const std::vector>& nodes) { + // logger__WARN("DHT done IPv6"); + op->status6 = {true, ok}; + doneCallbackWrapper(donecb, nodes, *op); + }, + f, + q); } -void Dht::query(const InfoHash& id, QueryCallback cb, DoneCallback done_cb, Query&& q) +void +Dht::query(const InfoHash& id, QueryCallback cb, DoneCallback done_cb, Query&& q) { if (not id) { if (logger_) @@ -1134,29 +1255,33 @@ void Dht::query(const InfoHash& id, QueryCallback cb, DoneCallback done_cb, Quer scheduler.syncTime(); auto op = std::make_shared>>>(); auto f = q.where.getFilter(); - auto qcb = [cb, done_cb, op](const std::vector>& fields){ + auto qcb = [cb, done_cb, op](const std::vector>& fields) { auto& o = *op; - return callbackWrapper(cb, done_cb, fields, [&](const std::vector>& fields) { - std::vector> newvals {}; - for (const auto& f : fields) { - auto it = std::find_if(o.values.cbegin(), o.values.cend(), - [&](const Sp& sf) { + return callbackWrapper( + cb, + done_cb, + fields, + [&](const std::vector>& fields) { + std::vector> newvals {}; + for (const auto& f : fields) { + auto it = std::find_if(o.values.cbegin(), o.values.cend(), [&](const Sp& sf) { return sf == f or f->containedIn(*sf); }); - if (it == o.values.cend()) { - auto lesser = std::find_if(o.values.begin(), o.values.end(), - [&](const Sp& sf) { - return sf->containedIn(*f); - }); - if (lesser != o.values.end()) - o.values.erase(lesser); - newvals.push_back(f); + if (it == o.values.cend()) { + auto lesser = std::find_if(o.values.begin(), + o.values.end(), + [&](const Sp& sf) { return sf->containedIn(*f); }); + if (lesser != o.values.end()) + o.values.erase(lesser); + newvals.push_back(f); + } } - } - return newvals; - }, [&](const std::vector>& fields){ - o.values.insert(o.values.end(), fields.begin(), fields.end()); - }, o); + return newvals; + }, + [&](const std::vector>& fields) { + o.values.insert(o.values.end(), fields.begin(), fields.end()); + }, + o); }; /* Try to answer this search locally. */ @@ -1168,23 +1293,38 @@ void Dht::query(const InfoHash& id, QueryCallback cb, DoneCallback done_cb, Quer qcb(local_fields); auto sq = std::make_shared(std::move(q)); - Dht::search(id, AF_INET, {}, qcb, [=](bool ok, const std::vector>& nodes) { - //logger__WARN("DHT done IPv4"); - op->status4 = {true, ok}; - doneCallbackWrapper(done_cb, nodes, *op); - }, f, sq); - Dht::search(id, AF_INET6, {}, qcb, [=](bool ok, const std::vector>& nodes) { - //logger__WARN("DHT done IPv6"); - op->status6 = {true, ok}; - doneCallbackWrapper(done_cb, nodes, *op); - }, f, sq); + Dht::search( + id, + AF_INET, + {}, + qcb, + [=](bool ok, const std::vector>& nodes) { + // logger__WARN("DHT done IPv4"); + op->status4 = {true, ok}; + doneCallbackWrapper(done_cb, nodes, *op); + }, + f, + sq); + Dht::search( + id, + AF_INET6, + {}, + qcb, + [=](bool ok, const std::vector>& nodes) { + // logger__WARN("DHT done IPv6"); + op->status6 = {true, ok}; + doneCallbackWrapper(done_cb, nodes, *op); + }, + f, + sq); } std::vector> Dht::getLocal(const InfoHash& id, const Value::Filter& f) const { auto s = store.find(id); - if (s == store.end()) return {}; + if (s == store.end()) + return {}; return s->second.get(f); } @@ -1203,7 +1343,8 @@ Dht::getPut(const InfoHash& id) const std::vector> ret; auto find_values = [&](const std::map>& srs) { auto srp = srs.find(id); - if (srp == srs.end()) return; + if (srp == srs.end()) + return; auto vals = srp->second->getPut(); ret.insert(ret.end(), vals.begin(), vals.end()); }; @@ -1263,9 +1404,10 @@ Dht::storageChanged(const InfoHash& id, Storage& st, const Sp& v, bool ne vals.push_back(v); if (not vals.empty()) { if (logger_) - logger_->d(id, "[store %s] Sending update local listener with token %lu", - id.toString().c_str(), - l.first); + logger_->d(id, + "[store %s] Sending update local listener with token %lu", + id.toString().c_str(), + l.first); cbs.emplace_back(l.second.get_cb, std::move(vals)); } } @@ -1284,14 +1426,24 @@ Dht::storageChanged(const InfoHash& id, Storage& st, const Sp& v, bool ne if (f and not f(*v)) continue; if (logger_) - logger_->w(id, node_listeners.first->id, "[store %s] [node %s] Sending update", - id.toString().c_str(), - node_listeners.first->toString().c_str()); + logger_->w(id, + node_listeners.first->id, + "[store %s] [node %s] Sending update", + id.toString().c_str(), + node_listeners.first->toString().c_str()); std::vector> vals {}; vals.push_back(v); Blob ntoken = makeToken(node_listeners.first->getAddr(), false); - network_engine.tellListener(node_listeners.first, l.first, id, 0, ntoken, {}, {}, - std::move(vals), l.second.query, l.second.version); + network_engine.tellListener(node_listeners.first, + l.first, + id, + 0, + ntoken, + {}, + {}, + std::move(vals), + l.second.query, + l.second.version); } } } @@ -1357,13 +1509,19 @@ Dht::storageAddListener(const InfoHash& id, const Sp& node, size_t socket_ if (l == node_listeners.end()) { auto vals = st->second.get(query.where.getFilter()); if (not vals.empty()) { - network_engine.tellListener(node, socket_id, id, WANT4 | WANT6, makeToken(node->getAddr(), false), - dht4.buckets.findClosestNodes(id, now, TARGET_NODES), dht6.buckets.findClosestNodes(id, now, TARGET_NODES), - std::move(vals), query, version); + network_engine.tellListener(node, + socket_id, + id, + WANT4 | WANT6, + makeToken(node->getAddr(), false), + dht4.buckets.findClosestNodes(id, now, TARGET_NODES), + dht6.buckets.findClosestNodes(id, now, TARGET_NODES), + std::move(vals), + query, + version); } node_listeners.emplace(socket_id, Listener {now, std::forward(query), version}); - } - else + } else l->second.refresh(now, std::forward(query)); } @@ -1390,8 +1548,7 @@ void Dht::storageRemoved(const InfoHash& id, Storage& st, const std::vector>& values, size_t totalSize) { if (logger_) - logger_->d(id, "[store %s] Discarded %ld values (%ld bytes)", - id.toString().c_str(), values.size(), totalSize); + logger_->d(id, "[store %s] Discarded %ld values (%ld bytes)", id.toString().c_str(), values.size(), totalSize); total_store_size -= totalSize; total_values -= values.size(); @@ -1408,9 +1565,11 @@ Dht::storageRemoved(const InfoHash& id, Storage& st, const std::vector for (const auto& node_listeners : st.listeners) { for (const auto& l : node_listeners.second) { if (logger_) - logger_->w(id, node_listeners.first->id, "[store %s] [node %s] Sending expired", - id.toString().c_str(), - node_listeners.first->toString().c_str()); + logger_->w(id, + node_listeners.first->id, + "[store %s] [node %s] Sending expired", + id.toString().c_str(), + node_listeners.first->toString().c_str()); Blob ntoken = makeToken(node_listeners.first->getAddr(), false); network_engine.tellListenerExpired(node_listeners.first, l.first, id, ntoken, ids, l.second.version); } @@ -1432,8 +1591,7 @@ Dht::expireStore() if (logger_) logger_->d(i->first, "[store %s] Discarding empty storage", i->first.toString().c_str()); i = store.erase(i); - } - else + } else ++i; } @@ -1456,7 +1614,10 @@ Dht::expireStore() auto storage = store.find(exp_value.first); if (storage != store.end()) { if (logger_) - logger_->w("Storage quota full: discarding value from %s at %s %016" PRIx64, largest->first.toString().c_str(), exp_value.first.to_c_str(), exp_value.second); + logger_->w("Storage quota full: discarding value from %s at %s %016" PRIx64, + largest->first.toString().c_str(), + exp_value.first.to_c_str(), + exp_value.second); if (auto value = storage->second.remove(exp_value.first, exp_value.second)) { storageRemoved(storage->first, storage->second, {value}, value->size()); @@ -1492,7 +1653,7 @@ void Dht::rotateSecrets() { oldsecret = secret; - secret = std::uniform_int_distribution{}(rd); + secret = std::uniform_int_distribution {}(rd); uniform_duration_distribution<> time_dist(std::chrono::minutes(15), std::chrono::minutes(45)); auto rotate_secrets_time = scheduler.time() + time_dist(rd); scheduler.add(rotate_secrets_time, std::bind(&Dht::rotateSecrets, this)); @@ -1501,7 +1662,7 @@ Dht::rotateSecrets() Blob Dht::makeToken(const SockAddr& addr, bool old) const { - const void *ip; + const void* ip; size_t iplen; in_port_t port; @@ -1522,10 +1683,10 @@ Dht::makeToken(const SockAddr& addr, bool old) const const auto& c1 = old ? oldsecret : secret; Blob data; - data.reserve(sizeof(secret)+sizeof(in_port_t)+iplen); - data.insert(data.end(), (uint8_t*)&c1, ((uint8_t*)&c1) + sizeof(c1)); - data.insert(data.end(), (uint8_t*)ip, (uint8_t*)ip+iplen); - data.insert(data.end(), (uint8_t*)&port, ((uint8_t*)&port)+sizeof(in_port_t)); + data.reserve(sizeof(secret) + sizeof(in_port_t) + iplen); + data.insert(data.end(), (uint8_t*) &c1, ((uint8_t*) &c1) + sizeof(c1)); + data.insert(data.end(), (uint8_t*) ip, (uint8_t*) ip + iplen); + data.insert(data.end(), (uint8_t*) &port, ((uint8_t*) &port) + sizeof(in_port_t)); return crypto::hash(data, TOKEN_SIZE); } @@ -1578,7 +1739,7 @@ Dht::dumpBucket(const Bucket& b, std::ostream& out) const out << b.first << " count: " << b.nodes.size() << " updated: " << print_time_relative(now, b.time); if (b.cached) out << " (cached)"; - out << std::endl; + out << std::endl; for (auto& n : b.nodes) { out << " Node " << n->toString(); const auto& t = n->getTime(); @@ -1601,16 +1762,16 @@ Dht::dumpSearch(const Search& sr, std::ostream& out) const const auto& now = scheduler.time(); const auto& listen_expire = getListenExpiration(); using namespace std::chrono; - fmt::print(out, "Search IPv{} {} gets: {} last step: {}{}{}{}{}\n", - (sr.af == AF_INET6 ? '6' : '4'), - sr.id, - sr.callbacks.size(), - print_time_relative(now, sr.step_time), - (sr.done ? " [done]"sv : ""sv), - (sr.expired ? " [expired]"sv : ""sv), - (sr.isSynced(now) ? " [synced]"sv : " [not synced]"sv), - (sr.isListening(now, listen_expire) ? " [listening]"sv : ""sv) - ); + fmt::print(out, + "Search IPv{} {} gets: {} last step: {}{}{}{}{}\n", + (sr.af == AF_INET6 ? '6' : '4'), + sr.id, + sr.callbacks.size(), + print_time_relative(now, sr.step_time), + (sr.done ? " [done]"sv : ""sv), + (sr.expired ? " [expired]"sv : ""sv), + (sr.isSynced(now) ? " [synced]"sv : " [not synced]"sv), + (sr.isListening(now, listen_expire) ? " [listening]"sv : ""sv)); // printing the queries if (sr.callbacks.size() + sr.listeners.size() > 0) @@ -1631,7 +1792,13 @@ Dht::dumpSearch(const Search& sr, std::ostream& out) const auto last_get = sr.getLastGetTime(); for (const auto& np : sr.nodes) { auto& n = *np; - auto listen = (not sr.listeners.empty() ? (n.listenStatus.empty() ? " " : fmt::format("[{}] ", (n.isListening(now,listen_expire) ? 'l' : (n.pending(n.listenStatus) ? 'f' : ' ')))) : ""); + auto listen = (not sr.listeners.empty() + ? (n.listenStatus.empty() ? " " + : fmt::format("[{}] ", + (n.isListening(now, listen_expire) + ? 'l' + : (n.pending(n.listenStatus) ? 'f' : ' ')))) + : ""); std::string announce; if (not sr.announce.empty()) { if (n.acked.empty()) { @@ -1650,16 +1817,16 @@ Dht::dumpSearch(const Search& sr, std::ostream& out) const } } - fmt::print(out, "{:3} {} {} [{}{}] {}{}{}\n", - InfoHash::commonBits(sr.id, n.node->id), - n.node->id, - (findNode(n.node->id, sr.af) ? '*' : ' '), - (n.pending(n.getStatus) ? (n.candidate ? 'c' : 'f') : ' '), - (n.isSynced(now) ? (n.last_get_reply > last_get ? 'u' : 's') : '-'), - listen, - announce, - n.node->getAddrStr() - ); + fmt::print(out, + "{:3} {} {} [{}{}] {}{}{}\n", + InfoHash::commonBits(sr.id, n.node->id), + n.node->id, + (findNode(n.node->id, sr.af) ? '*' : ' '), + (n.pending(n.getStatus) ? (n.candidate ? 'c' : 'f') : ' '), + (n.isSynced(now) ? (n.last_get_reply > last_get ? 'u' : 's') : '-'), + listen, + announce, + n.node->getAddrStr()); } } @@ -1708,7 +1875,7 @@ Dht::getStorageLog() const if (total_store_size < 1024) out << total_store_size << " bytes)"; else - out << (total_store_size/1024) << " / " << (max_store_size/1024) << " KB)"; + out << (total_store_size / 1024) << " / " << (max_store_size / 1024) << " KB)"; out << std::endl; return out.str(); } @@ -1731,15 +1898,14 @@ Dht::printStorageLog(const decltype(store)::value_type& s) const std::ostringstream out; using namespace std::chrono; const auto& st = s.second; - out << "Storage " << s.first << " " - << st.listeners.size() << " list., " - << st.valueCount() << " values (" - << st.totalSize() << " bytes)" << std::endl; + out << "Storage " << s.first << " " << st.listeners.size() << " list., " << st.valueCount() << " values (" + << st.totalSize() << " bytes)" << std::endl; if (not st.local_listeners.empty()) out << " " << st.local_listeners.size() << " local listeners" << std::endl; for (const auto& node_listeners : st.listeners) { const auto& node = node_listeners.first; - out << " " << "Listener " << node->toString() << " : " << node_listeners.second.size() << " entries" << std::endl; + out << " " << "Listener " << node->toString() << " : " << node_listeners.second.size() << " entries" + << std::endl; } return out.str(); } @@ -1774,7 +1940,8 @@ Dht::getSearchesLog(sa_family_t af) const for (const auto& sr : dht6.searches) dumpSearch(*sr.second, out); } - out << "Total: " << num_searches << " searches (" << dht4.searches.size() << " IPv4, " << dht6.searches.size() << " IPv6)." << std::endl; + out << "Total: " << num_searches << " searches (" << dht4.searches.size() << " IPv4, " << dht6.searches.size() + << " IPv6)." << std::endl; return out.str(); } @@ -1807,36 +1974,43 @@ fromDhtConfig(const Config& config) net::NetworkConfig netConf; netConf.network = config.network; netConf.max_req_per_sec = config.max_req_per_sec ? config.max_req_per_sec : MAX_REQUESTS_PER_SEC; - netConf.max_peer_req_per_sec = config.max_peer_req_per_sec - ? config.max_peer_req_per_sec - : netConf.max_req_per_sec/8; + netConf.max_peer_req_per_sec = config.max_peer_req_per_sec ? config.max_peer_req_per_sec + : netConf.max_req_per_sec / 8; netConf.is_client = config.client_mode; return netConf; } -Dht::Dht(std::unique_ptr&& sock, const Config& config, const Sp& l, std::unique_ptr&& rda) - : DhtInterface(l), - rd(rda ? std::move(*rda) : crypto::getSeededRandomEngine()), - myid(config.node_id ? config.node_id : InfoHash::getRandom(rd)), - store(), - store_quota(), - max_store_keys(config.max_store_keys ? (int)config.max_store_keys : MAX_HASHES), - max_store_size(config.max_store_size ? (int)config.max_store_size : DEFAULT_STORAGE_LIMIT), - max_searches(config.max_searches ? (int)config.max_searches : MAX_SEARCHES), - network_engine(myid, fromDhtConfig(config), std::move(sock), logger_, rd, scheduler, - std::bind(&Dht::onError, this, _1, _2), - std::bind(&Dht::onNewNode, this, _1, _2), - std::bind(&Dht::onReportedAddr, this, _1, _2), - std::bind(&Dht::onPing, this, _1), - std::bind(&Dht::onFindNode, this, _1, _2, _3), - std::bind(&Dht::onGetValues, this, _1, _2, _3, _4), - std::bind(&Dht::onListen, this, _1, _2, _3, _4, _5, _6), - std::bind(&Dht::onAnnounce, this, _1, _2, _3, _4, _5), - std::bind(&Dht::onRefresh, this, _1, _2, _3, _4)), - persistPath(config.persist_path), - is_bootstrap(config.is_bootstrap), - maintain_storage(config.maintain_storage), - public_stable(config.public_stable) +Dht::Dht(std::unique_ptr&& sock, + const Config& config, + const Sp& l, + std::unique_ptr&& rda) + : DhtInterface(l) + , rd(rda ? std::move(*rda) : crypto::getSeededRandomEngine()) + , myid(config.node_id ? config.node_id : InfoHash::getRandom(rd)) + , store() + , store_quota() + , max_store_keys(config.max_store_keys ? (int) config.max_store_keys : MAX_HASHES) + , max_store_size(config.max_store_size ? (int) config.max_store_size : DEFAULT_STORAGE_LIMIT) + , max_searches(config.max_searches ? (int) config.max_searches : MAX_SEARCHES) + , network_engine(myid, + fromDhtConfig(config), + std::move(sock), + logger_, + rd, + scheduler, + std::bind(&Dht::onError, this, _1, _2), + std::bind(&Dht::onNewNode, this, _1, _2), + std::bind(&Dht::onReportedAddr, this, _1, _2), + std::bind(&Dht::onPing, this, _1), + std::bind(&Dht::onFindNode, this, _1, _2, _3), + std::bind(&Dht::onGetValues, this, _1, _2, _3, _4), + std::bind(&Dht::onListen, this, _1, _2, _3, _4, _5, _6), + std::bind(&Dht::onAnnounce, this, _1, _2, _3, _4, _5), + std::bind(&Dht::onRefresh, this, _1, _2, _3, _4)) + , persistPath(config.persist_path) + , is_bootstrap(config.is_bootstrap) + , maintain_storage(config.maintain_storage) + , public_stable(config.public_stable) { scheduler.syncTime(); auto s = network_engine.getSocket(); @@ -1851,13 +2025,13 @@ Dht::Dht(std::unique_ptr&& sock, const Config& config, cons dht6.buckets.is_client = config.is_bootstrap; } - search_id = std::uniform_int_distribution{}(rd); + search_id = std::uniform_int_distribution {}(rd); uniform_duration_distribution<> time_dis {std::chrono::seconds(3), std::chrono::seconds(5)}; nextNodesConfirmation = scheduler.add(scheduler.time() + time_dis(rd), std::bind(&Dht::confirmNodes, this)); // Fill old secret - secret = std::uniform_int_distribution{}(rd); + secret = std::uniform_int_distribution {}(rd); rotateSecrets(); if (not persistPath.empty()) @@ -1872,20 +2046,20 @@ Dht::Dht(std::unique_ptr&& sock, const Config& config, cons bool Dht::neighbourhoodMaintenance(RoutingTable& list) { - //logger__DBG("neighbourhoodMaintenance"); + // logger__DBG("neighbourhoodMaintenance"); auto b = list.findBucket(myid); if (b == list.end()) return false; InfoHash id = myid; #ifdef _WIN32 - std::uniform_int_distribution rand_byte{ 0, std::numeric_limits::max() }; + std::uniform_int_distribution rand_byte {0, std::numeric_limits::max()}; #else std::uniform_int_distribution rand_byte; #endif - id[HASH_LEN-1] = rand_byte(rd); + id[HASH_LEN - 1] = rand_byte(rd); - std::bernoulli_distribution rand_trial(1./8.); + std::bernoulli_distribution rand_trial(1. / 8.); auto q = b; if (std::next(q) != list.end() && (q->nodes.empty() || rand_trial(rd))) q = std::next(q); @@ -1898,8 +2072,11 @@ Dht::neighbourhoodMaintenance(RoutingTable& list) auto n = q->randomNode(rd); if (n) { if (logger_) - logger_->d(id, n->id, "[node %s] Sending [find %s] for neighborhood maintenance", - n->toString().c_str(), id.toString().c_str()); + logger_->d(id, + n->id, + "[node %s] Sending [find %s] for neighborhood maintenance", + n->toString().c_str(), + id.toString().c_str()); /* Since our node-id is the same in both DHTs, it's probably profitable to query both families. */ network_engine.sendFindNode(n, id, network_engine.want()); @@ -1911,8 +2088,8 @@ Dht::neighbourhoodMaintenance(RoutingTable& list) bool Dht::bucketMaintenance(RoutingTable& list) { - std::bernoulli_distribution rand_trial(1./8.); - std::bernoulli_distribution rand_trial_38(1./38.); + std::bernoulli_distribution rand_trial(1. / 8.); + std::bernoulli_distribution rand_trial_38(1. / 38.); bool sent {false}; for (auto b = list.begin(); b != list.end(); ++b) { @@ -1952,14 +2129,19 @@ Dht::bucketMaintenance(RoutingTable& list) } if (logger_) - logger_->d(id, n->id, "[node %s] Sending find %s for bucket maintenance", n->toString().c_str(), id.toString().c_str()); - //auto start = scheduler.time(); - network_engine.sendFindNode(n, id, want, nullptr, [this,n](const net::Request&, bool over) { + logger_->d(id, + n->id, + "[node %s] Sending find %s for bucket maintenance", + n->toString().c_str(), + id.toString().c_str()); + // auto start = scheduler.time(); + network_engine.sendFindNode(n, id, want, nullptr, [this, n](const net::Request&, bool over) { if (over) { const auto& end = scheduler.time(); // using namespace std::chrono; // if (logger_) - // logger_->d(n->id, "[node %s] Bucket maintenance op expired after %s", n->toString().c_str(), print_duration(end-start).c_str()); + // logger_->d(n->id, "[node %s] Bucket maintenance op expired after %s", + // n->toString().c_str(), print_duration(end-start).c_str()); scheduler.edit(nextNodesConfirmation, end + Node::MAX_RESPONSE_TIME); } }); @@ -1977,8 +2159,11 @@ Dht::dataPersistence(InfoHash id) auto str = store.find(id); if (str != store.end() and now > str->second.maintenance_time) { if (logger_) - logger_->d(id, "[storage %s] Maintenance (%u values, %u bytes)", - id.toString().c_str(), str->second.valueCount(), str->second.totalSize()); + logger_->d(id, + "[storage %s] Maintenance (%u values, %u bytes)", + id.toString().c_str(), + str->second.valueCount(), + str->second.totalSize()); maintainStorage(*str); str->second.maintenance_time = now + MAX_STORAGE_MAINTENANCE_EXPIRE_TIME; scheduler.add(str->second.maintenance_time, std::bind(&Dht::dataPersistence, this, id)); @@ -1991,12 +2176,12 @@ Dht::maintainStorage(decltype(store)::value_type& storage, bool force, const Don const auto& now = scheduler.time(); size_t announce_per_af = 0; - auto maintain = [&](sa_family_t af){ + auto maintain = [&](sa_family_t af) { bool want = true; auto nodes = buckets(af).findClosestNodes(storage.first, now); if (!nodes.empty()) { if (force || storage.first.xorCmp(nodes.back()->id, myid) < 0) { - for (auto &value : storage.second.getValues()) { + for (auto& value : storage.second.getValues()) { const auto& vt = getType(value.data->type); if (force || value.created + vt.expiration > now + MAX_STORAGE_MAINTENANCE_EXPIRE_TIME) { // gotta put that value there @@ -2023,7 +2208,7 @@ Dht::maintainStorage(decltype(store)::value_type& storage, bool force, const Don } time_point -Dht::periodic(const uint8_t *buf, size_t buflen, SockAddr from, const time_point& now) +Dht::periodic(const uint8_t* buf, size_t buflen, SockAddr from, const time_point& now) { scheduler.syncTime(now); if (buflen) { @@ -2085,7 +2270,11 @@ Dht::bootstrap() } } catch (const std::exception& e) { if (logger_) - logger_->e(myid, "Unable to resolve %s:%s: %s", boootstrap.first.c_str(), boootstrap.second.c_str(), e.what()); + logger_->e(myid, + "Unable to resolve %s:%s: %s", + boootstrap.first.c_str(), + boootstrap.second.c_str(), + e.what()); } } scheduler.cancel(bootstrapJob); @@ -2139,9 +2328,8 @@ Dht::confirmNodes() case is roughly 27 seconds, assuming the table is 22 bits deep. We want to keep a margin for neighborhood maintenance, so keep this within 25 seconds. */ - auto time_dis = soon - ? uniform_duration_distribution<> {seconds(5) , seconds(25)} - : uniform_duration_distribution<> {seconds(60), seconds(180)}; + auto time_dis = soon ? uniform_duration_distribution<> {seconds(5), seconds(25)} + : uniform_duration_distribution<> {seconds(60), seconds(180)}; auto confirm_nodes_time = now + time_dis(rd); scheduler.edit(nextNodesConfirmation, confirm_nodes_time); @@ -2165,7 +2353,7 @@ Dht::exportValues() const pk.pack(v.created.time_since_epoch().count()); v.data->msgpack_pack(pk); } - ve.second = {buffer.data(), buffer.data()+buffer.size()}; + ve.second = {buffer.data(), buffer.data() + buffer.size()}; e.push_back(std::move(ve)); } return e; @@ -2182,7 +2370,7 @@ Dht::importValues(const std::vector& import) try { msgpack::unpacked msg; - msgpack::unpack(msg, (const char*)value.second.data(), value.second.size()); + msgpack::unpack(msg, (const char*) value.second.data(), value.second.size()); auto valarr = msg.get(); if (valarr.type != msgpack::type::ARRAY) throw msgpack::type_error(); @@ -2193,7 +2381,8 @@ Dht::importValues(const std::vector& import) time_point val_time; Value tmp_val; try { - val_time = time_point{time_point::duration{valel.via.array.ptr[0].as()}}; + val_time = time_point { + time_point::duration {valel.via.array.ptr[0].as()}}; tmp_val.msgpack_unpack(valel.via.array.ptr[1]); } catch (const std::exception&) { if (logger_) @@ -2211,7 +2400,6 @@ Dht::importValues(const std::vector& import) } } - std::vector Dht::exportNodes() const { @@ -2230,13 +2418,15 @@ Dht::exportNodes() const nodes.emplace_back(n->exportNode()); } for (auto b = dht4.buckets.begin(); b != dht4.buckets.end(); ++b) { - if (b == b4) continue; + if (b == b4) + continue; for (auto& n : b->nodes) if (n->isGood(now)) nodes.emplace_back(n->exportNode()); } for (auto b = dht6.buckets.begin(); b != dht6.buckets.end(); ++b) { - if (b == b6) continue; + if (b == b6) + continue; for (auto& n : b->nodes) if (n->isGood(now)) nodes.emplace_back(n->exportNode()); @@ -2261,21 +2451,25 @@ Dht::pingNode(SockAddr sa, DoneCallbackSimple&& cb) logger_->debug("Sending ping to {}", sa); auto& count = dht(sa.getFamily()).pending_pings; count++; - network_engine.sendPing(std::move(sa), [&count,cb](const net::Request&, net::RequestAnswer&&) { - count--; - if (cb) - cb(true); - }, [&count,cb](const net::Request&, bool last){ - if (last) { + network_engine.sendPing( + std::move(sa), + [&count, cb](const net::Request&, net::RequestAnswer&&) { count--; if (cb) - cb(false); - } - }); + cb(true); + }, + [&count, cb](const net::Request&, bool last) { + if (last) { + count--; + if (cb) + cb(false); + } + }); } void -Dht::onError(Sp req, net::DhtProtocolException e) { +Dht::onError(Sp req, net::DhtProtocolException e) +{ const auto& node = req->node; if (e.getCode() == net::DhtProtocolException::UNAUTHORIZED) { if (logger_) @@ -2284,7 +2478,8 @@ Dht::onError(Sp req, net::DhtProtocolException e) { for (auto& srp : searches(node->getFamily())) { auto& sr = srp.second; for (auto& n : sr->nodes) { - if (n->node != node) continue; + if (n->node != node) + continue; n->token.clear(); n->last_get_reply = time_point::min(); searchSendGetValues(sr); @@ -2331,10 +2526,8 @@ Dht::onGetValues(Sp node, const InfoHash& hash, want_t, const Query& query if (not hash) { if (logger_) logger_->w("[node %s] Eek! Got get_values with no info_hash", node->toString().c_str()); - throw net::DhtProtocolException { - net::DhtProtocolException::NON_AUTHORITATIVE_INFORMATION, - net::DhtProtocolException::GET_NO_INFOHASH - }; + throw net::DhtProtocolException {net::DhtProtocolException::NON_AUTHORITATIVE_INFORMATION, + net::DhtProtocolException::GET_NO_INFOHASH}; } const auto& now = scheduler.time(); net::RequestAnswer answer {}; @@ -2350,10 +2543,8 @@ Dht::onGetValues(Sp node, const InfoHash& hash, want_t, const Query& query return answer; } -void Dht::onGetValuesDone(const Sp& node, - net::RequestAnswer& a, - Sp& sr, - const Sp& orig_query) +void +Dht::onGetValuesDone(const Sp& node, net::RequestAnswer& a, Sp& sr, const Sp& orig_query) { if (not sr) { if (logger_) @@ -2368,12 +2559,16 @@ void Dht::onGetValuesDone(const Sp& node, if (not a.ntoken.empty()) { if (not a.values.empty() or not a.fields.empty()) { if (logger_) - logger_->d(sr->id, node->id, "[search %s] [node %s] Found %u values", - sr->id.toString().c_str(), node->toString().c_str(), a.values.size()); + logger_->d(sr->id, + node->id, + "[search %s] [node %s] Found %u values", + sr->id.toString().c_str(), + node->toString().c_str(), + a.values.size()); for (auto& getp : sr->callbacks) { /* call all callbacks for this search */ auto& get = getp.second; - if (not (get.get_cb or get.query_cb) or - (orig_query and get.query and not get.query->isSatisfiedBy(*orig_query))) + if (not(get.get_cb or get.query_cb) + or (orig_query and get.query and not get.query->isSatisfiedBy(*orig_query))) continue; if (get.query_cb) { /* in case of a request with query */ @@ -2383,7 +2578,8 @@ void Dht::onGetValuesDone(const Sp& node, std::vector> fields; fields.reserve(a.values.size()); for (const auto& v : a.values) - fields.emplace_back(std::make_shared(*v, orig_query ? orig_query->select : Select {})); + fields.emplace_back( + std::make_shared(*v, orig_query ? orig_query->select : Select {})); get.query_cb(fields); } } else if (get.get_cb) { /* in case of a vanilla get request */ @@ -2399,21 +2595,21 @@ void Dht::onGetValuesDone(const Sp& node, /* callbacks for local search listeners */ /*std::vector>>> tmp_lists; for (auto& l : sr->listeners) { - if (!l.second.get_cb or (orig_query and l.second.query and not l.second.query->isSatisfiedBy(*orig_query))) - continue; - std::vector> tmp; - for (const auto& v : a.values) - if (not l.second.filter or l.second.filter(*v)) - tmp.emplace_back(v); - if (not tmp.empty()) + if (!l.second.get_cb or (orig_query and l.second.query and not + l.second.query->isSatisfiedBy(*orig_query))) continue; std::vector> tmp; for (const auto& v : + a.values) if (not l.second.filter or l.second.filter(*v)) tmp.emplace_back(v); if (not tmp.empty()) tmp_lists.emplace_back(l.second.get_cb, std::move(tmp)); } for (auto& l : tmp_lists) l.first(l.second, false);*/ } else if (not a.expired_values.empty()) { if (logger_) - logger_->w(sr->id, node->id, "[search %s] [node %s] %u expired values", - sr->id.toString().c_str(), node->toString().c_str(), a.expired_values.size()); + logger_->w(sr->id, + node->id, + "[search %s] [node %s] %u expired values", + sr->id.toString().c_str(), + node->toString().c_str(), + a.expired_values.size()); } } else { if (logger_) @@ -2435,15 +2631,18 @@ Dht::onListen(Sp node, const InfoHash& hash, const Blob& token, size_t soc if (not hash) { if (logger_) logger_->w(node->id, "[node %s] Listen with no info_hash", node->toString().c_str()); - throw net::DhtProtocolException { - net::DhtProtocolException::NON_AUTHORITATIVE_INFORMATION, - net::DhtProtocolException::LISTEN_NO_INFOHASH - }; + throw net::DhtProtocolException {net::DhtProtocolException::NON_AUTHORITATIVE_INFORMATION, + net::DhtProtocolException::LISTEN_NO_INFOHASH}; } if (not tokenMatch(token, node->getAddr())) { if (logger_) - logger_->w(hash, node->id, "[node %s] Incorrect token %s for 'listen'", node->toString().c_str(), hash.toString().c_str()); - throw net::DhtProtocolException {net::DhtProtocolException::UNAUTHORIZED, net::DhtProtocolException::LISTEN_WRONG_TOKEN}; + logger_->w(hash, + node->id, + "[node %s] Incorrect token %s for 'listen'", + node->toString().c_str(), + hash.toString().c_str()); + throw net::DhtProtocolException {net::DhtProtocolException::UNAUTHORIZED, + net::DhtProtocolException::LISTEN_WRONG_TOKEN}; } Query q = query; storageAddListener(hash, node, socket_id, std::move(q), version); @@ -2466,24 +2665,27 @@ Dht::onListenDone(const Sp& /* node */, net::RequestAnswer& /* answer */, net::RequestAnswer Dht::onAnnounce(Sp n, - const InfoHash& hash, - const Blob& token, - const std::vector>& values, - const time_point& creation_date) + const InfoHash& hash, + const Blob& token, + const std::vector>& values, + const time_point& creation_date) { auto& node = *n; if (not hash) { if (logger_) logger_->w(node.id, "Put with no info_hash"); - throw net::DhtProtocolException { - net::DhtProtocolException::NON_AUTHORITATIVE_INFORMATION, - net::DhtProtocolException::PUT_NO_INFOHASH - }; + throw net::DhtProtocolException {net::DhtProtocolException::NON_AUTHORITATIVE_INFORMATION, + net::DhtProtocolException::PUT_NO_INFOHASH}; } if (!tokenMatch(token, node.getAddr())) { if (logger_) - logger_->w(hash, node.id, "[node %s] Incorrect token %s for 'put'", node.toString().c_str(), hash.toString().c_str()); - throw net::DhtProtocolException {net::DhtProtocolException::UNAUTHORIZED, net::DhtProtocolException::PUT_WRONG_TOKEN}; + logger_->w(hash, + node.id, + "[node %s] Incorrect token %s for 'put'", + node.toString().c_str(), + hash.toString().c_str()); + throw net::DhtProtocolException {net::DhtProtocolException::UNAUTHORIZED, + net::DhtProtocolException::PUT_WRONG_TOKEN}; } { // We store a value only if we think we're part of the @@ -2491,7 +2693,10 @@ Dht::onAnnounce(Sp n, auto closest_nodes = buckets(node.getFamily()).findClosestNodes(hash, scheduler.time(), SEARCH_NODES); if (closest_nodes.size() >= TARGET_NODES and hash.xorCmp(closest_nodes.back()->id, myid) < 0) { if (logger_) - logger_->w(hash, node.id, "[node %s] Announce too far from the target. Dropping value.", node.toString().c_str()); + logger_->w(hash, + node.id, + "[node %s] Announce too far from the target. Dropping value.", + node.toString().c_str()); return {}; } } @@ -2501,10 +2706,8 @@ Dht::onAnnounce(Sp n, if (v->id == Value::INVALID_ID) { if (logger_) logger_->w(hash, node.id, "[value %s] Incorrect value id", hash.toString().c_str()); - throw net::DhtProtocolException { - net::DhtProtocolException::NON_AUTHORITATIVE_INFORMATION, - net::DhtProtocolException::PUT_INVALID_ID - }; + throw net::DhtProtocolException {net::DhtProtocolException::NON_AUTHORITATIVE_INFORMATION, + net::DhtProtocolException::PUT_INVALID_ID}; } auto lv = getLocalById(hash, v->id); Sp vc = v; @@ -2512,18 +2715,29 @@ Dht::onAnnounce(Sp n, if (*lv == *vc) { storageRefresh(hash, v->id); if (logger_) - logger_->d(hash, node.id, "[store %s] [node %s] Refreshed value %016" PRIx64, hash.toString().c_str(), node.toString().c_str(), v->id); + logger_->d(hash, + node.id, + "[store %s] [node %s] Refreshed value %016" PRIx64, + hash.toString().c_str(), + node.toString().c_str(), + v->id); } else { const auto& type = getType(lv->type); if (type.editPolicy(hash, lv, vc, node.id, node.getAddr())) { if (logger_) - logger_->d(hash, node.id, "[store %s] Editing %s", - hash.toString().c_str(), vc->toString().c_str()); + logger_->d(hash, + node.id, + "[store %s] Editing %s", + hash.toString().c_str(), + vc->toString().c_str()); storageStore(hash, vc, created, node.getAddr()); } else { if (logger_) - logger_->d(hash, node.id, "[store %s] Rejecting edition of %s because of storage policy", - hash.toString().c_str(), vc->toString().c_str()); + logger_->d(hash, + node.id, + "[store %s] Rejecting edition of %s because of storage policy", + hash.toString().c_str(), + vc->toString().c_str()); } } } else { @@ -2531,12 +2745,16 @@ Dht::onAnnounce(Sp n, const auto& type = getType(vc->type); if (type.storePolicy(hash, vc, node.id, node.getAddr())) { // if (logger_) - // logger_->d(hash, node.id, "[store %s] Storing %s", hash.toString().c_str(), std::to_string(vc->id).c_str()); + // logger_->d(hash, node.id, "[store %s] Storing %s", hash.toString().c_str(), + // std::to_string(vc->id).c_str()); storageStore(hash, vc, created, node.getAddr()); } else { if (logger_) - logger_->d(hash, node.id, "[store %s] Rejecting storage of %s", - hash.toString().c_str(), vc->toString().c_str()); + logger_->d(hash, + node.id, + "[store %s] Rejecting storage of %s", + hash.toString().c_str(), + vc->toString().c_str()); } } } @@ -2550,16 +2768,28 @@ Dht::onRefresh(Sp node, const InfoHash& hash, const Blob& token, const Val if (not tokenMatch(token, node->getAddr())) { if (logger_) - logger_->w(hash, node->id, "[node %s] Incorrect token %s for 'put'", node->toString().c_str(), hash.toString().c_str()); + logger_->w(hash, + node->id, + "[node %s] Incorrect token %s for 'put'", + node->toString().c_str(), + hash.toString().c_str()); throw DhtProtocolException {DhtProtocolException::UNAUTHORIZED, DhtProtocolException::PUT_WRONG_TOKEN}; } if (storageRefresh(hash, vid)) { if (logger_) - logger_->d(hash, node->id, "[store %s] [node %s] Refreshed value %016" PRIx64, hash.toString().c_str(), node->toString().c_str(), vid); + logger_->d(hash, + node->id, + "[store %s] [node %s] Refreshed value %016" PRIx64, + hash.toString().c_str(), + node->toString().c_str(), + vid); } else { if (logger_) - logger_->d(hash, node->id, "[store %s] [node %s] Got refresh for unknown value", - hash.toString().c_str(), node->toString().c_str()); + logger_->d(hash, + node->id, + "[store %s] [node %s] Got refresh for unknown value", + hash.toString().c_str(), + node->toString().c_str()); throw DhtProtocolException {DhtProtocolException::NOT_FOUND, DhtProtocolException::STORAGE_NOT_FOUND}; } return {}; @@ -2581,11 +2811,14 @@ Dht::storageRefresh(const InfoHash& id, Value::Id vid) for (const auto& node_listeners : st.listeners) { for (const auto& l : node_listeners.second) { if (logger_) - logger_->w(id, node_listeners.first->id, "[store %s] [node %s] Sending refresh", - id.toString().c_str(), - node_listeners.first->toString().c_str()); + logger_->w(id, + node_listeners.first->id, + "[store %s] [node %s] Sending refresh", + id.toString().c_str(), + node_listeners.first->toString().c_str()); Blob ntoken = makeToken(node_listeners.first->getAddr(), false); - network_engine.tellListenerRefreshed(node_listeners.first, l.first, id, ntoken, ids, l.second.version); + network_engine + .tellListenerRefreshed(node_listeners.first, l.first, id, ntoken, ids, l.second.version); } } } @@ -2594,7 +2827,8 @@ Dht::storageRefresh(const InfoHash& id, Value::Id vid) if (expiration.first) { scheduler.cancel(expiration.first->expiration_job); if (expiration.second != time_point::max()) { - expiration.first->expiration_job = scheduler.add(expiration.second, std::bind(&Dht::expireStorage, this, id)); + expiration.first->expiration_job = scheduler.add(expiration.second, + std::bind(&Dht::expireStorage, this, id)); } } return true; @@ -2606,14 +2840,17 @@ void Dht::onAnnounceDone(const Sp& node, net::RequestAnswer& answer, Sp& sr) { if (logger_) - logger_->d(sr->id, node->id, "[search %s] [node %s] Got reply to put!", - sr->id.toString().c_str(), node->toString().c_str()); + logger_->d(sr->id, + node->id, + "[search %s] [node %s] Got reply to put!", + sr->id.toString().c_str(), + node->toString().c_str()); searchSendGetValues(sr); sr->checkAnnounced(answer.vid); } - -struct DhtState { +struct DhtState +{ unsigned v {1}; InfoHash id; std::vector nodes; @@ -2643,14 +2880,14 @@ Dht::loadState(const std::string& path) msgpack::unpacker pac; { // Read whole file - std::ifstream file(path, std::ios::binary|std::ios::ate); + std::ifstream file(path, std::ios::binary | std::ios::ate); if (!file.is_open()) { return; } auto size = file.tellg(); - file.seekg (0, std::ios::beg); + file.seekg(0, std::ios::beg); pac.reserve_buffer(size); - file.read (pac.buffer(), size); + file.read(pac.buffer(), size); pac.buffer_consumed(size); } // Import nodes @@ -2673,4 +2910,4 @@ Dht::loadState(const std::string& path) } } -} +} // namespace dht diff --git a/src/dht_proxy_client.cpp b/src/dht_proxy_client.cpp index 5e1756fd..285f0905 100644 --- a/src/dht_proxy_client.cpp +++ b/src/dht_proxy_client.cpp @@ -1,21 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * Adrien Béraud - * Vsevolod Ivanov - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "dht_proxy_client.h" #include "dhtrunner.h" diff --git a/src/dht_proxy_server.cpp b/src/dht_proxy_server.cpp index d36bbe11..bac2be3d 100644 --- a/src/dht_proxy_server.cpp +++ b/src/dht_proxy_server.cpp @@ -1,21 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * Adrien Béraud - * Vsevolod Ivanov - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" diff --git a/src/dhtrunner.cpp b/src/dhtrunner.cpp index f9040ae4..55eb4ef7 100644 --- a/src/dhtrunner.cpp +++ b/src/dhtrunner.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" diff --git a/src/http.cpp b/src/http.cpp index 61dd8e49..c7f72cdd 100644 --- a/src/http.cpp +++ b/src/http.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "http.h" #include "logger.h" diff --git a/src/indexation/pht.cpp b/src/indexation/pht.cpp index 921778c0..15df96b7 100644 --- a/src/indexation/pht.cpp +++ b/src/indexation/pht.cpp @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "indexation/pht.h" #include "rng.h" @@ -28,7 +13,9 @@ namespace indexation { * * @return string that represent the blob into a readable way */ -static std::string blobToString(const Blob &bl) { +static std::string +blobToString(const Blob& bl) +{ std::ostringstream ss; auto bn = bl.size() % 8; auto n = bl.size() / 8; @@ -36,13 +23,15 @@ static std::string blobToString(const Blob &bl) { for (size_t i = 0; i < bl.size(); i++) ss << std::bitset<8>(bl[i]) << " "; if (bn) - for (unsigned b=0; b < bn; b++) - ss << (char)((bl[n] & (1 << (7 - b))) ? '1':'0'); + for (unsigned b = 0; b < bn; b++) + ss << (char) ((bl[n] & (1 << (7 - b))) ? '1' : '0'); return ss.str(); } -std::string Prefix::toString() const { +std::string +Prefix::toString() const +{ std::ostringstream ss; ss << "Prefix : " << std::endl << "\tContent_ : \""; @@ -56,20 +45,19 @@ std::string Prefix::toString() const { return ss.str(); } -void Pht::Cache::insert(const Prefix& p) { +void +Pht::Cache::insert(const Prefix& p) +{ size_t i = 0; auto now = clock::now(); std::shared_ptr curr_node; - while ((leaves_.size() > 0 - and leaves_.begin()->first + NODE_EXPIRE_TIME < now) - or leaves_.size() > MAX_ELEMENT) { - + while ((leaves_.size() > 0 and leaves_.begin()->first + NODE_EXPIRE_TIME < now) or leaves_.size() > MAX_ELEMENT) { leaves_.erase(leaves_.begin()); } - if (not (curr_node = root_.lock()) ) { + if (not(curr_node = root_.lock())) { /* Root does not exist, need to create one*/ curr_node = std::make_shared(); root_ = curr_node; @@ -78,10 +66,9 @@ void Pht::Cache::insert(const Prefix& p) { curr_node->last_reply = now; /* Iterate through all bit of the Blob */ - for ( i = 0; i < p.size_; i++ ) { - + for (i = 0; i < p.size_; i++) { /* According to the bit define which node is the next one */ - auto& next = ( p.isContentBitActive(i) ) ? curr_node->right_child : curr_node->left_child; + auto& next = (p.isContentBitActive(i)) ? curr_node->right_child : curr_node->left_child; /** * If lock, node exists @@ -101,42 +88,43 @@ void Pht::Cache::insert(const Prefix& p) { } /* Insert the leaf (curr_node) into the multimap */ - leaves_.emplace(std::move(now), std::move(curr_node) ); + leaves_.emplace(std::move(now), std::move(curr_node)); } -int Pht::Cache::lookup(const Prefix& p) { +int +Pht::Cache::lookup(const Prefix& p) +{ int pos = -1; auto now = clock::now(), last_node_time = now; /* Before lookup remove the useless one [i.e. too old] */ - while ( leaves_.size() > 0 - and leaves_.begin()->first + NODE_EXPIRE_TIME < now ) { - + while (leaves_.size() > 0 and leaves_.begin()->first + NODE_EXPIRE_TIME < now) { leaves_.erase(leaves_.begin()); } auto next = root_; std::shared_ptr curr_node; - while ( auto n = next.lock() ) { + while (auto n = next.lock()) { ++pos; /* Safe since pos is equal to 0 until here */ - if ( (unsigned) pos >= p.content_.size() * 8) break; + if ((unsigned) pos >= p.content_.size() * 8) + break; curr_node = n; last_node_time = curr_node->last_reply; curr_node->last_reply = now; /* Get the Prefix bit by bit, starting from left */ - next = ( p.isContentBitActive(pos) ) ? curr_node->right_child : curr_node->left_child; + next = (p.isContentBitActive(pos)) ? curr_node->right_child : curr_node->left_child; } - if ( pos >= 0 ) { + if (pos >= 0) { auto to_erase = leaves_.find(last_node_time); - if ( to_erase != leaves_.end() ) - leaves_.erase( to_erase ); + if (to_erase != leaves_.end()) + leaves_.erase(to_erase); - leaves_.emplace( std::move(now), std::move(curr_node) ); + leaves_.emplace(std::move(now), std::move(curr_node)); } return pos; @@ -145,19 +133,25 @@ int Pht::Cache::lookup(const Prefix& p) { const ValueType& IndexEntry::TYPE = ValueType::USER_DATA; constexpr std::chrono::minutes Pht::Cache::NODE_EXPIRE_TIME; -void Pht::lookupStep(Prefix p, std::shared_ptr lo, std::shared_ptr hi, - std::shared_ptr>> vals, - LookupCallbackWrapper cb, DoneCallbackSimple done_cb, - std::shared_ptr max_common_prefix_len, - int start, bool all_values) +void +Pht::lookupStep(Prefix p, + std::shared_ptr lo, + std::shared_ptr hi, + std::shared_ptr>> vals, + LookupCallbackWrapper cb, + DoneCallbackSimple done_cb, + std::shared_ptr max_common_prefix_len, + int start, + bool all_values) { - struct node_lookup_result { + struct node_lookup_result + { bool done {false}; bool is_pht {false}; }; /* start could be under 0 but after the compare it to 0 it always will be unsigned, so we can cast it*/ - auto mid = (start >= 0) ? (unsigned) start : (*lo + *hi)/2; + auto mid = (start >= 0) ? (unsigned) start : (*lo + *hi) / 2; auto first_res = std::make_shared(); auto second_res = std::make_shared(); @@ -167,8 +161,7 @@ void Pht::lookupStep(Prefix p, std::shared_ptr lo, std::shared_ptr hi, if (not ok) { if (done_cb) done_cb(false); - } - else if (is_leaf or *lo > *hi) { + } else if (is_leaf or *lo > *hi) { // leaf node Prefix to_insert = p.getPrefix(mid); cache_.insert(to_insert); @@ -188,7 +181,7 @@ void Pht::lookupStep(Prefix p, std::shared_ptr lo, std::shared_ptr hi, done_cb(true); } else if (first_res->is_pht) { // internal node - *lo = mid+1; + *lo = mid + 1; lookupStep(p, lo, hi, vals, cb, done_cb, max_common_prefix_len, -1, all_values); } else { // first get failed before second. @@ -205,8 +198,7 @@ void Pht::lookupStep(Prefix p, std::shared_ptr lo, std::shared_ptr hi, auto on_get = [=](const std::shared_ptr& value, std::shared_ptr res) { if (value->user_type == canary_) { res->is_pht = true; - } - else { + } else { IndexEntry entry; entry.unpackValue(*value); @@ -224,8 +216,7 @@ void Pht::lookupStep(Prefix p, std::shared_ptr lo, std::shared_ptr hi, if (vals->empty()) { vals->emplace_back(std::make_shared(entry)); *max_common_prefix_len = common_bits; - } - else { + } else { if (common_bits == *max_common_prefix_len) /* this is the max so far */ vals->emplace_back(std::make_shared(entry)); else if (common_bits > *max_common_prefix_len) { /* new max found! */ @@ -241,50 +232,54 @@ void Pht::lookupStep(Prefix p, std::shared_ptr lo, std::shared_ptr hi, return true; }; - dht_->get(p.getPrefix(mid).hash(), - std::bind(on_get, std::placeholders::_1, first_res), + dht_->get( + p.getPrefix(mid).hash(), + std::bind(on_get, std::placeholders::_1, first_res), + [=](bool ok) { + if (not ok) { + // DHT failed + first_res->done = true; + if (done_cb and second_res->done) + on_done(false); + } else { + if (not first_res->is_pht) { + // Not a PHT node. + *hi = mid - 1; + lookupStep(p, lo, hi, vals, cb, done_cb, max_common_prefix_len, -1, all_values); + } else { + first_res->done = true; + if (second_res->done or mid >= p.size_ - 1) + on_done(true); + } + } + }, + pht_filter); + + if (mid < p.size_ - 1) + dht_->get( + p.getPrefix(mid + 1).hash(), + std::bind(on_get, std::placeholders::_1, second_res), [=](bool ok) { if (not ok) { // DHT failed - first_res->done = true; - if (done_cb and second_res->done) + second_res->done = true; + if (done_cb and first_res->done) on_done(false); + } else { + second_res->done = true; + if (first_res->done) + on_done(true); } - else { - if (not first_res->is_pht) { - // Not a PHT node. - *hi = mid-1; - lookupStep(p, lo, hi, vals, cb, done_cb, max_common_prefix_len, -1, all_values); - } else { - first_res->done = true; - if (second_res->done or mid >= p.size_ - 1) - on_done(true); - } - } - }, pht_filter); - - if (mid < p.size_ - 1) - dht_->get(p.getPrefix(mid+1).hash(), - std::bind(on_get, std::placeholders::_1, second_res), - [=](bool ok) { - if (not ok) { - // DHT failed - second_res->done = true; - if (done_cb and first_res->done) - on_done(false); - } - else { - second_res->done = true; - if (first_res->done) - on_done(true); - } - }, pht_filter); + }, + pht_filter); } else { on_done(true); } } -void Pht::lookup(Key k, Pht::LookupCallback cb, DoneCallbackSimple done_cb, bool exact_match) { +void +Pht::lookup(Key k, Pht::LookupCallback cb, DoneCallbackSimple done_cb, bool exact_match) +{ auto prefix = linearize(k); auto values = std::make_shared>>(); @@ -292,32 +287,38 @@ void Pht::lookup(Key k, Pht::LookupCallback cb, DoneCallbackSimple done_cb, bool auto hi = std::make_shared(prefix.size_); std::shared_ptr max_common_prefix_len = not exact_match ? std::make_shared(0) : nullptr; - lookupStep(prefix, lo, hi, values, + lookupStep( + prefix, + lo, + hi, + values, [=](std::vector>& entries, const Prefix& p) { std::vector> vals(entries.size()); - std::transform(entries.begin(), entries.end(), vals.begin(), - [](const std::shared_ptr& ie) { - return std::make_shared(ie->value); + std::transform(entries.begin(), entries.end(), vals.begin(), [](const std::shared_ptr& ie) { + return std::make_shared(ie->value); }); cb(vals, p); - }, done_cb, max_common_prefix_len, cache_.lookup(prefix)); + }, + done_cb, + max_common_prefix_len, + cache_.lookup(prefix)); } -void Pht::updateCanary(Prefix p) { +void +Pht::updateCanary(Prefix p) +{ // TODO: change this... copy value dht::Value canary_value; canary_value.user_type = canary_; - dht_->put(p.hash(), std::move(canary_value), - [=](bool){ - static std::bernoulli_distribution d(0.5); - std::random_device rd; - if (p.size_ and d(rd)) - updateCanary(p.getPrefix(-1)); - } - ); + dht_->put(p.hash(), std::move(canary_value), [=](bool) { + static std::bernoulli_distribution d(0.5); + std::random_device rd; + if (p.size_ and d(rd)) + updateCanary(p.getPrefix(-1)); + }); if (p.size_) { dht::Value canary_second_value; @@ -326,67 +327,76 @@ void Pht::updateCanary(Prefix p) { } } -void Pht::insert(const Prefix& kp, IndexEntry entry, std::shared_ptr lo, std::shared_ptr hi, time_point time_p, - bool check_split, DoneCallbackSimple done_cb) { - - if (time_p + ValueType::USER_DATA.expiration < clock::now()) return; +void +Pht::insert(const Prefix& kp, + IndexEntry entry, + std::shared_ptr lo, + std::shared_ptr hi, + time_point time_p, + bool check_split, + DoneCallbackSimple done_cb) +{ + if (time_p + ValueType::USER_DATA.expiration < clock::now()) + return; auto vals = std::make_shared>>(); auto final_prefix = std::make_shared(); - lookupStep(kp, lo, hi, vals, - [=](std::vector>&, Prefix p) { - *final_prefix = Prefix(p); - }, - [=](bool ok){ + lookupStep( + kp, + lo, + hi, + vals, + [=](std::vector>&, Prefix p) { *final_prefix = Prefix(p); }, + [=](bool ok) { if (not ok) { if (done_cb) done_cb(false); } else { - RealInsertCallback real_insert = [=](const Prefix& p, IndexEntry entry) { updateCanary(p); checkPhtUpdate(p, entry, time_p); cache_.insert(p); - dht_->put(p.hash(), std::move(entry), done_cb , time_p); + dht_->put(p.hash(), std::move(entry), done_cb, time_p); }; - if ( not check_split or final_prefix->size_ == kp.size_ ) { + if (not check_split or final_prefix->size_ == kp.size_) { real_insert(*final_prefix, std::move(entry)); } else { - if ( vals->size() < MAX_NODE_ENTRY_COUNT ) { + if (vals->size() < MAX_NODE_ENTRY_COUNT) { getRealPrefix(final_prefix, std::move(entry), real_insert); - } - else { + } else { split(*final_prefix, *vals, entry, real_insert); } } } - }, nullptr, cache_.lookup(kp), true); + }, + nullptr, + cache_.lookup(kp), + true); } -Prefix Pht::zcurve(const std::vector& all_prefix) const { +Prefix +Pht::zcurve(const std::vector& all_prefix) const +{ Prefix p; - if ( all_prefix.size() == 1 ) + if (all_prefix.size() == 1) return all_prefix[0]; /* All prefix got the same size (thanks to padding) */ size_t prefix_size = all_prefix[0].content_.size(); /* Loop on all uint8_t of the input prefix */ - for ( size_t j = 0, bit = 0; j < prefix_size; j++) { - + for (size_t j = 0, bit = 0; j < prefix_size; j++) { uint8_t mask = 0x80; /* For each of the 8 bits of the input uint8_t */ - for ( int i = 0; i < 8; ) { - + for (int i = 0; i < 8;) { uint8_t flags = 0; uint8_t content = 0; /* For each bit of the output uint8_t */ - for ( int k = 0 ; k < 8; k++ ) { - + for (int k = 0; k < 8; k++) { auto diff = k - i; /*get the content 'c', and the flag 'f' of the input prefix */ @@ -395,12 +405,16 @@ Prefix Pht::zcurve(const std::vector& all_prefix) const { /* Move this bit at the right position according to the diff and merge it into content and flags in the same way */ - content |= ( diff >= 0 ) ? c >> diff : c << std::abs(diff); - flags |= ( diff >= 0 ) ? f >> diff : f << std::abs(diff); + content |= (diff >= 0) ? c >> diff : c << std::abs(diff); + flags |= (diff >= 0) ? f >> diff : f << std::abs(diff); /* If we are on the last prefix of the vector get back to the first and ,move the mask in order to get the n + 1nth bit */ - if ( ++bit == all_prefix.size() ) { bit = 0; ++i; mask >>= 1; } + if (++bit == all_prefix.size()) { + bit = 0; + ++i; + mask >>= 1; + } } /* Add the next flags + content to the output prefix */ @@ -413,19 +427,26 @@ Prefix Pht::zcurve(const std::vector& all_prefix) const { return p; } -Prefix Pht::linearize(Key k) const { - if (not validKey(k)) { throw std::invalid_argument(INVALID_KEY); } +Prefix +Pht::linearize(Key k) const +{ + if (not validKey(k)) { + throw std::invalid_argument(INVALID_KEY); + } std::vector all_prefix; all_prefix.reserve(k.size()); /* Get the max size of the keyspec and take it for size limit (for padding) */ - auto max = std::max_element(keySpec_.begin(), keySpec_.end(), - [](const std::pair& a, const std::pair& b) { - return a.second < b.second; - })->second + 1; + auto max = std::max_element(keySpec_.begin(), + keySpec_.end(), + [](const std::pair& a, const std::pair& b) { + return a.second < b.second; + }) + ->second + + 1; - for ( auto const& it : k ) { + for (auto const& it : k) { Prefix p = Blob {it.second.begin(), it.second.end()}; p.addPaddingContent(max); p.updateFlags(); @@ -436,18 +457,22 @@ Prefix Pht::linearize(Key k) const { return zcurve(all_prefix); } -void Pht::getRealPrefix(const std::shared_ptr& p, IndexEntry entry, RealInsertCallback end_cb ) +void +Pht::getRealPrefix(const std::shared_ptr& p, IndexEntry entry, RealInsertCallback end_cb) { - if ( p->size_ == 0 ) { + if (p->size_ == 0) { end_cb(*p, std::move(entry)); return; } - struct OpState { + struct OpState + { unsigned entry_count {0}; /* Total number of data on 3 nodes */ - unsigned ended {0}; /* How many ops have ended */ + unsigned ended {0}; /* How many ops have ended */ Prefix parent; - OpState(Prefix p) : parent(p) {} + OpState(Prefix p) + : parent(p) + {} }; auto op_state = std::make_shared(p->getPrefix(-1)); @@ -456,16 +481,16 @@ void Pht::getRealPrefix(const std::shared_ptr& p, IndexEntry entry, Real }; /* Lambda will count total number of data node */ - auto count = [=]( const std::shared_ptr& value ) { + auto count = [=](const std::shared_ptr& value) { if (value->user_type != canary_) op_state->entry_count++; return true; }; - auto on_done = [=] ( bool ) { + auto on_done = [=](bool) { op_state->ended++; /* Only the last one do the CallBack*/ - if (op_state->ended == 3) { + if (op_state->ended == 3) { if (op_state->entry_count < MAX_NODE_ENTRY_COUNT) end_cb(op_state->parent, std::move(entry)); else @@ -473,34 +498,25 @@ void Pht::getRealPrefix(const std::shared_ptr& p, IndexEntry entry, Real } }; - dht_->get(op_state->parent.hash(), - count, - on_done, - pht_filter - ); + dht_->get(op_state->parent.hash(), count, on_done, pht_filter); - dht_->get(p->hash(), - count, - on_done, - pht_filter - ); + dht_->get(p->hash(), count, on_done, pht_filter); - dht_->get(p->getSibling().hash(), - count, - on_done, - pht_filter - ); + dht_->get(p->getSibling().hash(), count, on_done, pht_filter); } -void Pht::checkPhtUpdate(Prefix p, IndexEntry entry, time_point time_p) { - +void +Pht::checkPhtUpdate(Prefix p, IndexEntry entry, time_point time_p) +{ Prefix full = entry.prefix; - if ( p.content_.size() * 8 >= full.content_.size() * 8 ) return; + if (p.content_.size() * 8 >= full.content_.size() * 8) + return; - auto next_prefix = full.getPrefix( p.size_ + 1 ); + auto next_prefix = full.getPrefix(p.size_ + 1); - dht_->listen(next_prefix.hash(), - [=](const std::shared_ptr &value) { + dht_->listen( + next_prefix.hash(), + [=](const std::shared_ptr& value) { if (value->user_type == canary_) { insert(full, entry, std::make_shared(0), std::make_shared(full.size_), time_p, false, nullptr); @@ -513,23 +529,27 @@ void Pht::checkPhtUpdate(Prefix p, IndexEntry entry, time_point time_p) { [=](const dht::Value& v) { /* Filter value v thats start with the same name as ours */ return v.user_type.compare(0, name_.size(), name_) == 0; - } - ); + }); } -void Pht::split(const Prefix& insert, const std::vector>& vals, IndexEntry entry, RealInsertCallback end_cb ) { +void +Pht::split(const Prefix& insert, + const std::vector>& vals, + IndexEntry entry, + RealInsertCallback end_cb) +{ const auto full = Prefix(entry.prefix); auto loc = findSplitLocation(full, vals); const auto prefix_to_insert = full.getPrefix(loc); - for(;loc != insert.size_ - 1; loc--) { + for (; loc != insert.size_ - 1; loc--) { updateCanary(full.getPrefix(loc)); } end_cb(prefix_to_insert, entry); } -} /* indexation */ +} // namespace indexation -} /* dht */ +} // namespace dht diff --git a/src/listener.h b/src/listener.h index 813fef70..8084766e 100644 --- a/src/listener.h +++ b/src/listener.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "value.h" @@ -26,14 +11,20 @@ namespace dht { /** * Foreign nodes asking for updates about an InfoHash. */ -struct Listener { +struct Listener +{ time_point time; Query query; int version; - Listener(time_point t, Query&& q, int version = 0) : time(t), query(std::move(q)), version(version) {} + Listener(time_point t, Query&& q, int version = 0) + : time(t) + , query(std::move(q)) + , version(version) + {} - void refresh(time_point t, Query&& q) { + void refresh(time_point t, Query&& q) + { time = t; query = std::move(q); } @@ -42,10 +33,11 @@ struct Listener { /** * A single "listen" operation data */ -struct LocalListener { +struct LocalListener +{ Sp query; Value::Filter filter; ValueCallback get_cb; }; -} +} // namespace dht diff --git a/src/log.cpp b/src/log.cpp index c47ee8ac..e81ae846 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "log.h" #include "dhtrunner.h" @@ -36,27 +22,28 @@ namespace log { * Terminal colors for logging */ namespace Color { - enum Code { - FG_RED = 31, - FG_GREEN = 32, - FG_YELLOW = 33, - FG_BLUE = 34, - FG_DEFAULT = 39, - BG_RED = 41, - BG_GREEN = 42, - BG_BLUE = 44, - BG_DEFAULT = 49 - }; - class Modifier { - const Code code; - public: - constexpr Modifier(Code pCode) : code(pCode) {} - friend std::ostream& - operator<<(std::ostream& os, const Modifier& mod) { - return os << "\033[" << mod.code << 'm'; - } - }; -} +enum Code { + FG_RED = 31, + FG_GREEN = 32, + FG_YELLOW = 33, + FG_BLUE = 34, + FG_DEFAULT = 39, + BG_RED = 41, + BG_GREEN = 42, + BG_BLUE = 44, + BG_DEFAULT = 49 +}; +class Modifier +{ + const Code code; + +public: + constexpr Modifier(Code pCode) + : code(pCode) + {} + friend std::ostream& operator<<(std::ostream& os, const Modifier& mod) { return os << "\033[" << mod.code << 'm'; } +}; +} // namespace Color constexpr const Color::Modifier def(Color::FG_DEFAULT); constexpr const Color::Modifier red(Color::FG_RED); @@ -66,7 +53,8 @@ constexpr const Color::Modifier yellow(Color::FG_YELLOW); * Print va_list to std::ostream (used for logging). */ void -printfLog(std::ostream& s, const std::string& message) { +printfLog(std::ostream& s, const std::string& message) +{ using namespace std::chrono; using log_precision = microseconds; auto num = duration_cast(steady_clock::now().time_since_epoch()).count(); @@ -75,7 +63,8 @@ printfLog(std::ostream& s, const std::string& message) { s << message << std::endl; } void -printLog(std::ostream& s, fmt::string_view format, fmt::format_args args) { +printLog(std::ostream& s, fmt::string_view format, fmt::format_args args) +{ using namespace std::chrono; using log_precision = microseconds; auto num = duration_cast(steady_clock::now().time_since_epoch()).count(); @@ -86,33 +75,31 @@ printLog(std::ostream& s, fmt::string_view format, fmt::format_args args) { } std::shared_ptr -getStdLogger() { - return std::make_shared( - [](LogLevel level, std::string&& message) { - if (level == LogLevel::error) - std::cerr << red; - else if (level == LogLevel::warning) - std::cerr << yellow; - printfLog(std::cerr, message); - std::cerr << def; - } - ); +getStdLogger() +{ + return std::make_shared([](LogLevel level, std::string&& message) { + if (level == LogLevel::error) + std::cerr << red; + else if (level == LogLevel::warning) + std::cerr << yellow; + printfLog(std::cerr, message); + std::cerr << def; + }); } std::shared_ptr -getFileLogger(const std::string &path) { +getFileLogger(const std::string& path) +{ auto logfile = std::make_shared(); logfile->open(path, std::ios::out); return std::make_shared( - [logfile](LogLevel /*level*/, std::string&& message) { - printfLog(*logfile, message); - } - ); + [logfile](LogLevel /*level*/, std::string&& message) { printfLog(*logfile, message); }); } #ifndef _WIN32 -constexpr -int syslogLevel(LogLevel level) { +constexpr int +syslogLevel(LogLevel level) +{ switch (level) { case LogLevel::error: return LOG_ERR; @@ -126,15 +113,13 @@ int syslogLevel(LogLevel level) { #endif std::shared_ptr -getSyslogLogger(const char* name) { +getSyslogLogger(const char* name) +{ #ifndef _WIN32 - struct Syslog { - explicit Syslog(const char* n) { - openlog(n, LOG_NDELAY, LOG_USER); - } - ~Syslog() { - closelog(); - } + struct Syslog + { + explicit Syslog(const char* n) { openlog(n, LOG_NDELAY, LOG_USER); } + ~Syslog() { closelog(); } }; // syslog is global. Existing instance must be reused. static std::weak_ptr opened_logfile; @@ -144,33 +129,35 @@ getSyslogLogger(const char* name) { opened_logfile = logfile; } return std::make_shared( - [logfile](LogLevel level, std::string&& message) { - syslog(syslogLevel(level), "%s", message.c_str()); - }); + [logfile](LogLevel level, std::string&& message) { syslog(syslogLevel(level), "%s", message.c_str()); }); #else return getStdLogger(); #endif } void -enableLogging(dht::DhtRunner &dht) { +enableLogging(dht::DhtRunner& dht) +{ dht.setLogger(getStdLogger()); } void -enableFileLogging(dht::DhtRunner &dht, const std::string &path) { +enableFileLogging(dht::DhtRunner& dht, const std::string& path) +{ dht.setLogger(getFileLogger(path)); } OPENDHT_PUBLIC void -enableSyslog(dht::DhtRunner &dht, const char* name) { +enableSyslog(dht::DhtRunner& dht, const char* name) +{ dht.setLogger(getSyslogLogger(name)); } void -disableLogging(dht::DhtRunner &dht) { +disableLogging(dht::DhtRunner& dht) +{ dht.setLogger(); } -} -} +} // namespace log +} // namespace dht diff --git a/src/net.h b/src/net.h index 0cbda17d..c7008ef5 100644 --- a/src/net.h +++ b/src/net.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once namespace dht { @@ -35,4 +20,4 @@ enum class MessageType { }; } /* namespace net */ -} /* dht */ +} // namespace dht diff --git a/src/network_engine.cpp b/src/network_engine.cpp index e9c400c0..2bba40f7 100644 --- a/src/network_engine.cpp +++ b/src/network_engine.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "network_engine.h" #include "request.h" @@ -48,8 +34,8 @@ static constexpr uint8_t v4prefix[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xF constexpr unsigned SEND_NODES {8}; - -struct NetworkEngine::PartialMessage { +struct NetworkEngine::PartialMessage +{ SockAddr from; time_point start; time_point last_part; @@ -70,57 +56,69 @@ void packToken(msgpack::packer& pk, const Blob& token) { pk.pack_bin(token.size()); - pk.pack_bin_body((char*)token.data(), token.size()); + pk.pack_bin_body((char*) token.data(), token.size()); } RequestAnswer::RequestAnswer(ParsedMessage&& msg) - : ntoken(std::move(msg.token)), - values(std::move(msg.values)), - refreshed_values(std::move(msg.refreshed_values)), - expired_values(std::move(msg.expired_values)), - fields(std::move(msg.fields)), - nodes4(std::move(msg.nodes4)), - nodes6(std::move(msg.nodes6)) + : ntoken(std::move(msg.token)) + , values(std::move(msg.values)) + , refreshed_values(std::move(msg.refreshed_values)) + , expired_values(std::move(msg.expired_values)) + , fields(std::move(msg.fields)) + , nodes4(std::move(msg.nodes4)) + , nodes6(std::move(msg.nodes6)) {} -NetworkEngine::NetworkEngine(InfoHash& myid, NetworkConfig c, - std::unique_ptr&& sock, - const Sp& log, - std::mt19937_64& rand, - Scheduler& scheduler, - decltype(NetworkEngine::onError)&& onError, - decltype(NetworkEngine::onNewNode)&& onNewNode, - decltype(NetworkEngine::onReportedAddr)&& onReportedAddr, - decltype(NetworkEngine::onPing)&& onPing, - decltype(NetworkEngine::onFindNode)&& onFindNode, - decltype(NetworkEngine::onGetValues)&& onGetValues, - decltype(NetworkEngine::onListen)&& onListen, - decltype(NetworkEngine::onAnnounce)&& onAnnounce, - decltype(NetworkEngine::onRefresh)&& onRefresh) : - onError(std::move(onError)), - onNewNode(std::move(onNewNode)), - onReportedAddr(std::move(onReportedAddr)), - onPing(std::move(onPing)), - onFindNode(std::move(onFindNode)), - onGetValues(std::move(onGetValues)), - onListen(std::move(onListen)), - onAnnounce(std::move(onAnnounce)), - onRefresh(std::move(onRefresh)), - myid(myid), config(c), dht_socket(std::move(sock)), logger_(log), rd(rand), - cache(rd), - rate_limiter(config.max_req_per_sec), - scheduler(scheduler) +NetworkEngine::NetworkEngine(InfoHash& myid, + NetworkConfig c, + std::unique_ptr&& sock, + const Sp& log, + std::mt19937_64& rand, + Scheduler& scheduler, + decltype(NetworkEngine::onError)&& onError, + decltype(NetworkEngine::onNewNode)&& onNewNode, + decltype(NetworkEngine::onReportedAddr)&& onReportedAddr, + decltype(NetworkEngine::onPing)&& onPing, + decltype(NetworkEngine::onFindNode)&& onFindNode, + decltype(NetworkEngine::onGetValues)&& onGetValues, + decltype(NetworkEngine::onListen)&& onListen, + decltype(NetworkEngine::onAnnounce)&& onAnnounce, + decltype(NetworkEngine::onRefresh)&& onRefresh) + : onError(std::move(onError)) + , onNewNode(std::move(onNewNode)) + , onReportedAddr(std::move(onReportedAddr)) + , onPing(std::move(onPing)) + , onFindNode(std::move(onFindNode)) + , onGetValues(std::move(onGetValues)) + , onListen(std::move(onListen)) + , onAnnounce(std::move(onAnnounce)) + , onRefresh(std::move(onRefresh)) + , myid(myid) + , config(c) + , dht_socket(std::move(sock)) + , logger_(log) + , rd(rand) + , cache(rd) + , rate_limiter(config.max_req_per_sec) + , scheduler(scheduler) {} -NetworkEngine::~NetworkEngine() { +NetworkEngine::~NetworkEngine() +{ clear(); } void -NetworkEngine::tellListener(const Sp& node, Tid socket_id, const InfoHash& hash, want_t want, - const Blob& ntoken, std::vector>&& nodes, - std::vector>&& nodes6, std::vector>&& values, - const Query& query, int version) +NetworkEngine::tellListener(const Sp& node, + Tid socket_id, + const InfoHash& hash, + want_t want, + const Blob& ntoken, + std::vector>&& nodes, + std::vector>&& nodes6, + std::vector>&& values, + const Query& query, + int version) { auto nnodes = bufferNodes(node->getFamily(), hash, want, nodes, nodes6); try { @@ -136,114 +134,147 @@ NetworkEngine::tellListener(const Sp& node, Tid socket_id, const InfoHash& } void -NetworkEngine::tellListenerRefreshed(const Sp& n, Tid socket_id, const InfoHash&, const Blob& token, const std::vector& values, int version) +NetworkEngine::tellListenerRefreshed(const Sp& n, + Tid socket_id, + const InfoHash&, + const Blob& token, + const std::vector& values, + int version) { msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(4 + (version >= 1 ? 1 : 0) + (config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(4 + (version >= 1 ? 1 : 0) + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); pk.pack(version >= 1 ? KEY_A : KEY_U); - pk.pack_map(1 + (version >= 1 ? 1 : 0) + (not values.empty()?1:0) + (not token.empty()?1:0)); - pk.pack(KEY_REQ_ID); pk.pack(myid); - if (version >= 1) { - pk.pack(KEY_REQ_SID); pk.pack(socket_id); - } - if (not token.empty()) { - pk.pack(KEY_REQ_TOKEN); packToken(pk, token); - } - if (not values.empty()) { - pk.pack(KEY_REQ_REFRESHED); - pk.pack(values); - if (logger_) - logger_->d(n->id, "[node %s] sending %zu refreshed values", n->toString().c_str(), values.size()); - } + pk.pack_map(1 + (version >= 1 ? 1 : 0) + (not values.empty() ? 1 : 0) + (not token.empty() ? 1 : 0)); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + if (version >= 1) { + pk.pack(KEY_REQ_SID); + pk.pack(socket_id); + } + if (not token.empty()) { + pk.pack(KEY_REQ_TOKEN); + packToken(pk, token); + } + if (not values.empty()) { + pk.pack(KEY_REQ_REFRESHED); + pk.pack(values); + if (logger_) + logger_->d(n->id, "[node %s] sending %zu refreshed values", n->toString().c_str(), values.size()); + } - pk.pack(KEY_Y); pk.pack(version >= 1 ? KEY_Q : KEY_R); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Y); + pk.pack(version >= 1 ? KEY_Q : KEY_R); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } if (version >= 1) { - Tid tid (n->getNewTid()); + Tid tid(n->getNewTid()); - pk.pack(KEY_Q); pk.pack(QUERY_UPDATE); - pk.pack(KEY_TID); pk.pack(tid); + pk.pack(KEY_Q); + pk.pack(QUERY_UPDATE); + pk.pack(KEY_TID); + pk.pack(tid); - auto req = std::make_shared(MessageType::UpdateValue, tid, n, + auto req = std::make_shared( + MessageType::UpdateValue, + tid, + n, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request&, ParsedMessage&&) { /* on done */ }, - [=](const Request&, bool) { /* on expired */ } - ); + [=](const Request&, bool) { /* on expired */ }); sendRequest(req); ++out_stats.updateValue; return; } - pk.pack(KEY_TID); pk.pack(socket_id); + pk.pack(KEY_TID); + pk.pack(socket_id); // send response send(n->getAddr(), buffer.data(), buffer.size()); } void -NetworkEngine::tellListenerExpired(const Sp& n, Tid socket_id, const InfoHash&, const Blob& token, const std::vector& values, int version) +NetworkEngine::tellListenerExpired(const Sp& n, + Tid socket_id, + const InfoHash&, + const Blob& token, + const std::vector& values, + int version) { msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(4 + (version >= 1 ? 1 : 0) + (config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(4 + (version >= 1 ? 1 : 0) + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); pk.pack(version >= 1 ? KEY_A : KEY_U); - pk.pack_map(1 + (version >= 1 ? 1 : 0) + (not values.empty()?1:0) + (not token.empty()?1:0)); - pk.pack(KEY_REQ_ID); pk.pack(myid); - if (version >= 1) { - pk.pack(KEY_REQ_SID); pk.pack(socket_id); - } - if (not token.empty()) { - pk.pack(KEY_REQ_TOKEN); packToken(pk, token); - } - if (not values.empty()) { - pk.pack(KEY_REQ_EXPIRED); - pk.pack(values); - if (logger_) - logger_->d(n->id, "[node %s] sending %zu expired values", n->toString().c_str(), values.size()); - } + pk.pack_map(1 + (version >= 1 ? 1 : 0) + (not values.empty() ? 1 : 0) + (not token.empty() ? 1 : 0)); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + if (version >= 1) { + pk.pack(KEY_REQ_SID); + pk.pack(socket_id); + } + if (not token.empty()) { + pk.pack(KEY_REQ_TOKEN); + packToken(pk, token); + } + if (not values.empty()) { + pk.pack(KEY_REQ_EXPIRED); + pk.pack(values); + if (logger_) + logger_->d(n->id, "[node %s] sending %zu expired values", n->toString().c_str(), values.size()); + } - pk.pack(KEY_Y); pk.pack(version >= 1 ? KEY_Q : KEY_R); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Y); + pk.pack(version >= 1 ? KEY_Q : KEY_R); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } if (version >= 1) { - Tid tid (n->getNewTid()); + Tid tid(n->getNewTid()); - pk.pack(KEY_Q); pk.pack(QUERY_UPDATE); - pk.pack(KEY_TID); pk.pack(tid); + pk.pack(KEY_Q); + pk.pack(QUERY_UPDATE); + pk.pack(KEY_TID); + pk.pack(tid); - auto req = std::make_shared(MessageType::UpdateValue, tid, n, + auto req = std::make_shared( + MessageType::UpdateValue, + tid, + n, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request&, ParsedMessage&&) { /* on done */ }, - [=](const Request&, bool) { /* on expired */ } - ); + [=](const Request&, bool) { /* on expired */ }); sendRequest(req); ++out_stats.updateValue; return; } - pk.pack(KEY_TID); pk.pack(socket_id); + pk.pack(KEY_TID); + pk.pack(socket_id); // send response send(n->getAddr(), buffer.data(), buffer.size()); } - bool NetworkEngine::isRunning(sa_family_t af) const { @@ -296,13 +327,8 @@ NetworkEngine::requestStep(Sp sreq) req.on_expired(req, false); } - auto err = send(node.getAddr(), (char*)req.msg.data(), req.msg.size(), node.getReplyTime() < now - UDP_REPLY_TIME); - if (err == ENETUNREACH || - err == EHOSTUNREACH || - err == EAFNOSUPPORT || - err == EPIPE || - err == EPERM) - { + auto err = send(node.getAddr(), (char*) req.msg.data(), req.msg.size(), node.getReplyTime() < now - UDP_REPLY_TIME); + if (err == ENETUNREACH || err == EHOSTUNREACH || err == EAFNOSUPPORT || err == EPIPE || err == EPERM) { node.setExpired(); if (not node.id) requests.erase(req.tid); @@ -310,14 +336,14 @@ NetworkEngine::requestStep(Sp sreq) req.last_try = now; if (err != EAGAIN) { ++req.attempt_count; - req.attempt_duration += - req.attempt_duration + uniform_duration_distribution<>(0ms, ((duration)Node::MAX_RESPONSE_TIME)/4)(rd); - if (not req.parts.empty()){ + req.attempt_duration += req.attempt_duration + + uniform_duration_distribution<>(0ms, ((duration) Node::MAX_RESPONSE_TIME) / 4)(rd); + if (not req.parts.empty()) { sendValueParts(req.tid, req.parts, node.getAddr()); } } std::weak_ptr wreq = sreq; - scheduler.add(req.last_try + req.attempt_duration, [this,wreq] { + scheduler.add(req.last_try + req.attempt_duration, [this, wreq] { if (auto req = wreq.lock()) requestStep(req); }); @@ -339,7 +365,6 @@ NetworkEngine::sendRequest(const Sp& request) requestStep(request); } - /* Rate control for requests we receive. */ bool NetworkEngine::rateLimit(const SockAddr& addr) @@ -359,10 +384,8 @@ NetworkEngine::rateLimit(const SockAddr& addr) // invoke per IP, then global rate limiter return (config.max_peer_req_per_sec < 0 - or address_rate_limiter - .emplace(addr, config.max_peer_req_per_sec).first->second - .limit(now)) - and rate_limiter.limit(now); + or address_rate_limiter.emplace(addr, config.max_peer_req_per_sec).first->second.limit(now)) + and rate_limiter.limit(now); } bool @@ -370,21 +393,19 @@ NetworkEngine::isMartian(const SockAddr& addr) { if (addr.getPort() == 0) return true; - switch(addr.getFamily()) { + switch (addr.getFamily()) { case AF_INET: { const auto& sin = addr.getIPv4(); - const uint8_t* address = (const uint8_t*)&sin.sin_addr; - return (address[0] == 0) || - ((address[0] & 0xE0) == 0xE0); + const uint8_t* address = (const uint8_t*) &sin.sin_addr; + return (address[0] == 0) || ((address[0] & 0xE0) == 0xE0); } case AF_INET6: { if (addr.getLength() < sizeof(sockaddr_in6)) return true; const auto& sin6 = addr.getIPv6(); - const uint8_t* address = (const uint8_t*)&sin6.sin6_addr; - return address[0] == 0xFF || - memcmp(address, InfoHash::zero().data(), 16) == 0 || - memcmp(address, v4prefix, 12) == 0; + const uint8_t* address = (const uint8_t*) &sin6.sin6_addr; + return address[0] == 0xFF || memcmp(address, InfoHash::zero().data(), 16) == 0 + || memcmp(address, v4prefix, 12) == 0; } default: return true; @@ -407,7 +428,7 @@ NetworkEngine::isNodeBlacklisted(const SockAddr& addr) const } void -NetworkEngine::processMessage(const uint8_t *buf, size_t buflen, SockAddr f) +NetworkEngine::processMessage(const uint8_t* buf, size_t buflen, SockAddr f) { auto from = f.getMappedIPv4(); if (isMartian(from)) { @@ -424,7 +445,7 @@ NetworkEngine::processMessage(const uint8_t *buf, size_t buflen, SockAddr f) auto msg = std::make_unique(); try { - msgpack::unpacked msg_res = msgpack::unpack((const char*)buf, buflen); + msgpack::unpacked msg_res = msgpack::unpack((const char*) buf, buflen); msg->msgpack_unpack(msg_res.get()); } catch (const std::exception& e) { if (logger_) @@ -494,7 +515,7 @@ NetworkEngine::processMessage(const uint8_t *buf, size_t buflen, SockAddr f) if (msg->value_parts.empty()) { try { process(std::move(msg), from); - } catch(...) { + } catch (...) { return; } } else { @@ -532,8 +553,7 @@ NetworkEngine::process(std::unique_ptr&& msg, const SockAddr& fro if (logger_) logger_->w("Unable to deserialize nodes %s", e.what()); } - } - else if (msg->type == MessageType::Error or msg->type == MessageType::Reply) { + } else if (msg->type == MessageType::Error or msg->type == MessageType::Reply) { auto rsocket = node->getSocket(msg->tid); auto req = node->getRequest(msg->tid); @@ -549,7 +569,10 @@ NetworkEngine::process(std::unique_ptr&& msg, const SockAddr& fro if (not node->isClient()) onNewNode(node, 1); if (logger_) - logger_->d(node->id, "[node %s] Unable to find transaction with id %u", node->toString().c_str(), msg->tid); + logger_->d(node->id, + "[node %s] Unable to find transaction with id %u", + node->toString().c_str(), + msg->tid); return; } } @@ -562,17 +585,18 @@ NetworkEngine::process(std::unique_ptr&& msg, const SockAddr& fro if (req and (req->cancelled() or req->expired() or req->completed())) { if (logger_) - logger_->w(node->id, "[node %s] response to expired, cancelled or completed request", node->toString().c_str()); + logger_->w(node->id, + "[node %s] response to expired, cancelled or completed request", + node->toString().c_str()); return; } switch (msg->type) { case MessageType::Error: { - if (msg->id and req and ( - (msg->error_code == DhtProtocolException::NOT_FOUND and req->getType() == MessageType::Refresh) or - (msg->error_code == DhtProtocolException::UNAUTHORIZED and (req->getType() == MessageType::AnnounceValue - or req->getType() == MessageType::Listen)))) - { + if (msg->id and req + and ((msg->error_code == DhtProtocolException::NOT_FOUND and req->getType() == MessageType::Refresh) + or (msg->error_code == DhtProtocolException::UNAUTHORIZED + and (req->getType() == MessageType::AnnounceValue or req->getType() == MessageType::Listen)))) { req->last_try = time_point::min(); req->reply_time = time_point::min(); if (not req->setError(DhtProtocolException {msg->error_code})) @@ -580,17 +604,19 @@ NetworkEngine::process(std::unique_ptr&& msg, const SockAddr& fro } else { if (logIncoming_) if (logger_) - logger_->w(msg->id, "[node %s %s] received unknown error message %u", - msg->id.toString().c_str(), from.toString().c_str(), msg->error_code); + logger_->w(msg->id, + "[node %s %s] received unknown error message %u", + msg->id.toString().c_str(), + from.toString().c_str(), + msg->error_code); } break; } case MessageType::Reply: if (req) { /* request reply */ auto& r = *req; - if (r.getType() == MessageType::AnnounceValue - or r.getType() == MessageType::Listen - or r.getType() == MessageType::Refresh) { + if (r.getType() == MessageType::AnnounceValue or r.getType() == MessageType::Listen + or r.getType() == MessageType::Refresh) { r.node->authSuccess(); } r.reply_time = scheduler.time(); @@ -631,7 +657,8 @@ NetworkEngine::process(std::unique_ptr&& msg, const SockAddr& fro break; case MessageType::FindNode: { // if (logger_) - // logger_->d(msg->target, node->id, "[node %s] got 'find' request for %s (%d)", node->toString().c_str(), msg->target.toString().c_str(), msg->want); + // logger_->d(msg->target, node->id, "[node %s] got 'find' request for %s (%d)", + // node->toString().c_str(), msg->target.toString().c_str(), msg->want); ++in_stats.find; RequestAnswer answer = onFindNode(node, msg->target, msg->want); auto nnodes = bufferNodes(from.getFamily(), msg->target, msg->want, answer.nodes4, answer.nodes6); @@ -640,7 +667,8 @@ NetworkEngine::process(std::unique_ptr&& msg, const SockAddr& fro } case MessageType::GetValues: { // if (logger_) - // logger_->d(msg->info_hash, node->id, "[node %s] got 'get' request for %s", node->toString().c_str(), msg->info_hash.toString().c_str()); + // logger_->d(msg->info_hash, node->id, "[node %s] got 'get' request for %s", + // node->toString().c_str(), msg->info_hash.toString().c_str()); ++in_stats.get; RequestAnswer answer = onGetValues(node, msg->info_hash, msg->want, msg->query); auto nnodes = bufferNodes(from.getFamily(), msg->info_hash, msg->want, answer.nodes4, answer.nodes6); @@ -649,7 +677,11 @@ NetworkEngine::process(std::unique_ptr&& msg, const SockAddr& fro } case MessageType::AnnounceValue: { if (logIncoming_ and logger_) - logger_->d(msg->info_hash, node->id, "[node %s] got 'put' request for %s", node->toString().c_str(), msg->info_hash.toString().c_str()); + logger_->d(msg->info_hash, + node->id, + "[node %s] got 'put' request for %s", + node->toString().c_str(), + msg->info_hash.toString().c_str()); ++in_stats.put; onAnnounce(node, msg->info_hash, msg->token, msg->values, msg->created); @@ -657,34 +689,51 @@ NetworkEngine::process(std::unique_ptr&& msg, const SockAddr& fro This is to prevent them from backtracking, and hence polluting the DHT. */ for (auto& v : msg->values) { - sendValueAnnounced(from, msg->tid, v->id); + sendValueAnnounced(from, msg->tid, v->id); } break; } case MessageType::Refresh: if (logIncoming_ and logger_) - logger_->d(msg->info_hash, node->id, "[node %s] got 'refresh' request for %s", node->toString().c_str(), msg->info_hash.toString().c_str()); + logger_->d(msg->info_hash, + node->id, + "[node %s] got 'refresh' request for %s", + node->toString().c_str(), + msg->info_hash.toString().c_str()); onRefresh(node, msg->info_hash, msg->token, msg->value_id); /* Same note as above in MessageType::AnnounceValue applies. */ sendValueAnnounced(from, msg->tid, msg->value_id); break; case MessageType::Listen: { if (logIncoming_ and logger_) - logger_->d(msg->info_hash, node->id, "[node %s] got 'listen' request for %s", node->toString().c_str(), msg->info_hash.toString().c_str()); + logger_->d(msg->info_hash, + node->id, + "[node %s] got 'listen' request for %s", + node->toString().c_str(), + msg->info_hash.toString().c_str()); ++in_stats.listen; - RequestAnswer answer = onListen(node, msg->info_hash, msg->token, msg->socket_id, std::move(msg->query), msg->version); + RequestAnswer answer + = onListen(node, msg->info_hash, msg->token, msg->socket_id, std::move(msg->query), msg->version); auto nnodes = bufferNodes(from.getFamily(), msg->info_hash, msg->want, answer.nodes4, answer.nodes6); sendListenConfirmation(from, msg->tid); break; } case MessageType::UpdateValue: { if (logIncoming_ and logger_) - logger_->d(msg->info_hash, node->id, "[node %s] got 'update' request for %s", node->toString().c_str(), msg->info_hash.toString().c_str()); + logger_->d(msg->info_hash, + node->id, + "[node %s] got 'update' request for %s", + node->toString().c_str(), + msg->info_hash.toString().c_str()); ++in_stats.updateValue; if (auto rsocket = node->getSocket(msg->socket_id)) rsocket->on_receive(node, std::move(*msg)); else if (logger_) - logger_->e(msg->info_hash, node->id, "[node %s] 'update' request without socket for %s", node->toString().c_str(), msg->info_hash.toString().c_str()); + logger_->e(msg->info_hash, + node->id, + "[node %s] 'update' request without socket for %s", + node->toString().c_str(), + msg->info_hash.toString().c_str()); sendListenConfirmation(from, msg->tid); break; } @@ -704,42 +753,54 @@ void insertAddr(msgpack::packer& pk, const SockAddr& addr) { size_t addr_len = std::min(addr.getLength(), - (addr.getFamily() == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)); - void* addr_ptr = (addr.getFamily() == AF_INET) ? (void*)&addr.getIPv4().sin_addr - : (void*)&addr.getIPv6().sin6_addr; + (addr.getFamily() == AF_INET) ? sizeof(in_addr) : sizeof(in6_addr)); + void* addr_ptr = (addr.getFamily() == AF_INET) ? (void*) &addr.getIPv4().sin_addr + : (void*) &addr.getIPv6().sin6_addr; pk.pack("sa"); pk.pack_bin(addr_len); - pk.pack_bin_body((char*)addr_ptr, addr_len); + pk.pack_bin_body((char*) addr_ptr, addr_len); } int -NetworkEngine::send(const SockAddr& addr, const char *buf, size_t len, bool confirmed) +NetworkEngine::send(const SockAddr& addr, const char* buf, size_t len, bool confirmed) { - return dht_socket ? dht_socket->sendTo(addr, (const uint8_t*)buf, len, confirmed) : ENOTCONN; + return dht_socket ? dht_socket->sendTo(addr, (const uint8_t*) buf, len, confirmed) : ENOTCONN; } Sp -NetworkEngine::sendPing(const Sp& node, RequestCb&& on_done, RequestExpiredCb&& on_expired) { - Tid tid (node->getNewTid()); +NetworkEngine::sendPing(const Sp& node, RequestCb&& on_done, RequestExpiredCb&& on_expired) +{ + Tid tid(node->getNewTid()); msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(5+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(5 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); - pk.pack(KEY_A); pk.pack_map(1); - pk.pack(KEY_REQ_ID); pk.pack(myid); + pk.pack(KEY_A); + pk.pack_map(1); + pk.pack(KEY_REQ_ID); + pk.pack(myid); - pk.pack(KEY_Q); pk.pack(QUERY_PING); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_Q); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Q); + pk.pack(QUERY_PING); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_Q); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } - auto req = std::make_shared(MessageType::Ping, tid, node, + auto req = std::make_shared( + MessageType::Ping, + tid, + node, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request& req_status, ParsedMessage&&) { if (logger_) @@ -748,132 +809,175 @@ NetworkEngine::sendPing(const Sp& node, RequestCb&& on_done, RequestExpire on_done(req_status, {}); } }, - std::move(on_expired) - ); + std::move(on_expired)); sendRequest(req); ++out_stats.ping; return req; } void -NetworkEngine::sendPong(const SockAddr& addr, Tid tid) { +NetworkEngine::sendPong(const SockAddr& addr, Tid tid) +{ msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(4+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(4 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); - pk.pack(KEY_R); pk.pack_map(2); - pk.pack(KEY_REQ_ID); pk.pack(myid); - insertAddr(pk, addr); + pk.pack(KEY_R); + pk.pack_map(2); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + insertAddr(pk, addr); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_R); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_R); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } send(addr, buffer.data(), buffer.size()); } Sp -NetworkEngine::sendFindNode(const Sp& n, const InfoHash& target, want_t want, - RequestCb&& on_done, RequestExpiredCb&& on_expired) { - Tid tid (n->getNewTid()); +NetworkEngine::sendFindNode( + const Sp& n, const InfoHash& target, want_t want, RequestCb&& on_done, RequestExpiredCb&& on_expired) +{ + Tid tid(n->getNewTid()); msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(5+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(5 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); - pk.pack(KEY_A); pk.pack_map(2 + (want>0?1:0)); - pk.pack(KEY_REQ_ID); pk.pack(myid); - pk.pack(KEY_REQ_TARGET); pk.pack(target); + pk.pack(KEY_A); + pk.pack_map(2 + (want > 0 ? 1 : 0)); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + pk.pack(KEY_REQ_TARGET); + pk.pack(target); if (want > 0) { - pk.pack(KEY_REQ_WANT); - pk.pack_array(((want & WANT4)?1:0) + ((want & WANT6)?1:0)); - if (want & WANT4) pk.pack(AF_INET); - if (want & WANT6) pk.pack(AF_INET6); + pk.pack(KEY_REQ_WANT); + pk.pack_array(((want & WANT4) ? 1 : 0) + ((want & WANT6) ? 1 : 0)); + if (want & WANT4) + pk.pack(AF_INET); + if (want & WANT6) + pk.pack(AF_INET6); } - pk.pack(KEY_Q); pk.pack(QUERY_FIND); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_Q); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Q); + pk.pack(QUERY_FIND); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_Q); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } - auto req = std::make_shared(MessageType::FindNode, tid, n, + auto req = std::make_shared( + MessageType::FindNode, + tid, + n, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request& req_status, ParsedMessage&& msg) { /* on done */ - if (on_done) { - on_done(req_status, {std::forward(msg)}); - } + if (on_done) { + on_done(req_status, + {std::forward(msg)}); + } }, - std::move(on_expired) - ); + std::move(on_expired)); sendRequest(req); ++out_stats.find; return req; } - Sp -NetworkEngine::sendGetValues(const Sp& n, const InfoHash& info_hash, const Query& query, want_t want, - RequestCb&& on_done, RequestExpiredCb&& on_expired) { - Tid tid (n->getNewTid()); +NetworkEngine::sendGetValues(const Sp& n, + const InfoHash& info_hash, + const Query& query, + want_t want, + RequestCb&& on_done, + RequestExpiredCb&& on_expired) +{ + Tid tid(n->getNewTid()); msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(5+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(5 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); unsigned sendQuery = (not query.where.empty() or not query.select.empty()) ? 1 : 0; unsigned sendWant = (want > 0) ? 1 : 0; - pk.pack(KEY_A); pk.pack_map(2 + sendQuery + sendWant); - pk.pack(KEY_REQ_ID); pk.pack(myid); - pk.pack(KEY_REQ_H); pk.pack(info_hash); - if (sendQuery) { - pk.pack(KEY_Q); pk.pack(query); - } - if (sendWant) { + pk.pack(KEY_A); + pk.pack_map(2 + sendQuery + sendWant); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + pk.pack(KEY_REQ_H); + pk.pack(info_hash); + if (sendQuery) { + pk.pack(KEY_Q); + pk.pack(query); + } + if (sendWant) { pk.pack(KEY_REQ_WANT); unsigned sendWant4 = (want & WANT4) ? 1 : 0; unsigned sendWant6 = (want & WANT6) ? 1 : 0; pk.pack_array(sendWant4 + sendWant6); - if (sendWant4) pk.pack(AF_INET); - if (sendWant6) pk.pack(AF_INET6); - } + if (sendWant4) + pk.pack(AF_INET); + if (sendWant6) + pk.pack(AF_INET6); + } - pk.pack(KEY_Q); pk.pack(QUERY_GET); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_Q); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Q); + pk.pack(QUERY_GET); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_Q); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } - - auto req = std::make_shared(MessageType::GetValues, tid, n, + + auto req = std::make_shared( + MessageType::GetValues, + tid, + n, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request& req_status, ParsedMessage&& msg) { /* on done */ - if (on_done) { - on_done(req_status, {std::forward(msg)}); - } + if (on_done) { + on_done(req_status, + {std::forward(msg)}); + } }, - std::move(on_expired) - ); + std::move(on_expired)); sendRequest(req); ++out_stats.get; return req; } -SockAddr deserializeIPv4(const uint8_t* ni) { +SockAddr +deserializeIPv4(const uint8_t* ni) +{ SockAddr addr; addr.setFamily(AF_INET); auto& sin = addr.getIPv4(); @@ -881,7 +985,9 @@ SockAddr deserializeIPv4(const uint8_t* ni) { std::memcpy(&sin.sin_port, ni + 4, 2); return addr; } -SockAddr deserializeIPv6(const uint8_t* ni) { +SockAddr +deserializeIPv6(const uint8_t* ni) +{ SockAddr addr; addr.setFamily(AF_INET6); auto& sin6 = addr.getIPv6(); @@ -891,7 +997,8 @@ SockAddr deserializeIPv6(const uint8_t* ni) { } void -NetworkEngine::deserializeNodes(ParsedMessage& msg, const SockAddr& from) { +NetworkEngine::deserializeNodes(ParsedMessage& msg, const SockAddr& from) +{ if (msg.nodes4_raw.size() % NODE4_INFO_BUF_LEN != 0 || msg.nodes6_raw.size() % NODE6_INFO_BUF_LEN != 0) { throw DhtProtocolException {DhtProtocolException::WRONG_NODE_INFO_BUF_LEN}; } @@ -932,7 +1039,9 @@ NetworkEngine::deserializeNodes(ParsedMessage& msg, const SockAddr& from) { } std::vector -NetworkEngine::packValueHeader(msgpack::sbuffer& buffer, std::vector>::const_iterator b, std::vector>::const_iterator e) const +NetworkEngine::packValueHeader(msgpack::sbuffer& buffer, + std::vector>::const_iterator b, + std::vector>::const_iterator e) const { std::vector svals; size_t total_size = 0; @@ -949,7 +1058,7 @@ NetworkEngine::packValueHeader(msgpack::sbuffer& buffer, std::vector>: // try to put everything in a single UDP packet if (svals.size() < 50 && total_size < MAX_PACKET_VALUE_SIZE) { for (const auto& b : svals) - buffer.write((const char*)b.data(), b.size()); + buffer.write((const char*) b.data(), b.size()); // if (logger_) // logger_->d("sending %lu bytes of values", total_size); svals.clear(); @@ -964,27 +1073,35 @@ void NetworkEngine::sendValueParts(Tid tid, const std::vector& svals, const SockAddr& addr) { msgpack::sbuffer buffer; - unsigned i=0; - for (const auto& v: svals) { + unsigned i = 0; + for (const auto& v : svals) { size_t start {0}, end; do { end = std::min(start + MTU, v.size()); buffer.clear(); msgpack::packer pk(&buffer); - pk.pack_map(3+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(3 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } - pk.pack(KEY_Y); pk.pack(KEY_V); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_V); pk.pack_map(1); - pk.pack(i); pk.pack_map(2); - pk.pack("o"sv); pk.pack(start); - pk.pack("d"sv); pk.pack_bin(end-start); - pk.pack_bin_body((const char*)v.data()+start, end-start); + pk.pack(KEY_Y); + pk.pack(KEY_V); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_V); + pk.pack_map(1); + pk.pack(i); + pk.pack_map(2); + pk.pack("o"sv); + pk.pack(start); + pk.pack("d"sv); + pk.pack_bin(end - start); + pk.pack_bin_body((const char*) v.data() + start, end - start); send(addr, buffer.data(), buffer.size()); start = end; } while (start != v.size()); @@ -993,29 +1110,37 @@ NetworkEngine::sendValueParts(Tid tid, const std::vector& svals, const Soc } void -NetworkEngine::sendNodesValues(const SockAddr& addr, Tid tid, const Blob& nodes, const Blob& nodes6, - const std::vector>& st, const Query& query, const Blob& token) +NetworkEngine::sendNodesValues(const SockAddr& addr, + Tid tid, + const Blob& nodes, + const Blob& nodes6, + const std::vector>& st, + const Query& query, + const Blob& token) { msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(4+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(4 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); pk.pack(KEY_R); - pk.pack_map(2 + (not st.empty()?1:0) + (nodes.size()>0?1:0) + (nodes6.size()>0?1:0) + (not token.empty()?1:0)); - pk.pack(KEY_REQ_ID); pk.pack(myid); + pk.pack_map(2 + (not st.empty() ? 1 : 0) + (nodes.size() > 0 ? 1 : 0) + (nodes6.size() > 0 ? 1 : 0) + + (not token.empty() ? 1 : 0)); + pk.pack(KEY_REQ_ID); + pk.pack(myid); insertAddr(pk, addr); if (nodes.size() > 0) { pk.pack(KEY_REQ_NODES4); pk.pack_bin(nodes.size()); - pk.pack_bin_body((const char*)nodes.data(), nodes.size()); + pk.pack_bin_body((const char*) nodes.data(), nodes.size()); } if (nodes6.size() > 0) { pk.pack(KEY_REQ_NODES6); pk.pack_bin(nodes6.size()); - pk.pack_bin_body((const char*)nodes6.data(), nodes6.size()); + pk.pack_bin_body((const char*) nodes6.data(), nodes6.size()); } if (not token.empty()) { - pk.pack(KEY_REQ_TOKEN); packToken(pk, token); + pk.pack(KEY_REQ_TOKEN); + packToken(pk, token); } std::vector svals {}; if (not st.empty()) { /* pack complete values */ @@ -1025,23 +1150,30 @@ NetworkEngine::sendNodesValues(const SockAddr& addr, Tid tid, const Blob& nodes, auto fields = query.select.getSelection(); pk.pack(KEY_REQ_FIELDS); pk.pack_map(2); - pk.pack("f"sv); pk.pack(fields); - pk.pack("v"sv); pk.pack_array(st.size()*fields.size()); + pk.pack("f"sv); + pk.pack(fields); + pk.pack("v"sv); + pk.pack_array(st.size() * fields.size()); for (const auto& v : st) v->msgpack_pack_fields(fields, pk); - //DHT_LOG_DBG("sending closest nodes (%d+%d nodes.), %u value headers containing %u fields", - // nodes.size(), nodes6.size(), st.size(), fields.size()); + // DHT_LOG_DBG("sending closest nodes (%d+%d nodes.), %u value headers containing %u fields", + // nodes.size(), nodes6.size(), st.size(), fields.size()); } } - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_R); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_R); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } // send response @@ -1055,14 +1187,14 @@ NetworkEngine::sendNodesValues(const SockAddr& addr, Tid tid, const Blob& nodes, Blob NetworkEngine::bufferNodes(sa_family_t af, const InfoHash& id, std::vector>& nodes) { - std::sort(nodes.begin(), nodes.end(), [&](const Sp& a, const Sp& b){ + std::sort(nodes.begin(), nodes.end(), [&](const Sp& a, const Sp& b) { return id.xorCmp(a->id, b->id) < 0; }); size_t nnode = std::min(SEND_NODES, nodes.size()); Blob bnodes; if (af == AF_INET) { bnodes.resize(NODE4_INFO_BUF_LEN * nnode); - for (size_t i=0; i -NetworkEngine::bufferNodes(sa_family_t af, const InfoHash& id, want_t want, - std::vector>& nodes4, std::vector>& nodes6) +NetworkEngine::bufferNodes( + sa_family_t af, const InfoHash& id, want_t want, std::vector>& nodes4, std::vector>& nodes6) { if (want < 0) want = af == AF_INET ? WANT4 : WANT6; @@ -1104,71 +1236,95 @@ NetworkEngine::bufferNodes(sa_family_t af, const InfoHash& id, want_t want, Sp NetworkEngine::sendListen(const Sp& n, - const InfoHash& hash, - const Query& query, - const Blob& token, - Tid socketId, - RequestCb&& on_done, - RequestExpiredCb&& on_expired) + const InfoHash& hash, + const Query& query, + const Blob& token, + Tid socketId, + RequestCb&& on_done, + RequestExpiredCb&& on_expired) { - Tid tid (n->getNewTid()); + Tid tid(n->getNewTid()); msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(5+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(5 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); auto has_query = not query.where.empty() or not query.select.empty(); - pk.pack(KEY_A); pk.pack_map(5 + has_query); - pk.pack(KEY_REQ_ID); pk.pack(myid); - pk.pack(KEY_VERSION); pk.pack(1); - pk.pack(KEY_REQ_H); pk.pack(hash); - pk.pack(KEY_REQ_TOKEN); packToken(pk, token); - pk.pack(KEY_REQ_SID); pk.pack(socketId); - if (has_query) { - pk.pack(KEY_REQ_QUERY); pk.pack(query); - } + pk.pack(KEY_A); + pk.pack_map(5 + has_query); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + pk.pack(KEY_VERSION); + pk.pack(1); + pk.pack(KEY_REQ_H); + pk.pack(hash); + pk.pack(KEY_REQ_TOKEN); + packToken(pk, token); + pk.pack(KEY_REQ_SID); + pk.pack(socketId); + if (has_query) { + pk.pack(KEY_REQ_QUERY); + pk.pack(query); + } - pk.pack(KEY_Q); pk.pack(QUERY_LISTEN); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_Q); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Q); + pk.pack(QUERY_LISTEN); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_Q); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } - auto req = std::make_shared(MessageType::Listen, tid, n, + auto req = std::make_shared( + MessageType::Listen, + tid, + n, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request& req_status, ParsedMessage&& msg) { /* on done */ - if (on_done) - on_done(req_status, {std::forward(msg)}); + if (on_done) + on_done(req_status, + {std::forward(msg)}); }, - std::move(on_expired) - ); + std::move(on_expired)); sendRequest(req); ++out_stats.listen; return req; } void -NetworkEngine::sendListenConfirmation(const SockAddr& addr, Tid tid) { +NetworkEngine::sendListenConfirmation(const SockAddr& addr, Tid tid) +{ msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(4+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(4 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); - pk.pack(KEY_R); pk.pack_map(2); - pk.pack(KEY_REQ_ID); pk.pack(myid); - insertAddr(pk, addr); + pk.pack(KEY_R); + pk.pack_map(2); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + insertAddr(pk, addr); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_R); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_R); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } send(addr, buffer.data(), buffer.size()); @@ -1176,56 +1332,69 @@ NetworkEngine::sendListenConfirmation(const SockAddr& addr, Tid tid) { Sp NetworkEngine::sendAnnounceValue(const Sp& n, - const InfoHash& infohash, - const Sp& value, - time_point created, - const Blob& token, - RequestCb&& on_done, - RequestExpiredCb&& on_expired) + const InfoHash& infohash, + const Sp& value, + time_point created, + const Blob& token, + RequestCb&& on_done, + RequestExpiredCb&& on_expired) { - Tid tid (n->getNewTid()); + Tid tid(n->getNewTid()); msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(5+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(5 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); bool add_created = created < scheduler.time(); - pk.pack(KEY_A); pk.pack_map(add_created ? 5 : 4); - pk.pack(KEY_REQ_ID); pk.pack(myid); - pk.pack(KEY_REQ_H); pk.pack(infohash); - auto v = packValueHeader(buffer, {value}); - if (add_created) { - pk.pack(KEY_REQ_CREATION); - pk.pack(to_time_t(created)); - } - pk.pack(KEY_REQ_TOKEN); pk.pack(token); + pk.pack(KEY_A); + pk.pack_map(add_created ? 5 : 4); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + pk.pack(KEY_REQ_H); + pk.pack(infohash); + auto v = packValueHeader(buffer, {value}); + if (add_created) { + pk.pack(KEY_REQ_CREATION); + pk.pack(to_time_t(created)); + } + pk.pack(KEY_REQ_TOKEN); + pk.pack(token); - pk.pack(KEY_Q); pk.pack(QUERY_PUT); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_Q); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Q); + pk.pack(QUERY_PUT); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_Q); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } - auto req = std::make_shared(MessageType::AnnounceValue, tid, n, + auto req = std::make_shared( + MessageType::AnnounceValue, + tid, + n, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request& req_status, ParsedMessage&& msg) { /* on done */ - if (msg.value_id == Value::INVALID_ID) { - if (logger_) - logger_->d(infohash, "Unknown search or announce!"); - } else { - if (on_done) { - RequestAnswer answer {}; - answer.vid = msg.value_id; - on_done(req_status, std::move(answer)); - } - } + if (msg.value_id == Value::INVALID_ID) { + if (logger_) + logger_->d(infohash, + "Unknown search or announce!"); + } else { + if (on_done) { + RequestAnswer answer {}; + answer.vid = msg.value_id; + on_done(req_status, std::move(answer)); + } + } }, - std::move(on_expired) - ); + std::move(on_expired)); req->parts = std::move(v); sendRequest(req); ++out_stats.put; @@ -1266,41 +1435,55 @@ NetworkEngine::sendUpdateValues(const Sp& n, const Blob& token, size_t socket_id) { - Tid tid (n->getNewTid()); - Tid sid (socket_id); + Tid tid(n->getNewTid()); + Tid sid(socket_id); msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(5+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(5 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); - pk.pack(KEY_A); pk.pack_map((created < scheduler.time() ? 7 : 6)); - pk.pack(KEY_REQ_ID); pk.pack(myid); - pk.pack(KEY_VERSION); pk.pack(1); - pk.pack(KEY_REQ_H); pk.pack(infohash); - pk.pack(KEY_REQ_SID); pk.pack(sid); - auto v = packValueHeader(buffer, begin, end); - if (created < scheduler.time()) { - pk.pack(KEY_REQ_CREATION); - pk.pack(to_time_t(created)); - } - pk.pack(KEY_REQ_TOKEN); pk.pack(token); + pk.pack(KEY_A); + pk.pack_map((created < scheduler.time() ? 7 : 6)); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + pk.pack(KEY_VERSION); + pk.pack(1); + pk.pack(KEY_REQ_H); + pk.pack(infohash); + pk.pack(KEY_REQ_SID); + pk.pack(sid); + auto v = packValueHeader(buffer, begin, end); + if (created < scheduler.time()) { + pk.pack(KEY_REQ_CREATION); + pk.pack(to_time_t(created)); + } + pk.pack(KEY_REQ_TOKEN); + pk.pack(token); - pk.pack(KEY_Q); pk.pack(QUERY_UPDATE); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_Q); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Q); + pk.pack(QUERY_UPDATE); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_Q); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } - auto req = std::make_shared(MessageType::UpdateValue, tid, n, + auto req = std::make_shared( + MessageType::UpdateValue, + tid, + n, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request&, ParsedMessage&&) { /* on done */ }, - [=](const Request&, bool) { /* on expired */ } - ); + [=](const Request&, bool) { /* on expired */ }); req->parts = std::move(v); sendRequest(req); ++out_stats.updateValue; @@ -1309,109 +1492,136 @@ NetworkEngine::sendUpdateValues(const Sp& n, Sp NetworkEngine::sendRefreshValue(const Sp& n, - const InfoHash& infohash, - const Value::Id& vid, - const Blob& token, - RequestCb&& on_done, - RequestErrorCb&& on_error, - RequestExpiredCb&& on_expired) + const InfoHash& infohash, + const Value::Id& vid, + const Blob& token, + RequestCb&& on_done, + RequestErrorCb&& on_error, + RequestExpiredCb&& on_expired) { - Tid tid (n->getNewTid()); + Tid tid(n->getNewTid()); msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(5+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(5 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); - pk.pack(KEY_A); pk.pack_map(4); - pk.pack(KEY_REQ_ID); pk.pack(myid); - pk.pack(KEY_REQ_H); pk.pack(infohash); - pk.pack(KEY_REQ_VALUE_ID); pk.pack(vid); - pk.pack(KEY_REQ_TOKEN); pk.pack(token); + pk.pack(KEY_A); + pk.pack_map(4); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + pk.pack(KEY_REQ_H); + pk.pack(infohash); + pk.pack(KEY_REQ_VALUE_ID); + pk.pack(vid); + pk.pack(KEY_REQ_TOKEN); + pk.pack(token); - pk.pack(KEY_Q); pk.pack(QUERY_REFRESH); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_Q); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_Q); + pk.pack(QUERY_REFRESH); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_Q); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } - auto req = std::make_shared(MessageType::Refresh, tid, n, + auto req = std::make_shared( + MessageType::Refresh, + tid, + n, Blob(buffer.data(), buffer.data() + buffer.size()), [=](const Request& req_status, ParsedMessage&& msg) { /* on done */ - if (msg.value_id == Value::INVALID_ID) { - if (logger_) - logger_->d(infohash, "Unknown search or announce!"); - } else { - if (on_done) { - RequestAnswer answer {}; - answer.vid = msg.value_id; - on_done(req_status, std::move(answer)); - } - } + if (msg.value_id == Value::INVALID_ID) { + if (logger_) + logger_->d(infohash, + "Unknown search or announce!"); + } else { + if (on_done) { + RequestAnswer answer {}; + answer.vid = msg.value_id; + on_done(req_status, std::move(answer)); + } + } }, std::move(on_error), - std::move(on_expired) - ); + std::move(on_expired)); sendRequest(req); ++out_stats.refresh; return req; } void -NetworkEngine::sendValueAnnounced(const SockAddr& addr, Tid tid, Value::Id vid) { +NetworkEngine::sendValueAnnounced(const SockAddr& addr, Tid tid, Value::Id vid) +{ msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(4+(config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(4 + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); - pk.pack(KEY_R); pk.pack_map(3); - pk.pack(KEY_REQ_ID); pk.pack(myid); - pk.pack(KEY_REQ_VALUE_ID); pk.pack(vid); - insertAddr(pk, addr); + pk.pack(KEY_R); + pk.pack_map(3); + pk.pack(KEY_REQ_ID); + pk.pack(myid); + pk.pack(KEY_REQ_VALUE_ID); + pk.pack(vid); + insertAddr(pk, addr); - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_R); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_R); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } send(addr, buffer.data(), buffer.size()); } void -NetworkEngine::sendError(const SockAddr& addr, - Tid tid, - uint16_t code, - const std::string& message, - bool include_id) +NetworkEngine::sendError(const SockAddr& addr, Tid tid, uint16_t code, const std::string& message, bool include_id) { msgpack::sbuffer buffer; msgpack::packer pk(&buffer); - pk.pack_map(4 + (include_id?1:0) + (config.network?1:0)+(config.is_client?1:0)); + pk.pack_map(4 + (include_id ? 1 : 0) + (config.network ? 1 : 0) + (config.is_client ? 1 : 0)); - pk.pack(KEY_E); pk.pack_array(2); - pk.pack(code); - pk.pack(message); + pk.pack(KEY_E); + pk.pack_array(2); + pk.pack(code); + pk.pack(message); if (include_id) { - pk.pack(KEY_R); pk.pack_map(1); - pk.pack(KEY_REQ_ID); pk.pack(myid); + pk.pack(KEY_R); + pk.pack_map(1); + pk.pack(KEY_REQ_ID); + pk.pack(myid); } - pk.pack(KEY_TID); pk.pack(tid); - pk.pack(KEY_Y); pk.pack(KEY_E); - pk.pack(KEY_UA); pk.pack(OPENDHT_UA); + pk.pack(KEY_TID); + pk.pack(tid); + pk.pack(KEY_Y); + pk.pack(KEY_E); + pk.pack(KEY_UA); + pk.pack(OPENDHT_UA); if (config.network) { - pk.pack(KEY_NETID); pk.pack(config.network); + pk.pack(KEY_NETID); + pk.pack(config.network); } if (config.is_client) { - pk.pack(KEY_ISCLIENT); pk.pack(config.is_client); + pk.pack(KEY_ISCLIENT); + pk.pack(config.is_client); } send(addr, buffer.data(), buffer.size()); @@ -1423,8 +1633,7 @@ NetworkEngine::maintainRxBuffer(Tid tid) auto msg = partial_messages.find(tid); if (msg != partial_messages.end()) { const auto& now = scheduler.time(); - if (msg->second.start + RX_MAX_PACKET_TIME < now - || msg->second.last_part + RX_TIMEOUT < now) { + if (msg->second.start + RX_MAX_PACKET_TIME < now || msg->second.last_part + RX_TIMEOUT < now) { if (logger_) logger_->w("Dropping expired partial message from %s", msg->second.from.toString().c_str()); partial_messages.erase(msg); @@ -1432,6 +1641,5 @@ NetworkEngine::maintainRxBuffer(Tid tid) } } - } /* namespace net */ } /* namespace dht */ diff --git a/src/network_utils.cpp b/src/network_utils.cpp index 0c2fe612..4df7abec 100644 --- a/src/network_utils.cpp +++ b/src/network_utils.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "network_utils.h" diff --git a/src/node.cpp b/src/node.cpp index cb370f7c..c6b37636 100644 --- a/src/node.cpp +++ b/src/node.cpp @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "node.h" #include "request.h" @@ -29,24 +14,28 @@ constexpr std::chrono::minutes Node::NODE_GOOD_TIME; constexpr std::chrono::seconds Node::MAX_RESPONSE_TIME; Node::Node(const InfoHash& id, const SockAddr& addr, std::mt19937_64& rd, bool client) -: id(id), addr(addr), is_client(client), sockets_() + : id(id) + , addr(addr) + , is_client(client) + , sockets_() { - transaction_id = std::uniform_int_distribution{1}(rd); + transaction_id = std::uniform_int_distribution {1}(rd); } Node::Node(const InfoHash& id, SockAddr&& addr, std::mt19937_64& rd, bool client) -: id(id), addr(std::move(addr)), is_client(client), sockets_() + : id(id) + , addr(std::move(addr)) + , is_client(client) + , sockets_() { - transaction_id = std::uniform_int_distribution{1}(rd); + transaction_id = std::uniform_int_distribution {1}(rd); } /* This is our definition of a known-good node. */ bool Node::isGood(time_point now) const { - return not expired_ && - reply_time >= now - NODE_GOOD_TIME && - time >= now - NODE_EXPIRE_TIME; + return not expired_ && reply_time >= now - NODE_GOOD_TIME && time >= now - NODE_EXPIRE_TIME; } bool @@ -151,7 +140,7 @@ Node::closeSocket(Tid id) { if (id) { sockets_.erase(id); - //DHT_LOG.w("Closing socket (tid: %d), %lu remaining", socket->id, sockets_.size()); + // DHT_LOG.w("Closing socket (tid: %d), %lu remaining", socket->id, sockets_.size()); } } @@ -163,7 +152,8 @@ Node::toString() const return ss.str(); } -std::ostream& operator<< (std::ostream& s, const Node& h) +std::ostream& +operator<<(std::ostream& s, const Node& h) { s << h.id << " " << h.addr.toString(); return s; @@ -186,13 +176,14 @@ NodeExport::msgpack_unpack(msgpack::object o) if (maddr.via.bin.size > sizeof(sockaddr_storage)) throw msgpack::type_error(); id.msgpack_unpack(o.via.map.ptr[0].val); - addr = {(const sockaddr*)maddr.via.bin.ptr, (socklen_t)maddr.via.bin.size}; + addr = {(const sockaddr*) maddr.via.bin.ptr, (socklen_t) maddr.via.bin.size}; } -std::ostream& operator<< (std::ostream& s, const NodeExport& h) +std::ostream& +operator<<(std::ostream& s, const NodeExport& h) { msgpack::pack(s, h); return s; } -} +} // namespace dht diff --git a/src/node_cache.cpp b/src/node_cache.cpp index f10f9091..73b720de 100644 --- a/src/node_cache.cpp +++ b/src/node_cache.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "node_cache.h" @@ -29,12 +15,14 @@ NodeCache::~NodeCache() } Sp -NodeCache::getNode(const InfoHash& id, sa_family_t family) { +NodeCache::getNode(const InfoHash& id, sa_family_t family) +{ return cache(family).getNode(id); } Sp -NodeCache::getNode(const InfoHash& id, const SockAddr& addr, time_point now, bool confirm, bool client) { +NodeCache::getNode(const InfoHash& id, const SockAddr& addr, time_point now, bool confirm, bool client) +{ if (not id) return std::make_shared(id, addr, rd, client); return cache(addr.getFamily()).getNode(id, addr, now, confirm, client, rd); @@ -58,8 +46,7 @@ NodeCache::NodeMap::getCachedNodes(const InfoHash& id, size_t count) const return ret; }; - auto it_p = lower_bound(id), - it_n = it_p; + auto it_p = lower_bound(id), it_n = it_p; if (not empty()) dec_it(it_p); /* Create 2 separate iterator if we could */ @@ -67,12 +54,15 @@ NodeCache::NodeMap::getCachedNodes(const InfoHash& id, size_t count) const /* If one of the iterator is at the end, then take the other one If they are both in middle of somewhere comapre both and take the closest to the id. */ - if (it_p == cend()) it = it_n++; - else if (it_n == cend()) it = dec_it(it_p); - else it = id.xorCmp(it_p->first, it_n->first) < 0 ? dec_it(it_p) : it_n++; + if (it_p == cend()) + it = it_n++; + else if (it_n == cend()) + it = dec_it(it_p); + else + it = id.xorCmp(it_p->first, it_n->first) < 0 ? dec_it(it_p) : it_n++; if (auto n = it->second.lock()) - if ( not n->isExpired() and not n->isClient() ) + if (not n->isExpired() and not n->isClient()) nodes.emplace_back(std::move(n)); } @@ -103,7 +93,8 @@ NodeCache::NodeMap::getNode(const InfoHash& id) } Sp -NodeCache::NodeMap::getNode(const InfoHash& id, const SockAddr& addr, time_point now, bool confirm, bool client, std::mt19937_64& rd) +NodeCache::NodeMap::getNode( + const InfoHash& id, const SockAddr& addr, time_point now, bool confirm, bool client, std::mt19937_64& rd) { auto& nref = (*this)[id]; auto node = nref.lock(); @@ -121,7 +112,8 @@ NodeCache::NodeMap::getNode(const InfoHash& id, const SockAddr& addr, time_point } void -NodeCache::NodeMap::clearBadNodes() { +NodeCache::NodeMap::clearBadNodes() +{ for (auto it = cbegin(); it != cend();) { if (auto n = it->second.lock()) { n->reset(); @@ -134,7 +126,8 @@ NodeCache::NodeMap::clearBadNodes() { } void -NodeCache::NodeMap::setExpired() { +NodeCache::NodeMap::setExpired() +{ for (auto& wn : *this) if (auto n = wn.second.lock()) n->setExpired(); @@ -156,4 +149,4 @@ NodeCache::NodeMap::cleanup() } } -} +} // namespace dht diff --git a/src/op_cache.cpp b/src/op_cache.cpp index 8739577b..885130fe 100644 --- a/src/op_cache.cpp +++ b/src/op_cache.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "op_cache.h" namespace dht { @@ -21,7 +7,8 @@ namespace dht { constexpr const std::chrono::seconds OpCache::EXPIRATION; bool -OpValueCache::onValuesAdded(const std::vector>& vals, const system_clock::time_point& t) { +OpValueCache::onValuesAdded(const std::vector>& vals, const system_clock::time_point& t) +{ std::vector> newValues; for (const auto& v : vals) { auto viop = values.emplace(v->id, v); @@ -42,14 +29,15 @@ OpValueCache::onValuesAdded(const std::vector>& vals, const system_clo } bool -OpValueCache::onValuesExpired(const std::vector>& vals, const system_clock::time_point& t) { +OpValueCache::onValuesExpired(const std::vector>& vals, const system_clock::time_point& t) +{ std::vector> expiredValues; for (const auto& v : vals) { auto vit = values.find(v->id); if (vit != values.end()) { if (vit->second.updated > t) continue; - + vit->second.updated = t; vit->second.refCount--; if (not vit->second.refCount) { @@ -70,7 +58,7 @@ OpValueCache::onValuesExpired(const std::vector& vids, const system_c if (vit != values.end()) { if (vit->second.updated > t) continue; - + vit->second.updated = t; vit->second.refCount--; if (not vit->second.refCount) { @@ -83,7 +71,8 @@ OpValueCache::onValuesExpired(const std::vector& vids, const system_c } std::vector> -OpValueCache::get(const Value::Filter& filter) const { +OpValueCache::get(const Value::Filter& filter) const +{ std::vector> ret; if (not filter) ret.reserve(values.size()); @@ -94,7 +83,8 @@ OpValueCache::get(const Value::Filter& filter) const { } Sp -OpValueCache::get(Value::Id id) const { +OpValueCache::get(Value::Id id) const +{ auto v = values.find(id); if (v == values.end()) return {}; @@ -102,7 +92,8 @@ OpValueCache::get(Value::Id id) const { } std::vector> -OpValueCache::getValues() const { +OpValueCache::getValues() const +{ std::vector> ret; ret.reserve(values.size()); for (const auto& v : values) @@ -111,7 +102,8 @@ OpValueCache::getValues() const { } void -OpCache::onValuesAdded(const std::vector>& vals) { +OpCache::onValuesAdded(const std::vector>& vals) +{ if (not listeners.empty()) { std::vector list; list.reserve(listeners.size()); @@ -123,7 +115,8 @@ OpCache::onValuesAdded(const std::vector>& vals) { } void -OpCache::onValuesExpired(const std::vector>& vals) { +OpCache::onValuesExpired(const std::vector>& vals) +{ if (not listeners.empty()) { std::vector list; list.reserve(listeners.size()); @@ -135,7 +128,8 @@ OpCache::onValuesExpired(const std::vector>& vals) { } time_point -OpCache::getExpiration() const { +OpCache::getExpiration() const +{ if (not listeners.empty()) return time_point::max(); return lastRemoved + EXPIRATION; @@ -182,11 +176,10 @@ SearchCache::listen(const ValueCallback& get_cb, const Sp& q, Value::Filt // New query op = ops.emplace(q, std::make_unique()).first; auto& cache = *op->second; - cache.searchToken = onListen(q, [&](const std::vector>& values, bool expired){ - return cache.onValue(values, expired); - }, [&](ListenSyncStatus status) { - cache.onNodeChanged(status); - }); + cache.searchToken = onListen( + q, + [&](const std::vector>& values, bool expired) { return cache.onValue(values, expired); }, + [&](ListenSyncStatus status) { cache.onNodeChanged(status); }); } auto token = nextToken_++; if (nextToken_ == 0) @@ -195,7 +188,8 @@ SearchCache::listen(const ValueCallback& get_cb, const Sp& q, Value::Filt } bool -SearchCache::cancelListen(size_t gtoken, const time_point& now) { +SearchCache::cancelListen(size_t gtoken, const time_point& now) +{ for (auto& op : ops) { if (op.second->removeListener(gtoken, now)) { nextExpiration_ = std::min(nextExpiration_, op.second->getExpiration()); @@ -206,7 +200,8 @@ SearchCache::cancelListen(size_t gtoken, const time_point& now) { } void -SearchCache::cancelAll(const std::function& onCancel) { +SearchCache::cancelAll(const std::function& onCancel) +{ for (auto& op : ops) { auto cache = std::move(op.second); cache->removeAll(); @@ -216,7 +211,8 @@ SearchCache::cancelAll(const std::function& onCancel) { } time_point -SearchCache::expire(const time_point& now, const std::function& onCancel) { +SearchCache::expire(const time_point& now, const std::function& onCancel) +{ nextExpiration_ = time_point::max(); auto ret = nextExpiration_; for (auto it = ops.begin(); it != ops.end();) { @@ -249,7 +245,8 @@ SearchCache::get(const Value::Filter& f, const Sp& q, const GetCallback& } std::vector> -SearchCache::get(const Value::Filter& filter) const { +SearchCache::get(const Value::Filter& filter) const +{ if (ops.size() == 1) return ops.begin()->second->get(filter); std::map> c; @@ -265,11 +262,12 @@ SearchCache::get(const Value::Filter& filter) const { } Sp -SearchCache::get(Value::Id id) const { +SearchCache::get(Value::Id id) const +{ for (const auto& op : ops) if (auto v = op.second->get(id)) return v; return {}; } -} +} // namespace dht diff --git a/src/op_cache.h b/src/op_cache.h index b88f0e68..ce843334 100644 --- a/src/op_cache.h +++ b/src/op_cache.h @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "value.h" @@ -27,21 +13,28 @@ struct OpCacheValueStorage Sp data {}; unsigned refCount {1}; system_clock::time_point updated {system_clock::time_point::min()}; - explicit OpCacheValueStorage(Sp val) : data(std::move(val)) {} + explicit OpCacheValueStorage(Sp val) + : data(std::move(val)) + {} }; -class OpValueCache { +class OpValueCache +{ public: - OpValueCache(ValueCallback&& cb) noexcept : callback(std::forward(cb)) {} - explicit OpValueCache(OpValueCache&& o) noexcept : values(std::move(o.values)), callback(std::move(o.callback)) { + OpValueCache(ValueCallback&& cb) noexcept + : callback(std::forward(cb)) + {} + explicit OpValueCache(OpValueCache&& o) noexcept + : values(std::move(o.values)) + , callback(std::move(o.callback)) + { o.callback = {}; } - static ValueCallback cacheCallback(ValueCallback&& cb, std::function&& onCancel) { - return [ - cache = std::make_shared(std::forward(cb)), - onCancel = std::move(onCancel) - ](const std::vector>& vals, bool expired){ + static ValueCallback cacheCallback(ValueCallback&& cb, std::function&& onCancel) + { + return [cache = std::make_shared(std::forward(cb)), + onCancel = std::move(onCancel)](const std::vector>& vals, bool expired) { auto ret = cache->onValue(vals, expired); if (not ret) onCancel(); @@ -49,22 +42,35 @@ public: }; } - bool onValue(const std::vector>& vals, bool expired, const system_clock::time_point& t = system_clock::time_point::min()) { - return expired - ? onValuesExpired(vals, t) - : onValuesAdded(vals, t); + bool onValue(const std::vector>& vals, + bool expired, + const system_clock::time_point& t = system_clock::time_point::min()) + { + return expired ? onValuesExpired(vals, t) : onValuesAdded(vals, t); } - bool onValuesAdded(const std::vector>& vals, const system_clock::time_point& t = system_clock::time_point::min()); - bool onValuesExpired(const std::vector>& vals, const system_clock::time_point& t = system_clock::time_point::min()); - bool onValuesExpired(const std::vector& vals, const system_clock::time_point& t = system_clock::time_point::min()); + bool onValuesAdded(const std::vector>& vals, + const system_clock::time_point& t = system_clock::time_point::min()); + bool onValuesExpired(const std::vector>& vals, + const system_clock::time_point& t = system_clock::time_point::min()); + bool onValuesExpired(const std::vector& vals, + const system_clock::time_point& t = system_clock::time_point::min()); - void onNodeChanged(ListenSyncStatus status) { + void onNodeChanged(ListenSyncStatus status) + { switch (status) { - case ListenSyncStatus::ADDED: nodes++; break; - case ListenSyncStatus::REMOVED: nodes--; break; - case ListenSyncStatus::SYNCED : syncedNodes++; break; - case ListenSyncStatus::UNSYNCED: syncedNodes--; break; + case ListenSyncStatus::ADDED: + nodes++; + break; + case ListenSyncStatus::REMOVED: + nodes--; + break; + case ListenSyncStatus::SYNCED: + syncedNodes++; + break; + case ListenSyncStatus::UNSYNCED: + syncedNodes--; + break; } } @@ -85,70 +91,58 @@ private: ValueCallback callback; }; -class OpCache { +class OpCache +{ public: - OpCache() : cache([this](const std::vector>& vals, bool expired){ - if (expired) - onValuesExpired(vals); - else - onValuesAdded(vals); - return true; - }) {} + OpCache() + : cache([this](const std::vector>& vals, bool expired) { + if (expired) + onValuesExpired(vals); + else + onValuesAdded(vals); + return true; + }) + {} - bool onValue(const std::vector>& vals, bool expired) { - return cache.onValue(vals, expired); - } - void onNodeChanged(ListenSyncStatus status) { - cache.onNodeChanged(status); - } + bool onValue(const std::vector>& vals, bool expired) { return cache.onValue(vals, expired); } + void onNodeChanged(ListenSyncStatus status) { cache.onNodeChanged(status); } void onValuesAdded(const std::vector>& vals); void onValuesExpired(const std::vector>& vals); - bool addListener(size_t token, const ValueCallback& cb, const Sp& q, Value::Filter&& filter) { + bool addListener(size_t token, const ValueCallback& cb, const Sp& q, Value::Filter&& filter) + { auto cached = cache.get(filter); if (not cached.empty() and not cb(cached, false)) { return false; } - listeners.emplace(token, LocalListener{q, std::move(filter), cb}); + listeners.emplace(token, LocalListener {q, std::move(filter), cb}); return true; } - bool removeListener(size_t token, const time_point& now) { + bool removeListener(size_t token, const time_point& now) + { lastRemoved = now; return listeners.erase(token) > 0; } - void removeAll() { - listeners.clear(); - } + void removeAll() { listeners.clear(); } - bool isDone() { - return listeners.empty(); - } + bool isDone() { return listeners.empty(); } - std::vector> get(const Value::Filter& filter) const { - return cache.get(filter); - } + std::vector> get(const Value::Filter& filter) const { return cache.get(filter); } - Sp get(Value::Id id) const { - return cache.get(id); - } + Sp get(Value::Id id) const { return cache.get(id); } - bool isSynced() const { - return cache.isSynced(); - } + bool isSynced() const { return cache.isSynced(); } - bool isExpired(const time_point& now) const { - return listeners.empty() and (lastRemoved + EXPIRATION < now); - } + bool isExpired(const time_point& now) const { return listeners.empty() and (lastRemoved + EXPIRATION < now); } time_point getExpiration() const; - size_t size() const { - return cache.size(); - } + size_t size() const { return cache.size(); } size_t searchToken {0}; + private: constexpr static const std::chrono::seconds EXPIRATION {60}; OpCache(const OpCache&) = delete; @@ -159,7 +153,8 @@ private: time_point lastRemoved {clock::now()}; }; -class SearchCache { +class SearchCache +{ public: SearchCache() {} SearchCache(SearchCache&&) = default; @@ -171,15 +166,14 @@ public: void cancelAll(const std::function& onCancel); time_point expire(const time_point& now, const std::function& onCancel); - time_point getExpiration() const { - return nextExpiration_; - } + time_point getExpiration() const { return nextExpiration_; } bool get(const Value::Filter& f, const Sp& q, const GetCallback& gcb, const DoneCallback& dcb) const; std::vector> get(const Value::Filter& filter) const; Sp get(Value::Id id) const; - std::pair size() const { + std::pair size() const + { size_t tot = 0; for (const auto& c : ops) tot += c.second->size(); @@ -199,4 +193,4 @@ private: time_point nextExpiration_ {time_point::max()}; }; -} +} // namespace dht diff --git a/src/parsed_message.h b/src/parsed_message.h index b73fc3b1..dcd3384c 100644 --- a/src/parsed_message.h +++ b/src/parsed_message.h @@ -1,20 +1,6 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - #pragma once +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT +#pragma once #include "infohash.h" #include "sockaddr.h" @@ -66,7 +52,9 @@ static constexpr auto QUERY_PUT = "put"sv; static constexpr auto QUERY_LISTEN = "listen"sv; static constexpr auto QUERY_REFRESH = "refresh"sv; -Tid unpackTid(const msgpack::object& o) { +Tid +unpackTid(const msgpack::object& o) +{ switch (o.type) { case msgpack::type::POSITIVE_INTEGER: return o.as(); @@ -75,7 +63,8 @@ Tid unpackTid(const msgpack::object& o) { } } -struct ParsedMessage { +struct ParsedMessage +{ MessageType type; /* Node ID of the sender */ InfoHash id; @@ -96,7 +85,7 @@ struct ParsedMessage { /* the value id (announce confirmation) */ Value::Id value_id {0}; /* time when value was first created */ - time_point created { time_point::max() }; + time_point created {time_point::max()}; /* IPv4 nodes in response to a 'find' request */ Blob nodes4_raw, nodes6_raw; std::vector> nodes4, nodes6; @@ -131,18 +120,15 @@ ParsedMessage::append(const ParsedMessage& block) bool ret(false); for (const auto& ve : block.value_parts) { auto part_val = value_parts.find(ve.first); - if (part_val == value_parts.end() - || part_val->second.second.size() >= part_val->second.first) + if (part_val == value_parts.end() || part_val->second.second.size() >= part_val->second.first) continue; // TODO: handle out-of-order packets if (ve.second.first != part_val->second.second.size()) { - //std::cout << "skipping out-of-order packet" << std::endl; + // std::cout << "skipping out-of-order packet" << std::endl; continue; } ret = true; - part_val->second.second.insert(part_val->second.second.end(), - ve.second.second.begin(), - ve.second.second.end()); + part_val->second.second.insert(part_val->second.second.end(), ve.second.second.begin(), ve.second.second.end()); } return ret; } @@ -152,13 +138,14 @@ ParsedMessage::complete() { for (auto& e : value_parts) { if (e.second.first > e.second.second.size()) { - //std::cout << "uncomplete part " << e.first << ": " << e.second.second.size() << "/" << e.second.first << std::endl; + // std::cout << "uncomplete part " << e.first << ": " << e.second.second.size() << "/" << e.second.first << + // std::endl; return false; } } for (auto& e : value_parts) { msgpack::unpacked msg; - msgpack::unpack(msg, (const char*)e.second.second.data(), e.second.second.size()); + msgpack::unpack(msg, (const char*) e.second.second.data(), e.second.second.size()); values.emplace_back(std::make_shared(msg.get())); } return true; @@ -167,9 +154,11 @@ ParsedMessage::complete() void ParsedMessage::msgpack_unpack(const msgpack::object& msg) { - if (msg.type != msgpack::type::MAP) throw msgpack::type_error(); + if (msg.type != msgpack::type::MAP) + throw msgpack::type_error(); - struct ParsedMsg { + struct ParsedMsg + { msgpack::object* y; msgpack::object* r; msgpack::object* u; @@ -259,7 +248,8 @@ ParsedMessage::msgpack_unpack(const msgpack::object& msg) error_code = parsed.e->via.array.ptr[0].as(); } - struct ParsedReq { + struct ParsedReq + { msgpack::object* values; msgpack::object* fields; msgpack::object* sa; @@ -315,12 +305,12 @@ ParsedMessage::msgpack_unpack(const msgpack::object& msg) addr.setFamily(AF_INET); auto& a = addr.getIPv4(); a.sin_port = 0; - std::copy_n(parsedReq.sa->via.bin.ptr, l, (char*)&a.sin_addr); + std::copy_n(parsedReq.sa->via.bin.ptr, l, (char*) &a.sin_addr); } else if (l == sizeof(in6_addr)) { addr.setFamily(AF_INET6); auto& a = addr.getIPv6(); a.sin6_port = 0; - std::copy_n(parsedReq.sa->via.bin.ptr, l, (char*)&a.sin6_addr); + std::copy_n(parsedReq.sa->via.bin.ptr, l, (char*) &a.sin6_addr); } } else addr = {}; @@ -334,12 +324,12 @@ ParsedMessage::msgpack_unpack(const msgpack::object& msg) // Skip oversize values with a small margin for header overhead if (packed_v.via.u64 > MAX_VALUE_SIZE + 32) continue; - value_parts.emplace(i, std::make_pair(packed_v.via.u64, Blob{})); + value_parts.emplace(i, std::make_pair(packed_v.via.u64, Blob {})); } else { try { values.emplace_back(std::make_shared(parsedReq.values->via.array.ptr[i])); } catch (const std::exception& e) { - //DHT_LOG_WARN("Error reading value: %s", e.what()); + // DHT_LOG_WARN("Error reading value: %s", e.what()); } } } @@ -353,9 +343,10 @@ ParsedMessage::msgpack_unpack(const msgpack::object& msg) for (size_t i = 0; i < val_num; ++i) { try { auto v = std::make_shared(); - v->msgpack_unpack_fields(vfields, *rvalues, i*vfields.size()); + v->msgpack_unpack_fields(vfields, *rvalues, i * vfields.size()); fields.emplace_back(std::move(v)); - } catch (const std::exception& e) { } + } catch (const std::exception& e) { + } } } } else { @@ -367,15 +358,16 @@ ParsedMessage::msgpack_unpack(const msgpack::object& msg) if (parsedReq.want->type != msgpack::type::ARRAY) throw msgpack::type_error(); want = 0; - for (unsigned i=0; ivia.array.size; i++) { + for (unsigned i = 0; i < parsedReq.want->via.array.size; i++) { auto& val = parsedReq.want->via.array.ptr[i]; try { auto w = val.as(); if (w == AF_INET) want |= WANT4; - else if(w == AF_INET6) + else if (w == AF_INET6) want |= WANT6; - } catch (const std::exception& e) {}; + } catch (const std::exception& e) { + }; } } else { want = -1; diff --git a/src/peer_discovery.cpp b/src/peer_discovery.cpp index 1d116bd6..87181f8d 100644 --- a/src/peer_discovery.cpp +++ b/src/peer_discovery.cpp @@ -1,21 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * Vsevolod Ivanov - * Adrien Béraud - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "peer_discovery.h" #include "network_utils.h" @@ -38,11 +22,14 @@ constexpr char MULTICAST_ADDRESS_IPV6[] = "ff08::101"; class PeerDiscovery::DomainPeerDiscovery { public: - DomainPeerDiscovery(asio::ip::udp domain, in_port_t port, Sp ioContext = {}, Sp logger = {}); + DomainPeerDiscovery(asio::ip::udp domain, + in_port_t port, + Sp ioContext = {}, + Sp logger = {}); ~DomainPeerDiscovery(); void startDiscovery(std::string_view type, ServiceDiscoveredCallback callback); - void startPublish(std::string_view type, const msgpack::sbuffer &pack_buf); + void startPublish(std::string_view type, const msgpack::sbuffer& pack_buf); void stop(); @@ -52,20 +39,19 @@ public: void connectivityChanged(); void stopConnectivityChanged(); + private: Sp logger_; - //dmtx_ for callbackmap_ and drunning_ (write) + // dmtx_ for callbackmap_ and drunning_ (write) std::mutex dmtx_; - //mtx_ for messages_ and lrunning (listen) + // mtx_ for messages_ and lrunning (listen) std::mutex mtx_; std::shared_ptr ioContext_; - static constexpr dht::duration PeerDiscovery_PERIOD_MAX{ - std::chrono::minutes(1)}; - static constexpr std::chrono::seconds PeerDiscovery_PERIOD{10}; + static constexpr dht::duration PeerDiscovery_PERIOD_MAX {std::chrono::minutes(1)}; + static constexpr std::chrono::seconds PeerDiscovery_PERIOD {10}; asio::steady_timer peerDiscoveryTimer; - std::chrono::steady_clock::duration peerDiscovery_period{ - PeerDiscovery_PERIOD}; + std::chrono::steady_clock::duration peerDiscovery_period {PeerDiscovery_PERIOD}; asio::ip::udp::socket sockFd_; asio::ip::udp::endpoint sockAddrSend_; @@ -91,13 +77,16 @@ private: void reDiscover(); }; -PeerDiscovery::DomainPeerDiscovery::DomainPeerDiscovery(asio::ip::udp domain, in_port_t port, Sp ioContext, Sp logger) +PeerDiscovery::DomainPeerDiscovery::DomainPeerDiscovery(asio::ip::udp domain, + in_port_t port, + Sp ioContext, + Sp logger) : logger_(logger) , ioContext_(ioContext) , peerDiscoveryTimer(*ioContext_) , sockFd_(*ioContext_, domain) - , sockAddrSend_(asio::ip::make_address(domain.family() == AF_INET ? MULTICAST_ADDRESS_IPV4 - : MULTICAST_ADDRESS_IPV6), port) + , sockAddrSend_(asio::ip::make_address(domain.family() == AF_INET ? MULTICAST_ADDRESS_IPV4 : MULTICAST_ADDRESS_IPV6), + port) { try { sockFd_.set_option(asio::ip::multicast::join_group(sockAddrSend_.address())); @@ -105,23 +94,23 @@ PeerDiscovery::DomainPeerDiscovery::DomainPeerDiscovery(asio::ip::udp domain, in sockFd_.bind({domain, port}); } catch (const std::exception& e) { #ifdef __ANDROID__ - if(domain.family() == AF_INET && strcmp(e.what(), "set_option: No such device") == 0) { - try{ + if (domain.family() == AF_INET && strcmp(e.what(), "set_option: No such device") == 0) { + try { sockFd_.set_option(asio::ip::udp::socket::reuse_address(true)); auto mc_interface = workaround::get_interface(); sockFd_.set_option(asio::ip::multicast::outbound_interface(mc_interface)); sockFd_.set_option(asio::ip::multicast::join_group(sockAddrSend_.address().to_v4(), mc_interface)); sockFd_.bind({domain, port}); - } catch(const std::exception& e){ + } catch (const std::exception& e) { if (logger_) logger_->error("Unable to start peer discovery using android workaround: {}", e.what()); } - } - else + } else #endif - if (logger_) + if (logger_) logger_->error("Unable to start peer discovery for {}: {}", - domain.family() == AF_INET ? "IPv4" : "IPv6", e.what()); + domain.family() == AF_INET ? "IPv4" : "IPv6", + e.what()); } } @@ -138,10 +127,10 @@ PeerDiscovery::DomainPeerDiscovery::startDiscovery(std::string_view type, Servic callbackmap_[std::string(type)] = callback; if (not drunning_) { drunning_ = true; - asio::post(*ioContext_, [this] () { - loopListener(); - query(sockAddrSend_); - }); + asio::post(*ioContext_, [this]() { + loopListener(); + query(sockAddrSend_); + }); } } @@ -151,47 +140,50 @@ PeerDiscovery::DomainPeerDiscovery::loopListener() std::lock_guard lck(dmtx_); if (not drunning_) return; - sockFd_.async_receive_from(asio::buffer(receiveBuf_), receiveFrom_, [this](const asio::error_code& error, size_t bytes) { - if (error == asio::error::operation_aborted) - return; - if (error) { - if (logger_) - logger_->e("Error receiving message: %s", error.message().c_str()); - } - try { - auto rcv = msgpack::unpack(receiveBuf_.data(), bytes); - msgpack::object obj = rcv.get(); + sockFd_.async_receive_from(asio::buffer(receiveBuf_), + receiveFrom_, + [this](const asio::error_code& error, size_t bytes) { + if (error == asio::error::operation_aborted) + return; + if (error) { + if (logger_) + logger_->e("Error receiving message: %s", error.message().c_str()); + } + try { + auto rcv = msgpack::unpack(receiveBuf_.data(), bytes); + msgpack::object obj = rcv.get(); - if (obj.type == msgpack::type::STR) { - if (lrunning_ and obj.as() == "q"sv) - publish(receiveFrom_); - } else if (obj.type == msgpack::type::MAP) { - for (unsigned i = 0; i < obj.via.map.size; i++) { - auto& o = obj.via.map.ptr[i]; - if (o.key.type != msgpack::type::STR) - continue; - ServiceDiscoveredCallback cb; - { - std::lock_guard lck(dmtx_); - if (drunning_) { - auto callback = callbackmap_.find(o.key.as()); - if (callback != callbackmap_.end()) - cb = callback->second; - } else - return; - } - if (cb) - cb(std::move(o.val), SockAddr{ receiveFrom_.data(), (socklen_t)receiveFrom_.size() }); - } - } else { - throw msgpack::type_error{}; - } - } catch (const std::exception& e) { - if (logger_) - logger_->e("Error receiving packet: %s", e.what()); - } - loopListener(); - }); + if (obj.type == msgpack::type::STR) { + if (lrunning_ and obj.as() == "q"sv) + publish(receiveFrom_); + } else if (obj.type == msgpack::type::MAP) { + for (unsigned i = 0; i < obj.via.map.size; i++) { + auto& o = obj.via.map.ptr[i]; + if (o.key.type != msgpack::type::STR) + continue; + ServiceDiscoveredCallback cb; + { + std::lock_guard lck(dmtx_); + if (drunning_) { + auto callback = callbackmap_.find(o.key.as()); + if (callback != callbackmap_.end()) + cb = callback->second; + } else + return; + } + if (cb) + cb(std::move(o.val), + SockAddr {receiveFrom_.data(), (socklen_t) receiveFrom_.size()}); + } + } else { + throw msgpack::type_error {}; + } + } catch (const std::exception& e) { + if (logger_) + logger_->e("Error receiving packet: %s", e.what()); + } + loopListener(); + }); } void @@ -204,15 +196,14 @@ PeerDiscovery::DomainPeerDiscovery::query(const asio::ip::udp::endpoint& peer) msgpack::sbuffer pbuf_request; msgpack::pack(pbuf_request, "q"); - sockFd_.async_send_to(asio::buffer(pbuf_request.data(), pbuf_request.size()), peer, - [logger=logger_, peer] (const asio::error_code& ec, size_t) - { - if (ec and (ec != asio::error::operation_aborted) and logger) - logger->w("Error sending packet to: %s with err: %s", - peer.address().to_string().c_str(), - ec.message().c_str()); - } - ); + sockFd_.async_send_to(asio::buffer(pbuf_request.data(), pbuf_request.size()), + peer, + [logger = logger_, peer](const asio::error_code& ec, size_t) { + if (ec and (ec != asio::error::operation_aborted) and logger) + logger->w("Error sending packet to: %s with err: %s", + peer.address().to_string().c_str(), + ec.message().c_str()); + }); } void @@ -222,20 +213,18 @@ PeerDiscovery::DomainPeerDiscovery::publish(const asio::ip::udp::endpoint& peer) if (not lrunning_) return; - sockFd_.async_send_to(asio::buffer((const void*)sbuf_.data(), sbuf_.size()), peer, - [logger=logger_, peer] (const asio::error_code& ec, size_t) - { - if (ec and (ec != asio::error::operation_aborted) and logger) - logger->w("Error sending packet to: %s with err: %s", - peer.address().to_string().c_str(), - ec.message().c_str()); - } - ); + sockFd_.async_send_to(asio::buffer((const void*) sbuf_.data(), sbuf_.size()), + peer, + [logger = logger_, peer](const asio::error_code& ec, size_t) { + if (ec and (ec != asio::error::operation_aborted) and logger) + logger->w("Error sending packet to: %s with err: %s", + peer.address().to_string().c_str(), + ec.message().c_str()); + }); } - void -PeerDiscovery::DomainPeerDiscovery::startPublish(std::string_view type, const msgpack::sbuffer &pack_buf) +PeerDiscovery::DomainPeerDiscovery::startPublish(std::string_view type, const msgpack::sbuffer& pack_buf) { msgpack::sbuffer pack_buf_c(pack_buf.size()); pack_buf_c.write(pack_buf.data(), pack_buf.size()); @@ -244,7 +233,7 @@ PeerDiscovery::DomainPeerDiscovery::startPublish(std::string_view type, const ms messages_[std::string(type)] = std::move(pack_buf_c); reloadMessages(); lrunning_ = true; - asio::post(*ioContext_, [this] () { publish(sockAddrSend_); }); + asio::post(*ioContext_, [this]() { publish(sockAddrSend_); }); } bool @@ -321,26 +310,23 @@ PeerDiscovery::DomainPeerDiscovery::reDiscover() sockFd_.set_option(asio::ip::multicast::join_group(sockAddrSend_.address()), ec); if (ec and logger_) - logger_->w("Unable to multicast on %s: %s", - sockAddrSend_.address().to_string().c_str(), - ec.message().c_str()); + logger_->w("Unable to multicast on %s: %s", sockAddrSend_.address().to_string().c_str(), ec.message().c_str()); query(sockAddrSend_); } void PeerDiscovery::DomainPeerDiscovery::connectivityChanged() { - asio::post(*ioContext_, [this] () { + asio::post(*ioContext_, [this]() { reDiscover(); publish(sockAddrSend_); }); if (logger_) logger_->d("PeerDiscovery: connectivity changed"); - - if (peerDiscovery_period == PeerDiscovery_PERIOD_MAX ){ + + if (peerDiscovery_period == PeerDiscovery_PERIOD_MAX) { peerDiscovery_period = PeerDiscovery_PERIOD; - } - else{ + } else { peerDiscoveryTimer.expires_after(peerDiscovery_period); peerDiscoveryTimer.async_wait([this](const asio::error_code& ec) { if (ec == asio::error::operation_aborted) @@ -351,7 +337,9 @@ PeerDiscovery::DomainPeerDiscovery::connectivityChanged() } } -void PeerDiscovery::DomainPeerDiscovery::stopConnectivityChanged() { +void +PeerDiscovery::DomainPeerDiscovery::stopConnectivityChanged() +{ peerDiscoveryTimer.cancel(); peerDiscovery_period = PeerDiscovery_PERIOD; } @@ -369,8 +357,7 @@ PeerDiscovery::PeerDiscovery(in_port_t port, Sp ioContext, Sp< ioContext->run(); if (logger) logger->d("[peerdiscovery] io_context stopped"); - } - catch (const std::exception& ex){ + } catch (const std::exception& ex) { if (logger) logger->e("[peerdiscovery] run error: %s", ex.what()); } @@ -379,19 +366,20 @@ PeerDiscovery::PeerDiscovery(in_port_t port, Sp ioContext, Sp< try { peerDiscovery4_.reset(new DomainPeerDiscovery(asio::ip::udp::v4(), port, ioContext, logger)); - } catch(const std::exception& e){ + } catch (const std::exception& e) { if (logger) logger->e("[peerdiscovery] Unable to start IPv4: %s", e.what()); } try { peerDiscovery6_.reset(new DomainPeerDiscovery(asio::ip::udp::v6(), port, ioContext, logger)); - } catch(const std::exception& e) { + } catch (const std::exception& e) { if (logger) logger->e("[peerdiscovery] Unable to start IPv6: %s", e.what()); } } -PeerDiscovery::~PeerDiscovery() { +PeerDiscovery::~PeerDiscovery() +{ stop(); if (ioContext_) ioContext_->stop(); @@ -402,32 +390,40 @@ PeerDiscovery::~PeerDiscovery() { void PeerDiscovery::startDiscovery(std::string_view type, ServiceDiscoveredCallback callback) { - if (peerDiscovery4_) peerDiscovery4_->startDiscovery(type, callback); - if (peerDiscovery6_) peerDiscovery6_->startDiscovery(type, callback); + if (peerDiscovery4_) + peerDiscovery4_->startDiscovery(type, callback); + if (peerDiscovery6_) + peerDiscovery6_->startDiscovery(type, callback); } void PeerDiscovery::startPublish(std::string_view type, const msgpack::sbuffer& pack_buf) { - if (peerDiscovery4_) peerDiscovery4_->startPublish(type, pack_buf); - if (peerDiscovery6_) peerDiscovery6_->startPublish(type, pack_buf); + if (peerDiscovery4_) + peerDiscovery4_->startPublish(type, pack_buf); + if (peerDiscovery6_) + peerDiscovery6_->startPublish(type, pack_buf); } void PeerDiscovery::startPublish(sa_family_t domain, std::string_view type, const msgpack::sbuffer& pack_buf) { if (domain == AF_INET) { - if (peerDiscovery4_) peerDiscovery4_->startPublish(type, pack_buf); + if (peerDiscovery4_) + peerDiscovery4_->startPublish(type, pack_buf); } else if (domain == AF_INET6) { - if (peerDiscovery6_) peerDiscovery6_->startPublish(type, pack_buf); + if (peerDiscovery6_) + peerDiscovery6_->startPublish(type, pack_buf); } } void PeerDiscovery::stop() { - if (peerDiscovery4_) peerDiscovery4_->stop(); - if (peerDiscovery6_) peerDiscovery6_->stop(); + if (peerDiscovery4_) + peerDiscovery4_->stop(); + if (peerDiscovery6_) + peerDiscovery6_->stop(); } bool @@ -466,9 +462,11 @@ PeerDiscovery::connectivityChanged() peerDiscovery6_->connectivityChanged(); } -void PeerDiscovery::stopConnectivityChanged() { - if (peerDiscovery4_) - peerDiscovery4_->stopConnectivityChanged(); +void +PeerDiscovery::stopConnectivityChanged() +{ + if (peerDiscovery4_) + peerDiscovery4_->stopConnectivityChanged(); if (peerDiscovery6_) peerDiscovery6_->stopConnectivityChanged(); } diff --git a/src/request.h b/src/request.h index 92f85e84..c82dee70 100644 --- a/src/request.h +++ b/src/request.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "net.h" @@ -36,19 +21,14 @@ struct ParsedMessage; * desitned to specific node and std::function callbacks to execute when the * request is done. */ -struct Request { +struct Request +{ friend class dht::net::NetworkEngine; - Sp node {}; /* the node to whom the request is destined. */ + Sp node {}; /* the node to whom the request is destined. */ time_point reply_time {time_point::min()}; /* time when we received the response to the request. */ - enum class State - { - PENDING, - CANCELLED, - EXPIRED, - COMPLETED - }; + enum class State { PENDING, CANCELLED, EXPIRED, COMPLETED }; bool expired() const { return state_ == State::EXPIRED; } bool completed() const { return state_ == State::COMPLETED; } @@ -56,35 +36,59 @@ struct Request { bool pending() const { return state_ == State::PENDING; } bool over() const { return not pending(); } State getState() const { return state_; } - char getStateChar() const { + char getStateChar() const + { switch (state_) { - case State::PENDING: return 'f'; - case State::CANCELLED: return 'c'; - case State::EXPIRED: return 'e'; - case State::COMPLETED: return 'a'; - default: return '?'; + case State::PENDING: + return 'f'; + case State::CANCELLED: + return 'c'; + case State::EXPIRED: + return 'e'; + case State::COMPLETED: + return 'a'; + default: + return '?'; } } - Request(State state = State::PENDING) : state_(state) {} - Request(MessageType type, Tid tid, + Request(State state = State::PENDING) + : state_(state) + {} + Request(MessageType type, + Tid tid, Sp node, Blob&& msg, std::function on_done, - std::function on_expired) : - node(std::move(node)), tid(tid), type(type), on_done(std::move(on_done)), on_expired(std::move(on_expired)), msg(std::move(msg)) { } - Request(MessageType type, Tid tid, + std::function on_expired) + : node(std::move(node)) + , tid(tid) + , type(type) + , on_done(std::move(on_done)) + , on_expired(std::move(on_expired)) + , msg(std::move(msg)) + {} + Request(MessageType type, + Tid tid, Sp node, Blob&& msg, std::function on_done, std::function on_error, - std::function on_expired) : - node(std::move(node)), tid(tid), type(type), on_done(std::move(on_done)), on_error(std::move(on_error)), on_expired(std::move(on_expired)), msg(std::move(msg)) { } + std::function on_expired) + : node(std::move(node)) + , tid(tid) + , type(type) + , on_done(std::move(on_done)) + , on_error(std::move(on_error)) + , on_expired(std::move(on_expired)) + , msg(std::move(msg)) + {} Tid getTid() const { return tid; } MessageType getType() const { return type; } - void setExpired() { + void setExpired() + { if (pending()) { state_ = Request::State::EXPIRED; if (on_expired) @@ -92,14 +96,16 @@ struct Request { clear(); } } - void setDone(ParsedMessage&& msg) { + void setDone(ParsedMessage&& msg) + { if (pending()) { state_ = Request::State::COMPLETED; on_done(*this, std::forward(msg)); clear(); } } - bool setError(DhtProtocolException&& e) { + bool setError(DhtProtocolException&& e) + { if (pending()) { state_ = Request::State::EXPIRED; bool handled = on_error and on_error(*this, std::forward(e)); @@ -109,7 +115,8 @@ struct Request { return true; } - void cancel() { + void cancel() + { if (pending()) { state_ = State::CANCELLED; clear(); @@ -119,11 +126,13 @@ struct Request { private: static const constexpr size_t MAX_ATTEMPT_COUNT {3}; - bool isExpired(time_point now) const { + bool isExpired(time_point now) const + { return pending() and now > last_try + attempt_duration and attempt_count >= Request::MAX_ATTEMPT_COUNT; } - void clear() { + void clear() + { on_done = {}; on_error = {}; on_expired = {}; @@ -135,18 +144,18 @@ private: const MessageType type {}; State state_ {State::PENDING}; - unsigned attempt_count {0}; /* number of attempt to process the request. */ - duration attempt_duration {((duration)Node::MAX_RESPONSE_TIME)/2}; - time_point start {time_point::min()}; /* time when the request is created. */ - time_point last_try {time_point::min()}; /* time of the last attempt to process the request. */ + unsigned attempt_count {0}; /* number of attempt to process the request. */ + duration attempt_duration {((duration) Node::MAX_RESPONSE_TIME) / 2}; + time_point start {time_point::min()}; /* time when the request is created. */ + time_point last_try {time_point::min()}; /* time of the last attempt to process the request. */ std::function on_done {}; std::function on_error {}; std::function on_expired {}; - Blob msg {}; /* the serialized message. */ + Blob msg {}; /* the serialized message. */ std::vector parts; }; } /* namespace net */ -} +} // namespace dht diff --git a/src/routing_table.cpp b/src/routing_table.cpp index 0614b2e0..6d1caae4 100644 --- a/src/routing_table.cpp +++ b/src/routing_table.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "routing_table.h" @@ -29,17 +15,19 @@ Bucket::randomNode(std::mt19937_64& rd) { if (nodes.empty()) return nullptr; - unsigned expired_node_count = std::count_if(nodes.cbegin(), nodes.cend(), [](const decltype(nodes)::value_type& node) { - return node->isExpired(); - }); + unsigned expired_node_count = std::count_if(nodes.cbegin(), + nodes.cend(), + [](const decltype(nodes)::value_type& node) { + return node->isExpired(); + }); auto prioritize_not_expired = expired_node_count < nodes.size(); - std::uniform_int_distribution rand_node(0, prioritize_not_expired - ? nodes.size() - expired_node_count - 1 - : nodes.size()-1); + std::uniform_int_distribution rand_node(0, + prioritize_not_expired ? nodes.size() - expired_node_count - 1 + : nodes.size() - 1); unsigned nn = rand_node(rd); for (auto& n : nodes) { - if (not (prioritize_not_expired and n->isExpired())) { + if (not(prioritize_not_expired and n->isExpired())) { if (not nn--) return n; } @@ -47,11 +35,12 @@ Bucket::randomNode(std::mt19937_64& rd) return nodes.back(); } -void Bucket::sendCachedPing(net::NetworkEngine& ne) +void +Bucket::sendCachedPing(net::NetworkEngine& ne) { if (not cached) return; - //DHT_LOG.d(b.cached->id, "[node %s] sending ping to cached node", cached->toString().c_str()); + // DHT_LOG.d(b.cached->id, "[node %s] sending ping to cached node", cached->toString().c_str()); ne.sendPing(cached, nullptr, nullptr); cached = {}; } @@ -63,16 +52,16 @@ RoutingTable::randomId(const RoutingTable::const_iterator& it, std::mt19937_64& int bit2 = std::next(it) != end() ? std::next(it)->first.lowbit() : -1; int bit = std::max(bit1, bit2) + 1; - if (bit >= 8*(int)HASH_LEN) + if (bit >= 8 * (int) HASH_LEN) return it->first; #ifdef _WIN32 - std::uniform_int_distribution rand_byte{ 0, std::numeric_limits::max() }; + std::uniform_int_distribution rand_byte {0, std::numeric_limits::max()}; #else std::uniform_int_distribution rand_byte; #endif - int b = bit/8; + int b = bit / 8; InfoHash id_return; std::copy_n(it->first.cbegin(), b, id_return.begin()); id_return[b] = it->first[b] & (0xFF00 >> (bit % 8)); @@ -86,7 +75,7 @@ InfoHash RoutingTable::middle(const RoutingTable::const_iterator& it) const { unsigned bit = depth(it); - if (bit >= 8*HASH_LEN) + if (bit >= 8 * HASH_LEN) throw std::out_of_range("End of table"); InfoHash id = it->first; @@ -101,7 +90,7 @@ RoutingTable::depth(const RoutingTable::const_iterator& it) const return 0; int bit1 = it->first.lowbit(); int bit2 = std::next(it) != end() ? std::next(it)->first.lowbit() : -1; - return std::max(bit1, bit2)+1; + return std::max(bit1, bit2) + 1; } std::vector> @@ -111,18 +100,18 @@ RoutingTable::findClosestNodes(const InfoHash id, time_point now, size_t count) nodes.reserve(count); auto bucket = findBucket(id); - if (bucket == end()) { return nodes; } + if (bucket == end()) { + return nodes; + } - auto sortedBucketInsert = [&](const Bucket &b) { + auto sortedBucketInsert = [&](const Bucket& b) { for (auto n : b.nodes) { if (not n->isGood(now)) continue; - auto here = std::find_if(nodes.begin(), nodes.end(), - [&id,&n](Sp &node) { - return id.xorCmp(n->id, node->id) < 0; - } - ); + auto here = std::find_if(nodes.begin(), nodes.end(), [&id, &n](Sp& node) { + return id.xorCmp(n->id, node->id) < 0; + }); nodes.insert(here, n); } }; @@ -200,9 +189,12 @@ RoutingTable::split(const RoutingTable::iterator& b) } bool -RoutingTable::onNewNode(const Sp& node, int confirm, const time_point& now, const InfoHash& myid, net::NetworkEngine& ne) { +RoutingTable::onNewNode( + const Sp& node, int confirm, const time_point& now, const InfoHash& myid, net::NetworkEngine& ne) +{ auto b = findBucket(node->id); - if (b == end()) return false; + if (b == end()) + return false; if (confirm == 2) b->time = now; @@ -215,7 +207,7 @@ RoutingTable::onNewNode(const Sp& node, int confirm, const time_point& now bool mybucket = contains(b, myid); if (mybucket) { grow_time = now; - //scheduler.edit(nextNodesConfirmation, now); + // scheduler.edit(nextNodesConfirmation, now); } if (b->nodes.size() >= TARGET_NODES) { @@ -235,7 +227,7 @@ RoutingTable::onNewNode(const Sp& node, int confirm, const time_point& now if (not n->isGood(now)) { dubious = true; if (not n->isPendingMessage()) { - //DHT_LOG.d(n->id, "[node %s] sending ping to dubious node", n->toString().c_str()); + // DHT_LOG.d(n->id, "[node %s] sending ping to dubious node", n->toString().c_str()); ne.sendPing(n, nullptr, nullptr); break; } @@ -243,7 +235,7 @@ RoutingTable::onNewNode(const Sp& node, int confirm, const time_point& now } if ((mybucket || (is_client and depth(b) < 6)) && (!dubious || size() == 1)) { - //DHT_LOG.d("Splitting from depth %u", depth(b)); + // DHT_LOG.d("Splitting from depth %u", depth(b)); b->sendCachedPing(ne); split(b); return onNewNode(node, confirm, now, myid, ne); @@ -259,6 +251,4 @@ RoutingTable::onNewNode(const Sp& node, int confirm, const time_point& now return true; } - - -} +} // namespace dht diff --git a/src/search.h b/src/search.h index 8413ed31..cb231ceb 100644 --- a/src/search.h +++ b/src/search.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "value.h" @@ -28,7 +13,8 @@ namespace dht { /** * A single "get" operation data */ -struct Dht::Get { +struct Dht::Get +{ time_point start; Value::Filter filter; Sp query; @@ -40,22 +26,26 @@ struct Dht::Get { /** * A single "put" operation data */ -struct Dht::Announce { +struct Dht::Announce +{ bool permanent; Sp value; time_point created; std::vector callbacks; }; -struct Dht::SearchNode { - - struct AnnounceStatus { +struct Dht::SearchNode +{ + struct AnnounceStatus + { Sp req {}; Sp refresh {}; time_point refresh_time; - AnnounceStatus(){}; - AnnounceStatus(Sp r, time_point t): req(std::move(r)), refresh_time(t) - {} + AnnounceStatus() {}; + AnnounceStatus(Sp r, time_point t) + : req(std::move(r)) + , refresh_time(t) + {} }; /** * Foreach value id, we keep track of a pair (net::Request, time_point) where the @@ -69,17 +59,21 @@ struct Dht::SearchNode { */ using SyncStatus = std::map, Sp>; - struct CachedListenStatus { + struct CachedListenStatus + { ValueCache cache; Sp refresh {}; Sp cacheExpirationJob {}; Sp req {}; Tid socketId {0}; CachedListenStatus(ValueStateCallback&& cb, SyncCallback scb, Tid sid) - : cache(std::forward(cb), std::forward(scb)), socketId(sid) {} + : cache(std::forward(cb), std::forward(scb)) + , socketId(sid) + {} CachedListenStatus(CachedListenStatus&&) = delete; CachedListenStatus(const CachedListenStatus&) = delete; - ~CachedListenStatus() { + ~CachedListenStatus() + { if (socketId and req and req->node) { req->node->closeSocket(socketId); } @@ -87,31 +81,36 @@ struct Dht::SearchNode { }; using NodeListenerStatus = std::map, CachedListenStatus>; - Sp node {}; /* the node info */ + Sp node {}; /* the node info */ /* queries sent for finding out values hosted by the node */ Sp probe_query {}; /* queries substituting formal 'get' requests */ std::map, std::vector>> pagination_queries {}; - SyncStatus getStatus {}; /* get/sync status */ + SyncStatus getStatus {}; /* get/sync status */ NodeListenerStatus listenStatus {}; /* listen status */ - AnnounceStatusMap acked {}; /* announcement status for a given value id */ + AnnounceStatusMap acked {}; /* announcement status for a given value id */ Blob token {}; /* last token the node sent to us after a get request */ time_point last_get_reply {time_point::min()}; /* last time received valid token */ Sp syncJob {}; - bool candidate {false}; /* A search node is candidate if the search is/was synced and this - node is a new candidate for inclusion. */ + bool candidate {false}; /* A search node is candidate if the search is/was synced and this + node is a new candidate for inclusion. */ - SearchNode() : node() {} + SearchNode() + : node() + {} SearchNode(const SearchNode&) = delete; SearchNode(SearchNode&&) = delete; SearchNode& operator=(const SearchNode&) = delete; SearchNode& operator=(SearchNode&&) = delete; - SearchNode(const Sp& node) : node(node) {} - ~SearchNode() { + SearchNode(const Sp& node) + : node(node) + {} + ~SearchNode() + { if (node) { cancelGet(); cancelListen(); @@ -122,22 +121,23 @@ struct Dht::SearchNode { /** * Can we use this node to listen/announce now ? */ - bool isSynced(const time_point& now) const { - return not node->isExpired() and - not token.empty() and last_get_reply >= now - Node::NODE_EXPIRE_TIME; + bool isSynced(const time_point& now) const + { + return not node->isExpired() and not token.empty() and last_get_reply >= now - Node::NODE_EXPIRE_TIME; } - time_point getSyncTime(const time_point& now) const { + time_point getSyncTime(const time_point& now) const + { if (node->isExpired() or token.empty()) return now; return last_get_reply + Node::NODE_EXPIRE_TIME; } - friend std::ostream& operator<< (std::ostream& s, const SearchNode& node) { - s << "getStatus:" << node.getStatus.size() - << " listenStatus:" << node.listenStatus.size() - << " acked:" << node.acked.size() - << " cache:" << (node.listenStatus.empty() ? 0 : node.listenStatus.begin()->second.cache.size()) << std::endl; + friend std::ostream& operator<<(std::ostream& s, const SearchNode& node) + { + s << "getStatus:" << node.getStatus.size() << " listenStatus:" << node.listenStatus.size() + << " acked:" << node.acked.size() + << " cache:" << (node.listenStatus.empty() ? 0 : node.listenStatus.begin()->second.cache.size()) << std::endl; return s; } @@ -159,28 +159,27 @@ struct Dht::SearchNode { * * @return true if we can send get, else false. */ - bool canGet(time_point now, time_point update, const Sp& q) const { + bool canGet(time_point now, time_point update, const Sp& q) const + { if (node->isExpired()) return false; - bool is_pending {false}, - completed_sq_status {false}, - pending_sq_status {false}; + bool is_pending {false}, completed_sq_status {false}, pending_sq_status {false}; for (const auto& s : getStatus) { if (s.second and s.second->pending()) is_pending = true; if (s.first and q and q->isSatisfiedBy(*s.first) and s.second) { if (s.second->pending()) pending_sq_status = true; - else if (s.second->completed() and not (update > s.second->reply_time)) + else if (s.second->completed() and not(update > s.second->reply_time)) completed_sq_status = true; if (completed_sq_status and pending_sq_status) break; } } - return (not is_pending and now > last_get_reply + Node::NODE_EXPIRE_TIME) or - not (completed_sq_status or pending_sq_status or hasStartedPagination(q)); + return (not is_pending and now > last_get_reply + Node::NODE_EXPIRE_TIME) + or not(completed_sq_status or pending_sq_status or hasStartedPagination(q)); } /** @@ -190,18 +189,20 @@ struct Dht::SearchNode { * * @return true if pagination process has started, else false. */ - bool hasStartedPagination(const Sp& q) const { + bool hasStartedPagination(const Sp& q) const + { const auto& pqs = pagination_queries.find(q); if (pqs == pagination_queries.cend() or pqs->second.empty()) return false; - return std::find_if(pqs->second.cbegin(), pqs->second.cend(), - [this](const Sp& query) { - const auto& req = getStatus.find(query); - return req != getStatus.cend() and req->second; - }) != pqs->second.cend(); + return std::find_if(pqs->second.cbegin(), + pqs->second.cend(), + [this](const Sp& query) { + const auto& req = getStatus.find(query); + return req != getStatus.cend() and req->second; + }) + != pqs->second.cend(); }; - /** * Tell if the node has finished responding to a given 'get' request. * @@ -213,14 +214,18 @@ struct Dht::SearchNode { * * @return true if it has finished, else false. */ - bool isDone(const Get& get) const { + bool isDone(const Get& get) const + { if (hasStartedPagination(get.query)) { const auto& pqs = pagination_queries.find(get.query); - auto paginationPending = std::find_if(pqs->second.cbegin(), pqs->second.cend(), - [this](const Sp& query) { - const auto& req = getStatus.find(query); - return req != getStatus.cend() and req->second and req->second->pending(); - }) != pqs->second.cend(); + auto paginationPending = std::find_if(pqs->second.cbegin(), + pqs->second.cend(), + [this](const Sp& query) { + const auto& req = getStatus.find(query); + return req != getStatus.cend() and req->second + and req->second->pending(); + }) + != pqs->second.cend(); return not paginationPending; } else { /* no pagination yet */ const auto& gs = get.query ? getStatus.find(get.query) : getStatus.cend(); @@ -228,7 +233,8 @@ struct Dht::SearchNode { } } - void cancelGet() { + void cancelGet() + { for (const auto& status : getStatus) { if (status.second->pending()) { node->cancelRequest(status.second); @@ -242,13 +248,16 @@ struct Dht::SearchNode { auto l = listenStatus.find(q); if (l != listenStatus.end()) { auto next = l->second.cache.onValues(answer.values, - answer.refreshed_values, - answer.expired_values, types, scheduler.time()); + answer.refreshed_values, + answer.expired_values, + types, + scheduler.time()); scheduler.edit(l->second.cacheExpirationJob, next); } } - void onListenSynced(const Sp& q, bool synced = true, Sp refreshJob = {}) { + void onListenSynced(const Sp& q, bool synced = true, Sp refreshJob = {}) + { auto l = listenStatus.find(q); if (l != listenStatus.end()) { if (l->second.refresh) @@ -258,7 +267,8 @@ struct Dht::SearchNode { } } - void expireValues(const Sp& q, Scheduler& scheduler) { + void expireValues(const Sp& q, Scheduler& scheduler) + { auto l = listenStatus.find(q); if (l != listenStatus.end()) { auto next = l->second.cache.expireValues(scheduler.time()); @@ -287,28 +297,34 @@ struct Dht::SearchNode { * * @return true if there exists an expired request, else false. */ - static bool pending(const SyncStatus& status) { - return std::find_if(status.cbegin(), status.cend(), - [](const SyncStatus::value_type& r){ - return r.second and r.second->pending(); - }) != status.cend(); + static bool pending(const SyncStatus& status) + { + return std::find_if(status.cbegin(), + status.cend(), + [](const SyncStatus::value_type& r) { return r.second and r.second->pending(); }) + != status.cend(); } - static bool pending(const NodeListenerStatus& status) { - return std::find_if(status.begin(), status.end(), - [](const NodeListenerStatus::value_type& r){ - return r.second.req and r.second.req->pending(); - }) != status.end(); + static bool pending(const NodeListenerStatus& status) + { + return std::find_if(status.begin(), + status.end(), + [](const NodeListenerStatus::value_type& r) { + return r.second.req and r.second.req->pending(); + }) + != status.end(); } bool pendingGet() const { return pending(getStatus); } - bool isAnnounced(Value::Id vid) const { + bool isAnnounced(Value::Id vid) const + { auto ack = acked.find(vid); if (ack == acked.end() or not ack->second.req) return false; return ack->second.req->completed(); } - void cancelAnnounce() { + void cancelAnnounce() + { for (const auto& status : acked) { const auto& req = status.second.req; if (req and req->pending()) { @@ -320,28 +336,34 @@ struct Dht::SearchNode { acked.clear(); } - inline bool isListening(time_point now, duration listen_expire) const { + inline bool isListening(time_point now, duration listen_expire) const + { auto ls = listenStatus.begin(); - for ( ; ls != listenStatus.end() ; ++ls) { + for (; ls != listenStatus.end(); ++ls) { if (isListening(now, ls, listen_expire)) { break; } } return ls != listenStatus.end(); } - inline bool isListening(time_point now, const Sp& q, duration listen_expire) const { + inline bool isListening(time_point now, const Sp& q, duration listen_expire) const + { const auto& ls = listenStatus.find(q); if (ls == listenStatus.end()) return false; else return isListening(now, ls, listen_expire); } - inline bool isListening(time_point now, NodeListenerStatus::const_iterator listen_status, duration listen_expire) const { + inline bool isListening(time_point now, + NodeListenerStatus::const_iterator listen_status, + duration listen_expire) const + { if (listen_status == listenStatus.end() or not listen_status->second.req) return false; return listen_status->second.req->reply_time + listen_expire > now; } - void cancelListen() { + void cancelListen() + { for (const auto& status : listenStatus) { node->cancelRequest(status.second.req); if (status.second.refresh) @@ -349,9 +371,10 @@ struct Dht::SearchNode { if (status.second.cacheExpirationJob) status.second.cacheExpirationJob->cancel(); } - listenStatus.clear(); + listenStatus.clear(); } - void cancelListen(const Sp& query) { + void cancelListen(const Sp& query) + { auto it = listenStatus.find(query); if (it != listenStatus.end()) { node->cancelRequest(it->second.req); @@ -364,7 +387,8 @@ struct Dht::SearchNode { /** * Assuming the node is synced, should a "put" request be sent to this node now ? */ - time_point getAnnounceTime(Value::Id vid) const { + time_point getAnnounceTime(Value::Id vid) const + { const auto& ack = acked.find(vid); if (ack == acked.cend() or not ack->second.req) { return time_point::min(); @@ -379,39 +403,41 @@ struct Dht::SearchNode { * Assuming the node is synced, should the "listen" request with Query q be * sent to this node now ? */ - time_point getListenTime(const decltype(listenStatus)::const_iterator listen_status, duration listen_expire) const { + time_point getListenTime(const decltype(listenStatus)::const_iterator listen_status, duration listen_expire) const + { if (listen_status == listenStatus.cend() or not listen_status->second.req) return time_point::min(); - return listen_status->second.req->pending() ? time_point::max() : - listen_status->second.req->reply_time + listen_expire - REANNOUNCE_MARGIN; + return listen_status->second.req->pending() + ? time_point::max() + : listen_status->second.req->reply_time + listen_expire - REANNOUNCE_MARGIN; } - time_point getListenTime(const Sp& q, duration listen_expire) const { + time_point getListenTime(const Sp& q, duration listen_expire) const + { return getListenTime(listenStatus.find(q), listen_expire); } /** * Is this node expired or candidate */ - bool isBad() const { - return not node or node->isExpired() or candidate; - } + bool isBad() const { return not node or node->isExpired() or candidate; } }; /** * A search is a list of the nodes we think are responsible * for storing values for a given hash. */ -struct Dht::Search { +struct Dht::Search +{ InfoHash id {}; sa_family_t af; uint16_t tid; time_point refill_time {time_point::min()}; - time_point step_time {time_point::min()}; /* the time of the last search step */ + time_point step_time {time_point::min()}; /* the time of the last search step */ Sp nextSearchStep {}; - bool expired {false}; /* no node, or all nodes expired */ - bool done {false}; /* search is over, cached for later */ + bool expired {false}; /* no node, or all nodes expired */ + bool done {false}; /* search is over, cached for later */ std::vector> nodes {}; /* pending puts */ @@ -421,7 +447,8 @@ struct Dht::Search { std::multimap callbacks {}; /* listeners */ - struct SearchListener { + struct SearchListener + { Sp query; ValueCallback get_cb; SyncCallback sync_cb; @@ -433,7 +460,8 @@ struct Dht::Search { SearchCache cache; Sp opExpirationJob; - ~Search() { + ~Search() + { if (opExpirationJob) opExpirationJob->cancel(); for (auto& g : callbacks) { @@ -447,12 +475,11 @@ struct Dht::Search { } } - friend std::ostream& operator<< (std::ostream& s, const Search& sr) { + friend std::ostream& operator<<(std::ostream& s, const Search& sr) + { auto csize = sr.cache.size(); - s << "announce:" << sr.announce.size() - << " gets:" << sr.callbacks.size() - << " listeners:" << sr.listeners.size() - << " cache:" << csize.first << ',' << csize.second << std::endl; + s << "announce:" << sr.announce.size() << " gets:" << sr.callbacks.size() + << " listeners:" << sr.listeners.size() << " cache:" << csize.first << ',' << csize.second << std::endl; s << "nodes:" << std::endl; for (const auto& n : sr.nodes) s << *n; @@ -462,9 +489,10 @@ struct Dht::Search { /** * @returns true if the node was not present and added to the search */ - bool insertNode(const Sp& n, time_point now, const Blob& token={}); + bool insertNode(const Sp& n, time_point now, const Blob& token = {}); - SearchNode* getNode(const Sp& n) { + SearchNode* getNode(const Sp& n) + { auto srn = std::find_if(nodes.begin(), nodes.end(), [&](const std::unique_ptr& sn) { return n == sn->node; }); @@ -472,7 +500,8 @@ struct Dht::Search { } /* number of concurrent sync requests */ - unsigned currentlySolicitedNodeCount() const { + unsigned currentlySolicitedNodeCount() const + { unsigned count = 0; for (const auto& n : nodes) if (not n->isBad() and n->pendingGet()) @@ -509,7 +538,8 @@ struct Dht::Search { * * @param get The 'get' operation which is now over. */ - void setDone(const Get& get) { + void setDone(const Get& get) + { for (auto& n : nodes) { auto pqs = n->pagination_queries.find(get.query); if (pqs != n->pagination_queries.cend()) { @@ -527,7 +557,8 @@ struct Dht::Search { * the opportunity we have to clear some entries in the SearchNodes status * maps. */ - void setDone() { + void setDone() + { for (auto& n : nodes) { n->getStatus.clear(); n->listenStatus.clear(); @@ -539,40 +570,50 @@ struct Dht::Search { bool isAnnounced(Value::Id id) const; bool isListening(time_point now, duration exp) const; - void get(const Value::Filter& f, const Sp& q, const QueryCallback& qcb, const GetCallback& gcb, const DoneCallback& dcb, Scheduler& scheduler) { + void get(const Value::Filter& f, + const Sp& q, + const QueryCallback& qcb, + const GetCallback& gcb, + const DoneCallback& dcb, + Scheduler& scheduler) + { if (gcb or qcb) { if (not cache.get(f, q, gcb, dcb)) { const auto& now = scheduler.time(); - callbacks.emplace(now, Get { now, f, q, qcb, gcb, dcb }); + callbacks.emplace(now, Get {now, f, q, qcb, gcb, dcb}); scheduler.edit(nextSearchStep, now); } } } - size_t listen(const ValueCallback& cb, Value::Filter&& f, const Sp& q, Scheduler& scheduler) { - //DHT_LOG.e(id, "[search %s IPv%c] listen", id.toString().c_str(), (af == AF_INET) ? '4' : '6'); - return cache.listen(cb, q, std::move(f), [&](const Sp& q, ValueCallback vcb, SyncCallback scb){ + size_t listen(const ValueCallback& cb, Value::Filter&& f, const Sp& q, Scheduler& scheduler) + { + // DHT_LOG.e(id, "[search %s IPv%c] listen", id.toString().c_str(), (af == AF_INET) ? '4' : '6'); + return cache.listen(cb, q, std::move(f), [&](const Sp& q, ValueCallback vcb, SyncCallback scb) { done = false; auto token = ++listener_token; - listeners.emplace(token, SearchListener{q, vcb, scb}); + listeners.emplace(token, SearchListener {q, vcb, scb}); scheduler.edit(nextSearchStep, scheduler.time()); return token; }); } - void cancelListen(size_t token, Scheduler& scheduler) { + void cancelListen(size_t token, Scheduler& scheduler) + { cache.cancelListen(token, scheduler.time()); if (not opExpirationJob) - opExpirationJob = scheduler.add(time_point::max(), [this,&scheduler]{ - auto nextExpire = cache.expire(scheduler.time(), [&](size_t t){ + opExpirationJob = scheduler.add(time_point::max(), [this, &scheduler] { + auto nextExpire = cache.expire(scheduler.time(), [&](size_t t) { const auto& ll = listeners.find(t); if (ll != listeners.cend()) { auto query = ll->second.query; listeners.erase(ll); if (listeners.empty()) { - for (auto& sn : nodes) sn->cancelListen(); + for (auto& sn : nodes) + sn->cancelListen(); } else if (query) { - for (auto& sn : nodes) sn->cancelListen(query); + for (auto& sn : nodes) + sn->cancelListen(query); } } }); @@ -581,7 +622,8 @@ struct Dht::Search { scheduler.edit(opExpirationJob, cache.getExpiration()); } - std::vector> getPut() const { + std::vector> getPut() const + { std::vector> ret; ret.reserve(announce.size()); for (const auto& a : announce) @@ -589,7 +631,8 @@ struct Dht::Search { return ret; } - Sp getPut(Value::Id vid) const { + Sp getPut(Value::Id vid) const + { for (auto& a : announce) { if (a.value->id == vid) return a.value; @@ -597,14 +640,14 @@ struct Dht::Search { return {}; } - bool cancelPut(Value::Id vid) { + bool cancelPut(Value::Id vid) + { bool canceled {false}; for (auto it = announce.begin(); it != announce.end();) { if (it->value->id == vid) { canceled = true; it = announce.erase(it); - } - else + } else ++it; } for (auto& n : nodes) { @@ -620,14 +663,15 @@ struct Dht::Search { return canceled; } - void put(const Sp& value, DoneCallback callback, time_point created, bool permanent) { + void put(const Sp& value, DoneCallback callback, time_point created, bool permanent) + { done = false; expired = false; - auto a_sr = std::find_if(announce.begin(), announce.end(), [&](const Announce& a){ + auto a_sr = std::find_if(announce.begin(), announce.end(), [&](const Announce& a) { return a.value->id == value->id; }); if (a_sr == announce.end()) { - auto& a = announce.emplace_back(Announce {permanent, value, created, {}} ); + auto& a = announce.emplace_back(Announce {permanent, value, created, {}}); if (callback) a.callbacks.emplace_back(std::move(callback)); for (auto& n : nodes) { @@ -644,7 +688,7 @@ struct Dht::Search { n->acked[value->id].req.reset(); n->probe_query.reset(); } - for (auto& cb: a_sr->callbacks) + for (auto& cb : a_sr->callbacks) cb(false, {}); a_sr->callbacks.clear(); if (callback) @@ -664,12 +708,14 @@ struct Dht::Search { /** * @return The number of non-good search nodes. */ - unsigned getNumberOfBadNodes() const { + unsigned getNumberOfBadNodes() const + { return std::count_if(nodes.begin(), nodes.end(), [](const std::unique_ptr& sn) { return sn->isBad(); }); } - unsigned getNumberOfConsecutiveBadNodes() const { + unsigned getNumberOfConsecutiveBadNodes() const + { unsigned count = 0; for (const auto& sn : nodes) { if (not sn->node->isExpired()) @@ -688,11 +734,13 @@ struct Dht::Search { * * @return true if a node has been removed, else false. */ - bool removeExpiredNode(const time_point& now) { + bool removeExpiredNode(const time_point& now) + { for (auto e = nodes.cend(); e != nodes.cbegin();) { const Node& n = *(*(--e))->node; if (n.isRemovable(now)) { - //std::cout << "Removing expired node " << n.id << " from IPv" << (af==AF_INET?'4':'6') << " search " << id << std::endl; + // std::cout << "Removing expired node " << n.id << " from IPv" << (af==AF_INET?'4':'6') << " search " + // << id << std::endl; nodes.erase(e); return true; } @@ -707,7 +755,8 @@ struct Dht::Search { * - remove all nodes from the search; * - clear (non-permanent) callbacks; */ - void expire() { + void expire() + { // no nodes or all expired nodes. This is most likely a connectivity change event. expired = true; @@ -725,8 +774,10 @@ struct Dht::Search { { std::vector a_cbs; a_cbs.reserve(announce.size()); - for (auto ait = announce.begin() ; ait != announce.end(); ) { - a_cbs.insert(a_cbs.end(), std::make_move_iterator(ait->callbacks.begin()), std::make_move_iterator(ait->callbacks.end())); + for (auto ait = announce.begin(); ait != announce.end();) { + a_cbs.insert(a_cbs.end(), + std::make_move_iterator(ait->callbacks.begin()), + std::make_move_iterator(ait->callbacks.end())); ait->callbacks.clear(); if (not ait->permanent) ait = announce.erase(ait); @@ -745,22 +796,22 @@ struct Dht::Search { * @param types The sequence of existing types. * @param now The time reference to now. */ - void checkAnnounced(Value::Id vid = Value::INVALID_ID) { - auto announced = std::partition(announce.begin(), announce.end(), - [this,&vid](Announce& a) { - if (vid != Value::INVALID_ID and (!a.value || a.value->id != vid)) - return true; - if (isAnnounced(a.value->id)) { - if (!a.callbacks.empty()) { - const auto& nodes = getNodes(); - for (auto& cb : a.callbacks) - cb(true, nodes); - a.callbacks.clear(); - } - if (not a.permanent) - return false; - } + void checkAnnounced(Value::Id vid = Value::INVALID_ID) + { + auto announced = std::partition(announce.begin(), announce.end(), [this, &vid](Announce& a) { + if (vid != Value::INVALID_ID and (!a.value || a.value->id != vid)) return true; + if (isAnnounced(a.value->id)) { + if (!a.callbacks.empty()) { + const auto& nodes = getNodes(); + for (auto& cb : a.callbacks) + cb(true, nodes); + a.callbacks.clear(); + } + if (not a.permanent) + return false; + } + return true; }); // remove acked for cleared annouces for (auto it = announced; it != announce.end(); ++it) { @@ -778,7 +829,8 @@ struct Dht::Search { std::vector> getNodes() const; - void clear() { + void clear() + { announce.clear(); callbacks.clear(); listeners.clear(); @@ -787,7 +839,6 @@ struct Dht::Search { } }; - /* A search contains a list of nodes, sorted by decreasing distance to the target. We just got a new candidate, insert it at the right spot or discard it. */ @@ -819,8 +870,8 @@ Dht::Search::insertNode(const Sp& snode, time_point now, const Blob& token if (not found) { // find if and where to trim excessive nodes auto t = nodes.cend(); - size_t bad = 0; // number of bad nodes (if search is not expired) - bool full {false}; // is the search full (has the maximum nodes) + size_t bad = 0; // number of bad nodes (if search is not expired) + bool full {false}; // is the search full (has the maximum nodes) if (expired) { // if the search is expired, trim to SEARCH_NODES nodes if (nodes.size() >= SEARCH_NODES) { @@ -830,8 +881,8 @@ Dht::Search::insertNode(const Sp& snode, time_point now, const Blob& token } else { // otherwise, trim to SEARCH_NODES nodes, not counting bad nodes bad = getNumberOfBadNodes(); - full = nodes.size() - bad >= SEARCH_NODES; - while (std::distance(nodes.cbegin(), t) - bad > SEARCH_NODES) { + full = nodes.size() - bad >= SEARCH_NODES; + while (std::distance(nodes.cbegin(), t) - bad > SEARCH_NODES) { --t; if ((*t)->isBad()) bad--; @@ -983,7 +1034,7 @@ Dht::Search::isListening(time_point now, duration listen_expire) const if (n->isBad()) continue; SearchNode::NodeListenerStatus::const_iterator ls {}; - for (ls = n->listenStatus.begin(); ls != n->listenStatus.end() ; ++ls) { + for (ls = n->listenStatus.begin(); ls != n->listenStatus.end(); ++ls) { if (n->isListening(now, ls, listen_expire)) break; } @@ -995,4 +1046,4 @@ Dht::Search::isListening(time_point now, duration listen_expire) const return i; } -} +} // namespace dht diff --git a/src/securedht.cpp b/src/securedht.cpp index a789233d..e14ea6fc 100644 --- a/src/securedht.cpp +++ b/src/securedht.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -33,10 +19,18 @@ extern "C" { namespace dht { -SecureDht::SecureDht(std::unique_ptr dht, SecureDht::Config conf, IdentityAnnouncedCb iacb, const std::shared_ptr& l) -: DhtInterface(l), dht_(std::move(dht)), key_(conf.id.first), certificate_(conf.id.second), enableCache_(conf.cert_cache_all) +SecureDht::SecureDht(std::unique_ptr dht, + SecureDht::Config conf, + IdentityAnnouncedCb iacb, + const std::shared_ptr& l) + : DhtInterface(l) + , dht_(std::move(dht)) + , key_(conf.id.first) + , certificate_(conf.id.second) + , enableCache_(conf.cert_cache_all) { - if (!dht_) return; + if (!dht_) + return; for (const auto& type : DEFAULT_TYPES) registerType(type); @@ -63,34 +57,32 @@ SecureDht::SecureDht(std::unique_ptr dht, SecureDht::Config conf, iacb(completedState->second); } : iacb; - dht_->addOnConnectedCallback([this, certId, certLongId, cb=std::move(cb)]{ - dht_->put(certId, Value { - CERTIFICATE_TYPE, - *certificate_, - 1 - }, cb, {}, true); - dht_->put(InfoHash::get(certLongId), Value { - CERTIFICATE_TYPE, - *certificate_, - 1 - }, cb, {}, true); + dht_->addOnConnectedCallback([this, certId, certLongId, cb = std::move(cb)] { + dht_->put(certId, Value {CERTIFICATE_TYPE, *certificate_, 1}, cb, {}, true); + dht_->put(InfoHash::get(certLongId), Value {CERTIFICATE_TYPE, *certificate_, 1}, cb, {}, true); }); } } -SecureDht::~SecureDht(){ +SecureDht::~SecureDht() +{ dht_.reset(); } ValueType SecureDht::secureType(ValueType&& type) { - type.storePolicy = [sp = std::move(type.storePolicy)](InfoHash id, Sp& v, const InfoHash& nid, const SockAddr& a) { - if (v->isSigned()) - return v->checkSignature(); - return sp(id, v, nid, a); - }; - type.editPolicy = [l = logger_, ep = std::move(type.editPolicy)](InfoHash id, const Sp& o, Sp& n, const InfoHash& nid, const SockAddr& a) { + type.storePolicy = + [sp = std::move(type.storePolicy)](InfoHash id, Sp& v, const InfoHash& nid, const SockAddr& a) { + if (v->isSigned()) + return v->checkSignature(); + return sp(id, v, nid, a); + }; + type.editPolicy = [l = logger_, ep = std::move(type.editPolicy)](InfoHash id, + const Sp& o, + Sp& n, + const InfoHash& nid, + const SockAddr& a) { if (not o->isSigned()) return ep(id, o, n, nid, a); if (*o->owner != *n->owner or not n->isSigned()) { @@ -111,8 +103,7 @@ SecureDht::secureType(ValueType&& type) l->w("Edition forbidden: sequence number must be increasing."); return false; } - } - else if (n->seq < o->seq) + } else if (n->seq < o->seq) return false; return true; }; @@ -244,22 +235,26 @@ SecureDht::findCertificate(const InfoHash& node, const std::function(false); - dht_->get(node, [cb,node,found,this](const std::vector>& vals) { - for (const auto& v : vals) { - if (auto cert = registerCertificate(node, v->data)) { - *found = true; - if (logger_) - logger_->d(node, "Found certificate for %s", node.to_c_str()); - if (cb) - cb(cert); - return false; + dht_->get( + node, + [cb, node, found, this](const std::vector>& vals) { + for (const auto& v : vals) { + if (auto cert = registerCertificate(node, v->data)) { + *found = true; + if (logger_) + logger_->d(node, "Found certificate for %s", node.to_c_str()); + if (cb) + cb(cert); + return false; + } } - } - return !*found; - }, [cb,found](bool) { - if (!*found and cb) - cb(nullptr); - }, Value::TypeFilter(CERTIFICATE_TYPE)); + return !*found; + }, + [cb, found](bool) { + if (!*found and cb) + cb(nullptr); + }, + Value::TypeFilter(CERTIFICATE_TYPE)); } void @@ -279,11 +274,13 @@ SecureDht::findPublicKey(const InfoHash& node, const std::functiongetId()] = pk; nodesPubKeysLong_[pk->getLongId()] = pk; - if (cb) cb(pk); + if (cb) + cb(pk); return; } } - if (cb) cb(nullptr); + if (cb) + cb(nullptr); }); } @@ -313,22 +310,26 @@ SecureDht::findCertificate(const PkId& node, const std::function(false); - dht_->get(InfoHash::get(node), [cb,node,found,this](const std::vector>& vals) { - for (const auto& v : vals) { - if (auto cert = registerCertificate(node, v->data)) { - *found = true; - if (logger_) - logger_->debug("Found certificate for {}", node.to_c_str()); - if (cb) - cb(cert); - return false; + dht_->get( + InfoHash::get(node), + [cb, node, found, this](const std::vector>& vals) { + for (const auto& v : vals) { + if (auto cert = registerCertificate(node, v->data)) { + *found = true; + if (logger_) + logger_->debug("Found certificate for {}", node.to_c_str()); + if (cb) + cb(cert); + return false; + } } - } - return !*found; - }, [cb,found](bool) { - if (!*found and cb) - cb(nullptr); - }, Value::TypeFilter(CERTIFICATE_TYPE)); + return !*found; + }, + [cb, found](bool) { + if (!*found and cb) + cb(nullptr); + }, + Value::TypeFilter(CERTIFICATE_TYPE)); } void @@ -348,11 +349,13 @@ SecureDht::findPublicKey(const PkId& node, const std::functiongetId()] = pk; nodesPubKeysLong_[pk->getLongId()] = pk; - if (cb) cb(pk); + if (cb) + cb(pk); return; } } - if (cb) cb(nullptr); + if (cb) + cb(nullptr); }); } @@ -420,7 +423,6 @@ SecureDht::getCallbackFilter(const ValueCallback& cb, Value::Filter&& filter) }; } - GetCallback SecureDht::getCallbackFilter(const GetCallback& cb, Value::Filter&& filter) { @@ -451,7 +453,6 @@ SecureDht::listen(const InfoHash& id, ValueCallback cb, Value::Filter f, Where w return dht_->listen(id, getCallbackFilter(cb, std::forward(f)), {}, std::forward(w)); } - size_t SecureDht::listen(const InfoHash& id, GetCallback cb, Value::Filter f, Where w) { @@ -461,7 +462,7 @@ SecureDht::listen(const InfoHash& id, GetCallback cb, Value::Filter f, Where w) void SecureDht::putSigned(const InfoHash& hash, Sp val, DoneCallback callback, bool permanent) { - if (not key_ or not hash or not val) { + if (not key_ or not hash or not val) { if (callback) callback(false, {}); return; @@ -479,8 +480,9 @@ SecureDht::putSigned(const InfoHash& hash, Sp val, DoneCallback callback, } // Check if data already exists on the dht - get(hash, - [val,this] (const std::vector>& vals) { + get( + hash, + [val, this](const std::vector>& vals) { if (logger_) logger_->d("Found online previous value being announced."); for (const auto& v : vals) { @@ -495,73 +497,77 @@ SecureDht::putSigned(const InfoHash& hash, Sp val, DoneCallback callback, } return true; }, - [hash,val,this,callback,permanent] (bool /* ok */) { + [hash, val, this, callback, permanent](bool /* ok */) { sign(*val); dht_->put(hash, val, callback, time_point::max(), permanent); }, Value::IdFilter(val->id), - Where().id(val->id) - ); + Where().id(val->id)); } void SecureDht::putEncrypted(const InfoHash& hash, const InfoHash& to, Sp val, DoneCallback callback, bool permanent) { - if (not key_) { + if (not key_) { if (callback) callback(false, {}); return; } - findPublicKey(to, [this, hash, val = std::move(val), callback = std::move(callback), permanent](const Sp& pk) { - if(!pk || !*pk) { - if (callback) - callback(false, {}); - return; - } - if (logger_) - logger_->w("Encrypting data for PK: %s", pk->getId().toString().c_str()); - try { - dht_->put(hash, encrypt(*val, *pk), callback, time_point::max(), permanent); - } catch (const std::exception& e) { - if (logger_) - logger_->e("Error putting encrypted data: %s", e.what()); - if (callback) - callback(false, {}); - } - }); + findPublicKey(to, + [this, hash, val = std::move(val), callback = std::move(callback), permanent]( + const Sp& pk) { + if (!pk || !*pk) { + if (callback) + callback(false, {}); + return; + } + if (logger_) + logger_->w("Encrypting data for PK: %s", pk->getId().toString().c_str()); + try { + dht_->put(hash, encrypt(*val, *pk), callback, time_point::max(), permanent); + } catch (const std::exception& e) { + if (logger_) + logger_->e("Error putting encrypted data: %s", e.what()); + if (callback) + callback(false, {}); + } + }); } void SecureDht::putEncrypted(const InfoHash& hash, const PkId& to, Sp val, DoneCallback callback, bool permanent) { - if (not key_) { + if (not key_) { if (callback) callback(false, {}); return; } - findPublicKey(to, [this, hash, val = std::move(val), callback = std::move(callback), permanent](const Sp& pk) { - if(!pk || !*pk) { - if (callback) - callback(false, {}); - return; - } - if (logger_) - logger_->warn("Encrypting data for PK: {}", pk->getLongId()); - try { - dht_->put(hash, encrypt(*val, *pk), callback, time_point::max(), permanent); - } catch (const std::exception& e) { - if (logger_) - logger_->e("Error putting encrypted data: %s", e.what()); - if (callback) - callback(false, {}); - } - }); + findPublicKey(to, + [this, hash, val = std::move(val), callback = std::move(callback), permanent]( + const Sp& pk) { + if (!pk || !*pk) { + if (callback) + callback(false, {}); + return; + } + if (logger_) + logger_->warn("Encrypting data for PK: {}", pk->getLongId()); + try { + dht_->put(hash, encrypt(*val, *pk), callback, time_point::max(), permanent); + } catch (const std::exception& e) { + if (logger_) + logger_->e("Error putting encrypted data: %s", e.what()); + if (callback) + callback(false, {}); + } + }); } void -SecureDht::putEncrypted(const InfoHash& hash, const crypto::PublicKey& pk, Sp val, DoneCallback callback, bool permanent) +SecureDht::putEncrypted( + const InfoHash& hash, const crypto::PublicKey& pk, Sp val, DoneCallback callback, bool permanent) { - if (not key_) { + if (not key_) { if (callback) callback(false, {}); return; @@ -599,7 +605,7 @@ SecureDht::decrypt(const Value& v) auto decrypted = key_->decrypt(v.cypher); Value ret {v.id}; - auto msg = msgpack::unpack((const char*)decrypted.data(), decrypted.size()); + auto msg = msgpack::unpack((const char*) decrypted.data(), decrypted.size()); ret.msgpack_unpack_body(msg.get()); if (ret.recipient != getId()) @@ -610,4 +616,4 @@ SecureDht::decrypt(const Value& v) return ret; } -} +} // namespace dht diff --git a/src/storage.h b/src/storage.h index 476688af..67efca2a 100644 --- a/src/storage.h +++ b/src/storage.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "infohash.h" @@ -29,13 +14,16 @@ namespace dht { /** * Tracks storage usage per IP or IP range */ -class StorageBucket { +class StorageBucket +{ public: - void insert(const InfoHash& id, const Value& value, time_point expiration) { + void insert(const InfoHash& id, const Value& value, time_point expiration) + { totalSize_ += value.size(); storedValues_.emplace(expiration, std::pair(id, value.id)); } - void erase(const InfoHash& id, const Value& value, time_point expiration) { + void erase(const InfoHash& id, const Value& value, time_point expiration) + { auto range = storedValues_.equal_range(expiration); for (auto rit = range.first; rit != range.second;) { if (rit->second.first == id && rit->second.second == value.id) { @@ -47,7 +35,8 @@ public: } // printf("StorageBucket::erase unable to find value %s %016" PRIx64 "\n", id.to_c_str(), value.id); } - void refresh(const InfoHash& id, const Value& value, time_point old_expiration, time_point expiration) { + void refresh(const InfoHash& id, const Value& value, time_point old_expiration, time_point expiration) + { auto range = storedValues_.equal_range(old_expiration); for (auto rit = range.first; rit != range.second;) { if (rit->second.first == id && rit->second.second == value.id) { @@ -61,13 +50,18 @@ public: insert(id, value, expiration); } size_t size() const { return totalSize_; } - std::pair getOldest() const { return storedValues_.empty() ? std::pair{} : storedValues_.begin()->second; } + std::pair getOldest() const + { + return storedValues_.empty() ? std::pair {} : storedValues_.begin()->second; + } + private: std::multimap> storedValues_; size_t totalSize_ {0}; }; -struct ValueStorage { +struct ValueStorage +{ Sp data {}; time_point created {}; time_point expiration {}; @@ -76,11 +70,14 @@ struct ValueStorage { ValueStorage() {} ValueStorage(const Sp& v, time_point t, time_point e) - : data(v), created(t), expiration(e) {} + : data(v) + , created(t) + , expiration(e) + {} }; - -struct Storage { +struct Storage +{ time_point maintenance_time {}; std::map, std::map> listeners; std::map local_listeners {}; @@ -92,7 +89,8 @@ struct Storage { /** * Changes caused by an operation on the storage. */ - struct StoreDiff { + struct StoreDiff + { /** Difference in stored size caused by the op */ ssize_t size_diff; /** Difference in number of values */ @@ -104,35 +102,35 @@ struct Storage { }; Storage() {} - Storage(time_point t) : maintenance_time(t) {} + Storage(time_point t) + : maintenance_time(t) + {} Storage(Storage&& o) noexcept = default; Storage& operator=(Storage&& o) = default; - bool empty() const { - return values.empty(); - } + bool empty() const { return values.empty(); } StoreDiff clear(); - size_t valueCount() const { - return values.size(); - } + size_t valueCount() const { return values.size(); } - size_t totalSize() const { - return total_size; - } + size_t totalSize() const { return total_size; } const std::vector& getValues() const { return values; } - Sp getById(Value::Id vid) const { + Sp getById(Value::Id vid) const + { for (auto& v : values) - if (v.data->id == vid) return v.data; + if (v.data->id == vid) + return v.data; return {}; } - std::vector> get(const Value::Filter& f = {}) const { + std::vector> get(const Value::Filter& f = {}) const + { std::vector> newvals {}; - if (not f) newvals.reserve(values.size()); + if (not f) + newvals.reserve(values.size()); for (auto& v : values) { if (not f || f(*v.data)) newvals.push_back(v.data); @@ -148,8 +146,8 @@ struct Storage { * change_size: size difference * change_value_num: change of value number (0 or 1) */ - std::pair - store(const InfoHash& id, const Sp&, time_point created, time_point expiration, StorageBucket*); + std::pair store( + const InfoHash& id, const Sp&, time_point created, time_point expiration, StorageBucket*); /** * Refreshes the time point of the value's lifetime begining. @@ -158,8 +156,11 @@ struct Storage { * @param vid The value id * @return time of the next expiration, time_point::max() if no expiration */ - std::pair - refresh(const InfoHash& id, const time_point& now, const Value::Id& vid, const TypeStore& types) { + std::pair refresh(const InfoHash& id, + const time_point& now, + const Value::Id& vid, + const TypeStore& types) + { for (auto& vs : values) if (vs.data->id == vid) { vs.created = now; @@ -174,9 +175,7 @@ struct Storage { size_t listen(ValueCallback& cb, Value::Filter& f, const Sp& q); - void cancelListen(size_t token) { - local_listeners.erase(token); - } + void cancelListen(size_t token) { local_listeners.erase(token); } Sp remove(const InfoHash& id, Value::Id); @@ -190,7 +189,6 @@ private: size_t total_size {}; }; - size_t Storage::listen(ValueCallback& gcb, Value::Filter& filter, const Sp& query) { @@ -202,15 +200,14 @@ Storage::listen(ValueCallback& gcb, Value::Filter& filter, const Sp& quer } } auto tokenlocal = ++listener_token; - local_listeners.emplace(tokenlocal, LocalListener{query, filter, gcb}); + local_listeners.emplace(tokenlocal, LocalListener {query, filter, gcb}); return tokenlocal; } - std::pair Storage::store(const InfoHash& id, const Sp& value, time_point created, time_point expiration, StorageBucket* sb) { - auto it = std::find_if (values.begin(), values.end(), [&](const ValueStorage& vr) { + auto it = std::find_if(values.begin(), values.end(), [&](const ValueStorage& vr) { return vr.data == value || vr.data->id == value->id; }); ssize_t size_new = value->size(); @@ -219,9 +216,9 @@ Storage::store(const InfoHash& id, const Sp& value, time_point created, t it->created = created; if (it->data != value) { size_t size_old = it->data->size(); - ssize_t size_diff = size_new - (ssize_t)size_old; - //DHT_LOG.DEBUG("Updating %s -> %s", id.toString().c_str(), value->toString().c_str()); - // clear quota for previous value + ssize_t size_diff = size_new - (ssize_t) size_old; + // DHT_LOG.DEBUG("Updating %s -> %s", id.toString().c_str(), value->toString().c_str()); + // clear quota for previous value if (it->store_bucket) it->store_bucket->erase(id, *it->data, it->expiration); it->expiration = expiration; @@ -231,28 +228,26 @@ Storage::store(const InfoHash& id, const Sp& value, time_point created, t sb->insert(id, *value, expiration); it->data = value; total_size += size_diff; - return std::make_pair(&(*it), StoreDiff{size_diff, 0, 0, 1}); + return std::make_pair(&(*it), StoreDiff {size_diff, 0, 0, 1}); } } else { - //DHT_LOG.DEBUG("Storing %s -> %s", id.toString().c_str(), value->toString().c_str()); + // DHT_LOG.DEBUG("Storing %s -> %s", id.toString().c_str(), value->toString().c_str()); if (values.size() < MAX_VALUES) { total_size += size_new; values.emplace_back(value, created, expiration); values.back().store_bucket = sb; if (sb) sb->insert(id, *value, expiration); - return std::make_pair(&values.back(), StoreDiff{size_new, 1, 0, 0}); + return std::make_pair(&values.back(), StoreDiff {size_new, 1, 0, 0}); } } - return std::make_pair(nullptr, StoreDiff{}); + return std::make_pair(nullptr, StoreDiff {}); } Sp Storage::remove(const InfoHash& id, Value::Id vid) { - auto it = std::find_if (values.begin(), values.end(), [&](const ValueStorage& vr) { - return vr.data->id == vid; - }); + auto it = std::find_if(values.begin(), values.end(), [&](const ValueStorage& vr) { return vr.data->id == vid; }); if (it == values.end()) return {}; ssize_t size = it->data->size(); @@ -291,15 +286,12 @@ Storage::expire(const InfoHash& id, time_point now) } if (node_listeners.empty()) { nl_it = listeners.erase(nl_it); - } - else + } else ++nl_it; } // expire values - auto r = std::partition(values.begin(), values.end(), [&](const ValueStorage& v) { - return v.expiration > now; - }); + auto r = std::partition(values.begin(), values.end(), [&](const ValueStorage& v) { return v.expiration > now; }); std::vector> ret; ret.reserve(std::distance(r, values.end())); ssize_t size_diff {0}; @@ -316,4 +308,4 @@ Storage::expire(const InfoHash& id, time_point now) return {size_diff, std::move(ret)}; } -} +} // namespace dht diff --git a/src/thread_pool.cpp b/src/thread_pool.cpp index d7553e98..55662102 100644 --- a/src/thread_pool.cpp +++ b/src/thread_pool.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "thread_pool.h" @@ -21,7 +7,7 @@ #include #include #include // fix windows compiler bug -#include // std::pow +#include // std::pow namespace dht { @@ -41,10 +27,9 @@ ThreadPool::io() return pool; } - ThreadPool::ThreadPool(unsigned minThreads, unsigned maxThreads) - : minThreads_(std::max(minThreads, 1u)) - , maxThreads_(maxThreads ? std::max(minThreads_, maxThreads) : minThreads_) + : minThreads_(std::max(minThreads, 1u)) + , maxThreads_(maxThreads ? std::max(minThreads_, maxThreads) : minThreads_) { threads_.reserve(maxThreads_); if (minThreads_ != maxThreads_) { @@ -53,7 +38,7 @@ ThreadPool::ThreadPool(unsigned minThreads, unsigned maxThreads) } ThreadPool::ThreadPool() - : ThreadPool(std::max(std::thread::hardware_concurrency(), 4u)) + : ThreadPool(std::max(std::thread::hardware_concurrency(), 4u)) {} ThreadPool::~ThreadPool() @@ -65,14 +50,15 @@ void ThreadPool::run(std::function&& cb) { std::unique_lock l(lock_); - if (not cb or not running_) return; + if (not cb or not running_) + return; // launch new thread if necessary if (not readyThreads_ && threads_.size() < maxThreads_) { try { bool permanent_thread = threads_.size() < minThreads_; auto& thread = *threads_.emplace_back(std::make_unique()); - thread = std::thread([this, permanent_thread, e=threadExpirationDelay, &thread]() { + thread = std::thread([this, permanent_thread, e = threadExpirationDelay, &thread]() { while (true) { std::function task; @@ -80,7 +66,9 @@ ThreadPool::run(std::function&& cb) { std::unique_lock l(lock_); readyThreads_++; - auto waitCond = [&](){ return not running_ or not tasks_.empty(); }; + auto waitCond = [&]() { + return not running_ or not tasks_.empty(); + }; if (permanent_thread) cv_.wait(l, waitCond); else @@ -103,7 +91,7 @@ ThreadPool::run(std::function&& cb) if (not permanent_thread) threadEnded(thread); }); - } catch(const std::exception& e) { + } catch (const std::exception& e) { std::cerr << "Exception starting thread: " << e.what() << std::endl; if (threads_.empty()) throw; @@ -121,7 +109,7 @@ void ThreadPool::threadEnded(std::thread& thread) { std::lock_guard l(lock_); - tasks_.emplace([this,t=std::reference_wrapper(thread)]{ + tasks_.emplace([this, t = std::reference_wrapper(thread)] { std::lock_guard l(lock_); for (auto it = threads_.begin(); it != threads_.end(); ++it) { if (&*(*it) == &t.get()) { @@ -135,7 +123,7 @@ ThreadPool::threadEnded(std::thread& thread) // If new threads start later, increase the expiration delay. if (threadExpirationDelay > std::chrono::hours(24 * 7)) { // If we reach 7 days, assume the thread is regularly used at full capacity - minThreads_ = std::min(minThreads_+1, maxThreads_); + minThreads_ = std::min(minThreads_ + 1, maxThreads_); } else { threadExpirationDelay *= threadDelayRatio_; } @@ -147,7 +135,7 @@ ThreadPool::stop(bool wait) { std::unique_lock l(lock_); if (wait) { - cv_.wait(l, [&](){ return tasks_.empty(); }); + cv_.wait(l, [&]() { return tasks_.empty(); }); } running_ = false; tasks_ = {}; @@ -190,7 +178,7 @@ Executor::run_(std::function&& task) { current_++; std::weak_ptr w = shared_from_this(); - threadPool_.get().run([w,task = std::move(task)] { + threadPool_.get().run([w, task = std::move(task)] { try { task(); } catch (const std::exception& e) { @@ -214,4 +202,4 @@ Executor::schedule() } } -} +} // namespace dht diff --git a/src/utils.cpp b/src/utils.cpp index 599ddb60..56e05e22 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" diff --git a/src/value.cpp b/src/value.cpp index a514bbd5..6f5f8ad4 100644 --- a/src/value.cpp +++ b/src/value.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" diff --git a/src/value_cache.h b/src/value_cache.h index ba62345e..730d95bd 100644 --- a/src/value_cache.h +++ b/src/value_cache.h @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "value.h" @@ -25,22 +11,29 @@ enum class ListenSyncStatus { ADDED, SYNCED, UNSYNCED, REMOVED }; using SyncCallback = std::function; using CallbackQueue = std::list>; -class ValueCache { +class ValueCache +{ public: explicit ValueCache(ValueStateCallback&& cb, SyncCallback&& scb = {}) - : callback(std::forward(cb)), syncCallback(std::move(scb)) + : callback(std::forward(cb)) + , syncCallback(std::move(scb)) { if (syncCallback) syncCallback(ListenSyncStatus::ADDED); } - ValueCache(ValueCache&& o) noexcept : values(std::move(o.values)), callback(std::move(o.callback)), syncCallback(std::move(o.syncCallback)) { + ValueCache(ValueCache&& o) noexcept + : values(std::move(o.values)) + , callback(std::move(o.callback)) + , syncCallback(std::move(o.syncCallback)) + { o.callback = {}; o.syncCallback = {}; } - ~ValueCache() { + ~ValueCache() + { auto q = clear(); - for (auto& cb: q) + for (auto& cb : q) cb(); if (syncCallback) { if (status == ListenSyncStatus::SYNCED) @@ -49,7 +42,8 @@ public: } } - CallbackQueue clear() { + CallbackQueue clear() + { std::vector> expired_values; expired_values.reserve(values.size()); for (auto& v : values) @@ -57,14 +51,13 @@ public: values.clear(); CallbackQueue ret; if (not expired_values.empty() and callback) { - ret.emplace_back([expired_values = std::move(expired_values), cb = callback]{ - cb(expired_values, true); - }); + ret.emplace_back([expired_values = std::move(expired_values), cb = callback] { cb(expired_values, true); }); } return ret; } - time_point expireValues(const time_point& now) { + time_point expireValues(const time_point& now) + { time_point ret = time_point::max(); auto cbs = expireValues(now, ret); while (not cbs.empty()) { @@ -74,7 +67,8 @@ public: return ret; } - CallbackQueue expireValues(const time_point& now, time_point& next) { + CallbackQueue expireValues(const time_point& now, time_point& next) + { std::vector> expired_values; for (auto it = values.begin(); it != values.end();) { if (it->second.expiration <= now) { @@ -101,18 +95,16 @@ public: } CallbackQueue ret; if (not expired_values.empty() and callback) { - ret.emplace_back([cb = callback, expired_values = std::move(expired_values)]{ - cb(expired_values, true); - }); + ret.emplace_back([cb = callback, expired_values = std::move(expired_values)] { cb(expired_values, true); }); } return ret; } - time_point onValues - (const std::vector>& new_values, - const std::vector& refreshed_values, - const std::vector& expired_values, - const TypeStore& types, const time_point& now) + time_point onValues(const std::vector>& new_values, + const std::vector& refreshed_values, + const std::vector& expired_values, + const TypeStore& types, + const time_point& now) { CallbackQueue cbs; time_point ret = time_point::max(); @@ -130,7 +122,8 @@ public: return ret; } - void onSynced(bool synced) { + void onSynced(bool synced) + { auto newStatus = synced ? ListenSyncStatus::SYNCED : ListenSyncStatus::UNSYNCED; if (status != newStatus) { status = newStatus; @@ -139,9 +132,7 @@ public: } } - size_t size() const { - return values.size(); - } + size_t size() const { return values.size(); } private: // prevent copy @@ -152,14 +143,18 @@ private: /* The maximum number of values we store in the cache. */ static constexpr unsigned MAX_VALUES {4096}; - struct CacheValueStorage { + struct CacheValueStorage + { Sp data {}; time_point created {}; time_point expiration {}; CacheValueStorage() {} CacheValueStorage(const Sp& v, time_point t, time_point e) - : data(v), created(t), expiration(e) {} + : data(v) + , created(t) + , expiration(e) + {} }; std::map values; @@ -167,7 +162,8 @@ private: SyncCallback syncCallback; ListenSyncStatus status {ListenSyncStatus::UNSYNCED}; - CallbackQueue addValues(const std::vector>& new_values, const TypeStore& types, const time_point& now) { + CallbackQueue addValues(const std::vector>& new_values, const TypeStore& types, const time_point& now) + { std::vector> nvals; for (const auto& value : new_values) { auto v = values.find(value->id); @@ -183,24 +179,25 @@ private: } CallbackQueue ret; if (callback and not nvals.empty()) - ret.emplace_back([cb = callback, nvals = std::move(nvals)]{ - cb(nvals, false); - }); + ret.emplace_back([cb = callback, nvals = std::move(nvals)] { cb(nvals, false); }); return ret; } - CallbackQueue expireValue(Value::Id vid) { + CallbackQueue expireValue(Value::Id vid) + { auto v = values.find(vid); if (v == values.end()) return {}; std::vector> val {std::move(v->second.data)}; values.erase(v); CallbackQueue ret; - ret.emplace_back([cb = callback, val = std::move(val)]{ - if (cb) cb(val, true); + ret.emplace_back([cb = callback, val = std::move(val)] { + if (cb) + cb(val, true); }); return ret; } - void refreshValue(Value::Id vid, const TypeStore& types, const time_point& now) { + void refreshValue(Value::Id vid, const TypeStore& types, const time_point& now) + { auto v = values.find(vid); if (v == values.end()) return; @@ -209,4 +206,4 @@ private: } }; -} +} // namespace dht diff --git a/tests/cryptotester.cpp b/tests/cryptotester.cpp index e26988fd..6e6105f0 100644 --- a/tests/cryptotester.cpp +++ b/tests/cryptotester.cpp @@ -1,21 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * Vsevolod Ivanov - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "cryptotester.h" diff --git a/tests/cryptotester.h b/tests/cryptotester.h index 674a234c..43dee56c 100644 --- a/tests/cryptotester.h +++ b/tests/cryptotester.h @@ -1,22 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * Vsevolod Ivanov - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once // cppunit diff --git a/tests/dhtproxy_stress_tester.cpp b/tests/dhtproxy_stress_tester.cpp index 62cfa953..fe7bc41c 100644 --- a/tests/dhtproxy_stress_tester.cpp +++ b/tests/dhtproxy_stress_tester.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "dhtproxy_stress_tester.h" @@ -28,7 +14,8 @@ namespace test { CPPUNIT_TEST_SUITE_REGISTRATION(DhtProxyStressTester); void -DhtProxyStressTester::setUp() { +DhtProxyStressTester::setUp() +{ logger = dht::log::getStdLogger(); dht::DhtRunner::Context ctx; @@ -55,26 +42,28 @@ DhtProxyStressTester::setUp() { } void -DhtProxyStressTester::tearDown() { +DhtProxyStressTester::tearDown() +{ nodePeer.join(); nodeClient.join(); bool done = false; std::condition_variable cv; std::mutex cv_m; - nodeProxy->shutdown([&]{ + nodeProxy->shutdown([&] { std::lock_guard lk(cv_m); done = true; cv.notify_all(); }); std::unique_lock lk(cv_m); - CPPUNIT_ASSERT(cv.wait_for(lk, 15s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 15s, [&] { return done; })); serverProxy.reset(); nodeProxy.reset(); } void -DhtProxyStressTester::testRepeatValues() { +DhtProxyStressTester::testRepeatValues() +{ dht::DhtRunner::Context ctx; ctx.logger = logger; nodeClient.run(0, clientConfig, std::move(ctx)); @@ -95,7 +84,7 @@ DhtProxyStressTester::testRepeatValues() { done = true; cv.notify_all(); }); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); done = false; std::vector values; @@ -109,7 +98,7 @@ DhtProxyStressTester::testRepeatValues() { } return true; }); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); done = false; // Here values should contains 1 values CPPUNIT_ASSERT_EQUAL(static_cast(values.size()), 1); @@ -119,7 +108,7 @@ DhtProxyStressTester::testRepeatValues() { dht::Value secondVal {"You're a monster"}; auto secondVal_data = secondVal.data; nodePeer.put(key, std::move(secondVal)); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); nodeClient.cancelListen(key, std::move(token)); CPPUNIT_ASSERT_EQUAL(static_cast(values.size()), 2); CPPUNIT_ASSERT(values.back() == secondVal_data); @@ -147,7 +136,7 @@ DhtProxyStressTester::testRepeatValues() { done = true; cv.notify_all(); }); - CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return done; })); done = false; // temporary node to make sure the value is retrieved auto tmpValues = tmpNode->get(key); @@ -165,7 +154,7 @@ DhtProxyStressTester::testRepeatValues() { } return true; }); - CPPUNIT_ASSERT(cv.wait_for(lk, 25s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 25s, [&] { return done; })); done = false; bool found_value = false; @@ -182,4 +171,4 @@ DhtProxyStressTester::testRepeatValues() { } } -} // namespace test +} // namespace test diff --git a/tests/dhtproxy_stress_tester.h b/tests/dhtproxy_stress_tester.h index 998a8c5a..518cf98f 100644 --- a/tests/dhtproxy_stress_tester.h +++ b/tests/dhtproxy_stress_tester.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once // cppunit @@ -27,27 +12,28 @@ namespace test { -class DhtProxyStressTester : public CppUnit::TestFixture { +class DhtProxyStressTester : public CppUnit::TestFixture +{ CPPUNIT_TEST_SUITE(DhtProxyStressTester); CPPUNIT_TEST(testRepeatValues); CPPUNIT_TEST_SUITE_END(); - public: +public: /** * Method automatically called before each test by CppUnit * Init nodes */ - void setUp(); + void setUp(); /** * Method automatically called after each test CppUnit */ - void tearDown(); + void tearDown(); /** * Test get and put methods */ - void testRepeatValues(); + void testRepeatValues(); - private: +private: std::shared_ptr logger; dht::DhtRunner::Config clientConfig {}; dht::DhtRunner nodePeer; @@ -56,4 +42,4 @@ class DhtProxyStressTester : public CppUnit::TestFixture { std::unique_ptr serverProxy; }; -} // namespace test +} // namespace test diff --git a/tests/dhtproxytester.cpp b/tests/dhtproxytester.cpp index 6863f98a..bb9ee3ff 100644 --- a/tests/dhtproxytester.cpp +++ b/tests/dhtproxytester.cpp @@ -1,21 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * Vsevolod Ivanov - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "dhtproxytester.h" @@ -32,7 +16,8 @@ namespace test { CPPUNIT_TEST_SUITE_REGISTRATION(DhtProxyTester); void -DhtProxyTester::setUp() { +DhtProxyTester::setUp() +{ clientConfig.dht_config.node_config.max_peer_req_per_sec = -1; clientConfig.dht_config.node_config.max_req_per_sec = -1; @@ -46,12 +31,12 @@ DhtProxyTester::setUp() { bound.setLoopback(); nodeProxy->bootstrap(bound); - //auto serverCAIdentity = dht::crypto::generateEcIdentity("DHT Node CA"); + // auto serverCAIdentity = dht::crypto::generateEcIdentity("DHT Node CA"); uint16_t port = 1024 + (std::rand() % (65535 - 1024)); dht::ProxyServerConfig serverConfig; - //serverConfig.identity = dht::crypto::generateIdentity("DHT Node", serverCAIdentity); + // serverConfig.identity = dht::crypto::generateIdentity("DHT Node", serverCAIdentity); serverConfig.port = port; // serverConfig.pushServer = "127.0.0.1:8090"; serverProxy = std::make_unique(nodeProxy, serverConfig); @@ -59,30 +44,32 @@ DhtProxyTester::setUp() { /*clientConfig.server_ca = serverCAIdentity.second; clientConfig.client_identity = dht::crypto::generateIdentity("DhtProxyTester"); clientConfig.push_node_id = "dhtnode";*/ - clientConfig.proxy_server = "http://127.0.0.1:" + std::to_string(port);//"https://127.0.0.1:8080"; + clientConfig.proxy_server = "http://127.0.0.1:" + std::to_string(port); //"https://127.0.0.1:8080"; } void -DhtProxyTester::tearDown() { +DhtProxyTester::tearDown() +{ nodePeer.join(); nodeClient.join(); bool done = false; std::condition_variable cv; std::mutex cv_m; - nodeProxy->shutdown([&]{ + nodeProxy->shutdown([&] { std::lock_guard lk(cv_m); done = true; cv.notify_all(); }); std::unique_lock lk(cv_m); - CPPUNIT_ASSERT(cv.wait_for(lk, 15s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 15s, [&] { return done; })); serverProxy.reset(); nodeProxy.reset(); } void -DhtProxyTester::testGetPut() { +DhtProxyTester::testGetPut() +{ nodeClient.run(0, clientConfig); bool done = false; @@ -99,7 +86,7 @@ DhtProxyTester::testGetPut() { cv.notify_all(); }); std::unique_lock lk(cv_m); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); } auto vals = nodeClient.get(key).get(); @@ -108,7 +95,8 @@ DhtProxyTester::testGetPut() { } void -DhtProxyTester::testListen() { +DhtProxyTester::testListen() +{ nodeClient.run(0, clientConfig); std::condition_variable cv; @@ -127,7 +115,7 @@ DhtProxyTester::testListen() { done = true; cv.notify_all(); }); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); done = false; std::vector values; @@ -141,7 +129,7 @@ DhtProxyTester::testListen() { } return true; }); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); done = false; // Here values should contains 1 values CPPUNIT_ASSERT_EQUAL(static_cast(values.size()), 1); @@ -152,7 +140,7 @@ DhtProxyTester::testListen() { dht::Value secondVal {"You're a monster"}; auto secondVal_data = secondVal.data; nodePeer.put(key, std::move(secondVal)); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); nodeClient.cancelListen(key, std::move(token)); // Here values should contains 2 values CPPUNIT_ASSERT_EQUAL(static_cast(values.size()), 2); @@ -160,7 +148,8 @@ DhtProxyTester::testListen() { } void -DhtProxyTester::testResubscribeGetValues() { +DhtProxyTester::testResubscribeGetValues() +{ clientConfig.push_token = "atlas"; nodeClient.run(0, clientConfig); @@ -180,14 +169,12 @@ DhtProxyTester::testResubscribeGetValues() { done = true; cv.notify_all(); }); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); done = false; // Send a first subscribe, the value is sent via a push notification // So ignore values here. - nodeClient.listen(key, [&](const std::vector>&, bool) { - return true; - }); + nodeClient.listen(key, [&](const std::vector>&, bool) { return true; }); cv.wait_for(lk, std::chrono::seconds(1)); // Reboot node (to avoid cache) @@ -207,12 +194,12 @@ DhtProxyTester::testResubscribeGetValues() { return true; }); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); auto token = ftoken.get(); CPPUNIT_ASSERT(token); nodeClient.cancelListen(key, token); // Here values should still contains 1 values - CPPUNIT_ASSERT_EQUAL((size_t)1u, values.size()); + CPPUNIT_ASSERT_EQUAL((size_t) 1u, values.size()); CPPUNIT_ASSERT(firstVal_data == values.front()->data); } @@ -242,21 +229,24 @@ DhtProxyTester::testPutGet40KChars() done_put = ok; cv.notify_all(); }); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done_put; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done_put; })); - nodeClient.get(key, [&](const std::vector>& vals){ - values.insert(values.end(), vals.begin(), vals.end()); - return true; - },[&](bool ok){ - std::lock_guard lk(cv_m); - done_get = ok; - cv.notify_all(); - }); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done_get; })); + nodeClient.get( + key, + [&](const std::vector>& vals) { + values.insert(values.end(), vals.begin(), vals.end()); + return true; + }, + [&](bool ok) { + std::lock_guard lk(cv_m); + done_get = ok; + cv.notify_all(); + }); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done_get; })); // Assert - CPPUNIT_ASSERT_EQUAL((size_t)1u, values.size()); - for (const auto &value: values) + CPPUNIT_ASSERT_EQUAL((size_t) 1u, values.size()); + for (const auto& value : values) CPPUNIT_ASSERT(value->data == mtu); } @@ -277,20 +267,19 @@ DhtProxyTester::testFuzzy() for (size_t i = 0; i < 100; i++) { auto nodeTest = std::make_shared(); nodeTest->run(0, clientConfig); - nodeTest->put(key, dht::Value(mtu), [&](bool ok) { - CPPUNIT_ASSERT(ok); - }); - nodeTest->get(key, [&](const std::vector>& vals){ - values.insert(values.end(), vals.begin(), vals.end()); - return true; - },[&](bool ok){ - CPPUNIT_ASSERT(ok); - }); + nodeTest->put(key, dht::Value(mtu), [&](bool ok) { CPPUNIT_ASSERT(ok); }); + nodeTest->get( + key, + [&](const std::vector>& vals) { + values.insert(values.end(), vals.begin(), vals.end()); + return true; + }, + [&](bool ok) { CPPUNIT_ASSERT(ok); }); std::this_thread::sleep_for(5ms); } // Assert - for (const auto &value: values) + for (const auto& value : values) CPPUNIT_ASSERT(value->data == mtu); } @@ -314,27 +303,28 @@ DhtProxyTester::testShutdownStop() for (size_t i = 0; i < C; i++) { auto nodeTest = std::make_shared(); nodeTest->run(0, clientConfig); - nodeTest->put(key, dht::Value(mtu), [&](bool /*ok*/) { - callback_count++; - }); - nodeTest->get(key, [&](const std::vector>& vals){ - values.insert(values.end(), vals.begin(), vals.end()); - return true; - },[&](bool /*ok*/){ - callback_count++; - }); + nodeTest->put(key, dht::Value(mtu), [&](bool /*ok*/) { callback_count++; }); + nodeTest->get( + key, + [&](const std::vector>& vals) { + values.insert(values.end(), vals.begin(), vals.end()); + return true; + }, + [&](bool /*ok*/) { callback_count++; }); bool done = false; std::condition_variable cv; std::mutex cv_m; - nodeTest->shutdown([&]{ - std::lock_guard lk(cv_m); - done = true; - cv.notify_all(); - }, true); + nodeTest->shutdown( + [&] { + std::lock_guard lk(cv_m); + done = true; + cv.notify_all(); + }, + true); std::unique_lock lk(cv_m); - CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&]{ return done; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 10s, [&] { return done; })); } - CPPUNIT_ASSERT_EQUAL(2*C, callback_count.load()); + CPPUNIT_ASSERT_EQUAL(2 * C, callback_count.load()); } -} // namespace test +} // namespace test diff --git a/tests/dhtproxytester.h b/tests/dhtproxytester.h index c699d50c..1e192052 100644 --- a/tests/dhtproxytester.h +++ b/tests/dhtproxytester.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once // cppunit @@ -27,7 +12,8 @@ namespace test { -class DhtProxyTester : public CppUnit::TestFixture { +class DhtProxyTester : public CppUnit::TestFixture +{ CPPUNIT_TEST_SUITE(DhtProxyTester); CPPUNIT_TEST(testGetPut); CPPUNIT_TEST(testListen); @@ -37,39 +23,39 @@ class DhtProxyTester : public CppUnit::TestFixture { CPPUNIT_TEST(testShutdownStop); CPPUNIT_TEST_SUITE_END(); - public: +public: /** * Method automatically called before each test by CppUnit * Init nodes */ - void setUp(); + void setUp(); /** * Method automatically called after each test CppUnit */ - void tearDown(); + void tearDown(); /** * Test get and put methods */ - void testGetPut(); + void testGetPut(); /** * Test listen */ - void testListen(); - /** - * When a proxy redo a subscribe on the proxy - * it should retrieve existant values - */ - void testResubscribeGetValues(); - /** - * Test MTU put/get on dht - */ - void testPutGet40KChars(); + void testListen(); + /** + * When a proxy redo a subscribe on the proxy + * it should retrieve existant values + */ + void testResubscribeGetValues(); + /** + * Test MTU put/get on dht + */ + void testPutGet40KChars(); - void testFuzzy(); + void testFuzzy(); - void testShutdownStop(); + void testShutdownStop(); - private: +private: dht::DhtRunner::Config clientConfig {}; dht::DhtRunner nodePeer; dht::DhtRunner nodeClient; @@ -77,4 +63,4 @@ class DhtProxyTester : public CppUnit::TestFixture { std::unique_ptr serverProxy; }; -} // namespace test +} // namespace test diff --git a/tests/dhtrunnertester.cpp b/tests/dhtrunnertester.cpp index c2ba596c..0c21272c 100644 --- a/tests/dhtrunnertester.cpp +++ b/tests/dhtrunnertester.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "dhtrunnertester.h" @@ -29,7 +15,8 @@ namespace test { CPPUNIT_TEST_SUITE_REGISTRATION(DhtRunnerTester); void -DhtRunnerTester::setUp() { +DhtRunnerTester::setUp() +{ dht::DhtRunner::Config config; config.dht_config.node_config.max_peer_req_per_sec = -1; config.dht_config.node_config.max_req_per_sec = -1; @@ -45,11 +32,12 @@ DhtRunnerTester::setUp() { } void -DhtRunnerTester::tearDown() { +DhtRunnerTester::tearDown() +{ unsigned done {0}; std::condition_variable cv; std::mutex cv_m; - auto shutdown = [&]{ + auto shutdown = [&] { std::lock_guard lk(cv_m); done++; cv.notify_all(); @@ -57,13 +45,14 @@ DhtRunnerTester::tearDown() { node1.shutdown(shutdown); node2.shutdown(shutdown); std::unique_lock lk(cv_m); - CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]{ return done == 2u; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return done == 2u; })); node1.join(); node2.join(); } void -DhtRunnerTester::testConstructors() { +DhtRunnerTester::testConstructors() +{ CPPUNIT_ASSERT(node1.getBoundPort()); CPPUNIT_ASSERT_EQUAL(node1.getBoundPort(), node1.getBound().getPort()); CPPUNIT_ASSERT(node2.getBoundPort()); @@ -77,14 +66,13 @@ DhtRunnerTester::testConstructors() { } void -DhtRunnerTester::testGetPut() { +DhtRunnerTester::testGetPut() +{ auto key = dht::InfoHash::get("123"); dht::Value val {"hey"}; auto val_data = val.data; std::promise p; - node2.put(key, std::move(val), [&](bool ok){ - p.set_value(ok); - }); + node2.put(key, std::move(val), [&](bool ok) { p.set_value(ok); }); CPPUNIT_ASSERT(p.get_future().get()); auto vals = node1.get(key).get(); CPPUNIT_ASSERT(not vals.empty()); @@ -92,19 +80,16 @@ DhtRunnerTester::testGetPut() { } void -DhtRunnerTester::testPutDuplicate() { +DhtRunnerTester::testPutDuplicate() +{ auto key = dht::InfoHash::get("123"); auto val = std::make_shared("hey"); val->id = 42; auto val_data = val->data; std::promise p1; std::promise p2; - node2.put(key, val, [&](bool ok){ - p1.set_value(ok); - }); - node2.put(key, val, [&](bool ok){ - p2.set_value(ok); - }); + node2.put(key, val, [&](bool ok) { p1.set_value(ok); }); + node2.put(key, val, [&](bool ok) { p2.set_value(ok); }); auto p1ret = p1.get_future().get(); auto p2ret = p2.get_future().get(); CPPUNIT_ASSERT(p1ret); @@ -115,9 +100,9 @@ DhtRunnerTester::testPutDuplicate() { CPPUNIT_ASSERT(vals.front()->data == val_data); } - void -DhtRunnerTester::testPutOverride() { +DhtRunnerTester::testPutOverride() +{ auto key = dht::InfoHash::get("123"); auto val = std::make_shared("meh"); val->id = 42; @@ -127,12 +112,8 @@ DhtRunnerTester::testPutOverride() { auto val_data = val2->data; std::promise p1; std::promise p2; - node2.put(key, val, [&](bool ok){ - p1.set_value(ok); - }); - node2.put(key, val2, [&](bool ok){ - p2.set_value(ok); - }); + node2.put(key, val, [&](bool ok) { p1.set_value(ok); }); + node2.put(key, val2, [&](bool ok) { p2.set_value(ok); }); auto p1ret = p1.get_future().get(); auto p2ret = p2.get_future().get(); CPPUNIT_ASSERT(!p1ret); @@ -143,9 +124,9 @@ DhtRunnerTester::testPutOverride() { CPPUNIT_ASSERT(vals.front()->data == val_data); } - void -DhtRunnerTester::testListen() { +DhtRunnerTester::testListen() +{ std::mutex mutex; std::condition_variable cv; std::atomic_uint valueCounta(0); @@ -203,17 +184,19 @@ DhtRunnerTester::testListen() { for (size_t i = 0; i < SZ; i++) mtu.emplace_back((i % 2) ? 'T' : 'M'); - for (unsigned i=0; i(); @@ -221,14 +204,15 @@ DhtRunnerTester::testListen() { node2.put(c, std::move(bigVal), [&](bool ok) { std::lock_guard lock(mutex); putCount++; - if (ok) putOkCount3++; + if (ok) + putOkCount3++; cv.notify_all(); }); } { std::unique_lock lk(mutex); - CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]{ return putCount == N * 3u; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return putCount == N * 3u; })); CPPUNIT_ASSERT_EQUAL(N, putOkCount1); CPPUNIT_ASSERT_EQUAL(N, putOkCount2); CPPUNIT_ASSERT_EQUAL(N, putOkCount3); @@ -259,7 +243,8 @@ DhtRunnerTester::testListen() { } void -DhtRunnerTester::testIdOps() { +DhtRunnerTester::testIdOps() +{ std::mutex mutex; std::condition_variable cv; unsigned identityCount(0); @@ -288,10 +273,10 @@ DhtRunnerTester::testIdOps() { { std::unique_lock lk(mutex); - CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]{ return identityCount == 1; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return identityCount == 1; })); } - node1.findCertificate(node2.getId(), [&](const std::shared_ptr& crt){ + node1.findCertificate(node2.getId(), [&](const std::shared_ptr& crt) { CPPUNIT_ASSERT(crt); std::lock_guard lk(mutex); valueCount++; @@ -300,7 +285,7 @@ DhtRunnerTester::testIdOps() { { std::unique_lock lk(mutex); - CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]{ return valueCount == 1u; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return valueCount == 1u; })); CPPUNIT_ASSERT_EQUAL(1u, identityCount); } @@ -321,21 +306,21 @@ DhtRunnerTester::testIdOps() { node1.bootstrap(bound); auto key = dht::InfoHash::get("key"); - node1.putEncrypted(key, node2.getId(), dht::Value("yo"), [&](bool ok){ + node1.putEncrypted(key, node2.getId(), dht::Value("yo"), [&](bool ok) { CPPUNIT_ASSERT(ok); std::lock_guard lk(mutex); valueCount++; cv.notify_all(); }); - node1.putEncrypted(key, node2.getPublicKey(), std::make_shared("yo"), [&](bool ok){ + node1.putEncrypted(key, node2.getPublicKey(), std::make_shared("yo"), [&](bool ok) { CPPUNIT_ASSERT(ok); std::lock_guard lk(mutex); valueCount++; cv.notify_all(); }); - node2.listen(key, [&](std::string&& value){ + node2.listen(key, [&](std::string&& value) { CPPUNIT_ASSERT_EQUAL("yo"s, value); std::lock_guard lk(mutex); valueCount++; @@ -345,13 +330,13 @@ DhtRunnerTester::testIdOps() { auto key2 = dht::InfoHash::get("key2"); auto editValue = std::make_shared("v1"); - node1.putSigned(key2, editValue, [&](bool ok){ + node1.putSigned(key2, editValue, [&](bool ok) { CPPUNIT_ASSERT(ok); std::lock_guard lk(mutex); valueCountEdit++; cv.notify_all(); }); - node2.listen(key2, [&](const std::vector>& values, bool /*expired*/){ + node2.listen(key2, [&](const std::vector>& values, bool /*expired*/) { for (const auto& v : values) { if (v->seq == 0) CPPUNIT_ASSERT_EQUAL("v1"s, dht::unpackMsg(v->data)); @@ -367,12 +352,12 @@ DhtRunnerTester::testIdOps() { { std::unique_lock lk(mutex); - CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]{ return identityCount == 2u; })); - CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]{ return valueCount == 5u; })); - CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]{ return valueCountEdit == 2u; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return identityCount == 2u; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return valueCount == 5u; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return valueCountEdit == 2u; })); } - node2.findCertificate(node1.getPublicKey()->getLongId(), [&](const std::shared_ptr& crt){ + node2.findCertificate(node1.getPublicKey()->getLongId(), [&](const std::shared_ptr& crt) { CPPUNIT_ASSERT(crt); std::lock_guard lk(mutex); valueCount++; @@ -381,24 +366,25 @@ DhtRunnerTester::testIdOps() { { std::unique_lock lk(mutex); - CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]{ return valueCount == 6u; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return valueCount == 6u; })); } // editValue->data = dht::packMsg("v2"); editValue = std::make_shared(editValue->id); editValue->data = dht::packMsg("v2"); - node1.putSigned(key2, editValue, [&](bool ok){ + node1.putSigned(key2, editValue, [&](bool ok) { CPPUNIT_ASSERT(ok); std::lock_guard lk(mutex); valueCountEdit++; cv.notify_all(); }); std::unique_lock lk(mutex); - CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&]{ return valueCountEdit == 4u; })); + CPPUNIT_ASSERT(cv.wait_for(lk, 20s, [&] { return valueCountEdit == 4u; })); } void -DhtRunnerTester::testListenLotOfBytes() { +DhtRunnerTester::testListenLotOfBytes() +{ std::mutex mutex; std::condition_variable cv; std::atomic_uint valueCount(0); @@ -410,17 +396,18 @@ DhtRunnerTester::testListenLotOfBytes() { auto foo = dht::InfoHash::get("foo"); constexpr unsigned N = 1024; - for (unsigned i=0; i&){ - return true; - }, [&](bool ok) { - std::lock_guard lock(mutex); - putCount++; - if (ok) putOkCount++; + if (ok) + putOkCount++; cv.notify_all(); }); + node2.get( + dht::InfoHash::get("123" + std::to_string(N - i - 1)), + [](const std::shared_ptr&) { return true; }, + [&](bool ok) { + std::lock_guard lock(mutex); + putCount++; + if (ok) + putOkCount++; + cv.notify_all(); + }); }); } std::unique_lock lk(mutex); - CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&]{ return putCount == 2*N; })); - CPPUNIT_ASSERT_EQUAL(2*N, putOkCount); - + CPPUNIT_ASSERT(cv.wait_for(lk, 30s, [&] { return putCount == 2 * N; })); + CPPUNIT_ASSERT_EQUAL(2 * N, putOkCount); } - -} // namespace test +} // namespace test diff --git a/tests/dhtrunnertester.h b/tests/dhtrunnertester.h index e426a642..e191fcd6 100644 --- a/tests/dhtrunnertester.h +++ b/tests/dhtrunnertester.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once // cppunit @@ -25,7 +10,8 @@ namespace test { -class DhtRunnerTester : public CppUnit::TestFixture { +class DhtRunnerTester : public CppUnit::TestFixture +{ CPPUNIT_TEST_SUITE(DhtRunnerTester); CPPUNIT_TEST(testConstructors); CPPUNIT_TEST(testGetPut); @@ -38,7 +24,8 @@ class DhtRunnerTester : public CppUnit::TestFixture { dht::DhtRunner node1 {}; dht::DhtRunner node2 {}; - public: + +public: /** * Method automatically called before each test by CppUnit */ @@ -79,7 +66,6 @@ class DhtRunnerTester : public CppUnit::TestFixture { * Test multithread */ void testMultithread(); - }; -} // namespace test +} // namespace test diff --git a/tests/httptester.cpp b/tests/httptester.cpp index 24bcb18f..4d9ddb11 100644 --- a/tests/httptester.cpp +++ b/tests/httptester.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "httptester.h" diff --git a/tests/httptester.h b/tests/httptester.h index 54da7288..78bfd181 100644 --- a/tests/httptester.h +++ b/tests/httptester.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once // cppunit @@ -30,7 +15,8 @@ namespace test { -class HttpTester : public CppUnit::TestFixture { +class HttpTester : public CppUnit::TestFixture +{ CPPUNIT_TEST_SUITE(HttpTester); // parse_url CPPUNIT_TEST(test_parse_url); @@ -57,53 +43,53 @@ class HttpTester : public CppUnit::TestFixture { CPPUNIT_TEST(test_send_json); CPPUNIT_TEST_SUITE_END(); - public: +public: /** * Method automatically called before each test by CppUnit * Init nodes */ - void setUp(); + void setUp(); /** * Method automatically called after each test CppUnit */ - void tearDown(); + void tearDown(); /** * Test parse urls */ - void test_parse_url(); - void test_parse_https_url_no_service(); - void test_parse_url_no_prefix_no_target(); - void test_parse_url_target(); - void test_parse_url_query(); - void test_parse_url_fragment(); + void test_parse_url(); + void test_parse_https_url_no_service(); + void test_parse_url_no_prefix_no_target(); + void test_parse_url_target(); + void test_parse_url_query(); + void test_parse_url_fragment(); /** * Test parse urls (ipv4) */ - void test_parse_url_ipv4(); - void test_parse_url_no_prefix_no_target_ipv4(); - void test_parse_url_target_ipv4(); + void test_parse_url_ipv4(); + void test_parse_url_no_prefix_no_target_ipv4(); + void test_parse_url_target_ipv4(); /** * Test parse urls (ipv6) */ - void test_parse_url_ipv6(); - void test_parse_url_no_prefix_no_target_ipv6(); - void test_parse_url_target_ipv6(); - void test_parse_url_user_pass(); - void test_parse_url_user_only(); - void test_parse_url_ipv6_brackets(); - void test_parse_url_ipv6_brackets_port(); - void test_parse_url_mixed_case_protocol(); - void test_parse_url_complex_path_query_fragment(); - void test_parse_url_empty(); - void test_parse_url_just_slash(); + void test_parse_url_ipv6(); + void test_parse_url_no_prefix_no_target_ipv6(); + void test_parse_url_target_ipv6(); + void test_parse_url_user_pass(); + void test_parse_url_user_only(); + void test_parse_url_ipv6_brackets(); + void test_parse_url_ipv6_brackets_port(); + void test_parse_url_mixed_case_protocol(); + void test_parse_url_complex_path_query_fragment(); + void test_parse_url_empty(); + void test_parse_url_just_slash(); /** * Test send(json) */ - void test_send_json(); + void test_send_json(); - private: +private: std::shared_ptr nodePeer; std::unique_ptr serverProxy; }; -} // namespace test +} // namespace test diff --git a/tests/infohashtester.cpp b/tests/infohashtester.cpp index 34a66503..0c7f8b9f 100644 --- a/tests/infohashtester.cpp +++ b/tests/infohashtester.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "infohashtester.h" @@ -28,20 +14,20 @@ namespace test { CPPUNIT_TEST_SUITE_REGISTRATION(InfoHashTester); void -InfoHashTester::setUp() { - -} +InfoHashTester::setUp() +{} void -InfoHashTester::testConstructors() { +InfoHashTester::testConstructors() +{ // Default constructor creates a null infohash auto nullHash = dht::InfoHash(); - CPPUNIT_ASSERT_EQUAL((size_t)20u, nullHash.size()); + CPPUNIT_ASSERT_EQUAL((size_t) 20u, nullHash.size()); CPPUNIT_ASSERT(!nullHash); // Build from a uint8_t. if length to short, should get a null infohash uint8_t to_short[] = {0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8}; auto infohash = dht::InfoHash(to_short, 8); - CPPUNIT_ASSERT_EQUAL((size_t)20u, infohash.size()); + CPPUNIT_ASSERT_EQUAL((size_t) 20u, infohash.size()); CPPUNIT_ASSERT_EQUAL(std::string("0000000000000000000000000000000000000000"), infohash.toString()); // Build from a uint8_t. if length is enough, data should contains the uint8_t uint8_t enough[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, @@ -53,8 +39,8 @@ InfoHashTester::testConstructors() { CPPUNIT_ASSERT_EQUAL(enough[i], data[i]); } // if too long, should be cutted to 20 - uint8_t tooLong[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, - 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb0}; + uint8_t tooLong[] = {0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0x1, + 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb0}; infohash = dht::InfoHash(tooLong, 21); CPPUNIT_ASSERT(infohash.size() == 20); const auto* data2 = infohash.data(); @@ -63,26 +49,27 @@ InfoHashTester::testConstructors() { } // Build from string auto infohashFromStr = dht::InfoHash("0102030405060708090A0102030405060708090A"); - CPPUNIT_ASSERT_EQUAL((size_t)20u, infohashFromStr.size()); + CPPUNIT_ASSERT_EQUAL((size_t) 20u, infohashFromStr.size()); const auto* dataStr = infohashFromStr.data(); for (auto i = 0; i < 20; ++i) { - CPPUNIT_ASSERT_EQUAL((int)dataStr[i], (int)data[i]); + CPPUNIT_ASSERT_EQUAL((int) dataStr[i], (int) data[i]); } } void -InfoHashTester::testComparators() { +InfoHashTester::testComparators() +{ auto nullHash = dht::InfoHash(); auto minHash = dht::InfoHash("0000000000000000000000000000000000111110"); auto maxHash = dht::InfoHash("0111110000000000000000000000000000000000"); // operator == CPPUNIT_ASSERT_EQUAL(minHash, minHash); CPPUNIT_ASSERT_EQUAL(minHash, dht::InfoHash("0000000000000000000000000000000000111110")); - CPPUNIT_ASSERT(!(minHash == maxHash)); + CPPUNIT_ASSERT(!(minHash == maxHash)); // operator != CPPUNIT_ASSERT(!(minHash != minHash)); CPPUNIT_ASSERT(!(minHash != dht::InfoHash("0000000000000000000000000000000000111110"))); - CPPUNIT_ASSERT(minHash != maxHash); + CPPUNIT_ASSERT(minHash != maxHash); // operator< CPPUNIT_ASSERT(nullHash < minHash); CPPUNIT_ASSERT(nullHash < maxHash); @@ -94,11 +81,11 @@ InfoHashTester::testComparators() { // bool() CPPUNIT_ASSERT(maxHash); CPPUNIT_ASSERT(!nullHash); - } void -InfoHashTester::testLowBit() { +InfoHashTester::testLowBit() +{ auto nullHash = dht::InfoHash(); auto minHash = dht::InfoHash("0000000000000000000000000000000000000010"); auto maxHash = dht::InfoHash("0100000000000000000000000000000000000000"); @@ -108,18 +95,20 @@ InfoHashTester::testLowBit() { } void -InfoHashTester::testCommonBits() { +InfoHashTester::testCommonBits() +{ auto nullHash = dht::InfoHash(); auto minHash = dht::InfoHash("0000000000000000000000000000000000000010"); auto maxHash = dht::InfoHash("0100000000000000000000000000000000000000"); - CPPUNIT_ASSERT_EQUAL(dht::InfoHash::commonBits(nullHash, nullHash), (unsigned)160); - CPPUNIT_ASSERT_EQUAL(dht::InfoHash::commonBits(nullHash, minHash), (unsigned)155); - CPPUNIT_ASSERT_EQUAL(dht::InfoHash::commonBits(nullHash, maxHash), (unsigned)7); - CPPUNIT_ASSERT_EQUAL(dht::InfoHash::commonBits(minHash, maxHash), (unsigned)7); + CPPUNIT_ASSERT_EQUAL(dht::InfoHash::commonBits(nullHash, nullHash), (unsigned) 160); + CPPUNIT_ASSERT_EQUAL(dht::InfoHash::commonBits(nullHash, minHash), (unsigned) 155); + CPPUNIT_ASSERT_EQUAL(dht::InfoHash::commonBits(nullHash, maxHash), (unsigned) 7); + CPPUNIT_ASSERT_EQUAL(dht::InfoHash::commonBits(minHash, maxHash), (unsigned) 7); } void -InfoHashTester::testXorCmp() { +InfoHashTester::testXorCmp() +{ auto nullHash = dht::InfoHash(); auto minHash = dht::InfoHash("0000000000000000000000000000000000000010"); auto maxHash = dht::InfoHash("0100000000000000000000000000000000000000"); @@ -135,7 +124,8 @@ InfoHashTester::testXorCmp() { } void -InfoHashTester::testHex() { +InfoHashTester::testHex() +{ const std::string TEST_HASH_STR("01b20304d5060708090a010203e05060708090ae"); dht::InfoHash TEST_HASH(TEST_HASH_STR); CPPUNIT_ASSERT_EQUAL(TEST_HASH_STR, TEST_HASH.toString()); @@ -143,7 +133,6 @@ InfoHashTester::testHex() { } void -InfoHashTester::tearDown() { - -} -} // namespace test +InfoHashTester::tearDown() +{} +} // namespace test diff --git a/tests/infohashtester.h b/tests/infohashtester.h index 360892da..ac1c009f 100644 --- a/tests/infohashtester.h +++ b/tests/infohashtester.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once // cppunit @@ -23,7 +8,8 @@ namespace test { -class InfoHashTester : public CppUnit::TestFixture { +class InfoHashTester : public CppUnit::TestFixture +{ CPPUNIT_TEST_SUITE(InfoHashTester); CPPUNIT_TEST(testConstructors); CPPUNIT_TEST(testComparators); @@ -33,7 +19,7 @@ class InfoHashTester : public CppUnit::TestFixture { CPPUNIT_TEST(testHex); CPPUNIT_TEST_SUITE_END(); - public: +public: /** * Method automatically called before each test by CppUnit */ @@ -69,4 +55,4 @@ class InfoHashTester : public CppUnit::TestFixture { void testHex(); }; -} // namespace test +} // namespace test diff --git a/tests/peerdiscoverytester.cpp b/tests/peerdiscoverytester.cpp index cf5b6b66..ce9ed965 100644 --- a/tests/peerdiscoverytester.cpp +++ b/tests/peerdiscoverytester.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "peerdiscoverytester.h" #include "opendht/value.h" @@ -29,13 +15,15 @@ constexpr unsigned MULTICAST_PORT = 2222; constexpr auto DHT_NODE_NAME {"dht"sv}; constexpr auto JAMI_NODE_NAME {"jami"sv}; -struct DhtNode { +struct DhtNode +{ dht::InfoHash nodeid; in_port_t node_port; dht::NetId nid; MSGPACK_DEFINE(nodeid, node_port, nid) }; -struct JamiNode { +struct JamiNode +{ int num; char cha; std::string str; @@ -44,9 +32,12 @@ struct JamiNode { CPPUNIT_TEST_SUITE_REGISTRATION(PeerDiscoveryTester); -void PeerDiscoveryTester::setUp(){} +void +PeerDiscoveryTester::setUp() +{} -void PeerDiscoveryTester::testMulticastToTwoNodes() +void +PeerDiscoveryTester::testMulticastToTwoNodes() { DhtNode dhtNode; dhtNode.nid = 10; @@ -67,7 +58,7 @@ void PeerDiscoveryTester::testMulticastToTwoNodes() dht::PeerDiscovery testDht(MULTICAST_PORT); dht::PeerDiscovery testJami(MULTICAST_PORT); - testJami.startDiscovery(DHT_NODE_NAME,[&](DhtNode&& v, dht::SockAddr&&){ + testJami.startDiscovery(DHT_NODE_NAME, [&](DhtNode&& v, dht::SockAddr&&) { CPPUNIT_ASSERT_EQUAL(dhtNode.node_port, v.node_port); CPPUNIT_ASSERT_EQUAL(dhtNode.nodeid, v.nodeid); CPPUNIT_ASSERT_EQUAL(dhtNode.nid, v.nid); @@ -78,7 +69,7 @@ void PeerDiscoveryTester::testMulticastToTwoNodes() cv.notify_all(); }); - testJami.startDiscovery(JAMI_NODE_NAME,[&](msgpack::object&& obj, dht::SockAddr&&){ + testJami.startDiscovery(JAMI_NODE_NAME, [&](msgpack::object&& obj, dht::SockAddr&&) { auto v = obj.as(); CPPUNIT_ASSERT_EQUAL(jamiNode.num, v.num); CPPUNIT_ASSERT_EQUAL(jamiNode.cha, v.cha); @@ -91,14 +82,10 @@ void PeerDiscoveryTester::testMulticastToTwoNodes() }); testDht.startPublish(DHT_NODE_NAME, dhtNode); - CPPUNIT_ASSERT(cv.wait_for(l, std::chrono::seconds(5), [&]{ - return countDht > 0; - })); + CPPUNIT_ASSERT(cv.wait_for(l, std::chrono::seconds(5), [&] { return countDht > 0; })); testDht.startPublish(JAMI_NODE_NAME, jamiNode); - CPPUNIT_ASSERT(cv.wait_for(l, std::chrono::seconds(5), [&]{ - return countDht > 1 and countJami > 0; - })); + CPPUNIT_ASSERT(cv.wait_for(l, std::chrono::seconds(5), [&] { return countDht > 1 and countJami > 0; })); // we don't verify count values since its a continious multicasting l.unlock(); @@ -109,6 +96,8 @@ void PeerDiscoveryTester::testMulticastToTwoNodes() } } -void PeerDiscoveryTester::tearDown(){} +void +PeerDiscoveryTester::tearDown() +{} -} // namespace test +} // namespace test diff --git a/tests/peerdiscoverytester.h b/tests/peerdiscoverytester.h index 88c8a502..33a913a0 100644 --- a/tests/peerdiscoverytester.h +++ b/tests/peerdiscoverytester.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once #include "opendht/peer_discovery.h" @@ -24,13 +9,13 @@ namespace test { -class PeerDiscoveryTester : public CppUnit::TestFixture { - +class PeerDiscoveryTester : public CppUnit::TestFixture +{ CPPUNIT_TEST_SUITE(PeerDiscoveryTester); CPPUNIT_TEST(testMulticastToTwoNodes); CPPUNIT_TEST_SUITE_END(); - public: +public: /** * Method automatically called before each test by CppUnit */ @@ -45,4 +30,4 @@ class PeerDiscoveryTester : public CppUnit::TestFixture { void testMulticastToTwoNodes(); }; -} // namespace test +} // namespace test diff --git a/tests/tests_runner.cpp b/tests/tests_runner.cpp index 35f44abb..36bfc63b 100644 --- a/tests/tests_runner.cpp +++ b/tests/tests_runner.cpp @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include #include #include @@ -24,7 +9,9 @@ extern "C" { #include } -int main(int /*argc*/, char** /*argv*/) { +int +main(int /*argc*/, char** /*argv*/) +{ #ifdef _MSC_VER if (auto err = gnutls_global_init()) { std::cerr << "Failed to initialize GnuTLS: " << gnutls_strerror(err) << std::endl; @@ -32,8 +19,8 @@ int main(int /*argc*/, char** /*argv*/) { } #endif - CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry(); - CppUnit::Test *suite = registry.makeTest(); + CppUnit::TestFactoryRegistry& registry = CppUnit::TestFactoryRegistry::getRegistry(); + CppUnit::Test* suite = registry.makeTest(); if (suite->countTestCases() == 0) { std::cout << "No test cases specified for suite" << std::endl; return 1; diff --git a/tests/threadpooltester.cpp b/tests/threadpooltester.cpp index f487abba..d841c2cf 100644 --- a/tests/threadpooltester.cpp +++ b/tests/threadpooltester.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "threadpooltester.h" @@ -26,20 +12,18 @@ CPPUNIT_TEST_SUITE_REGISTRATION(ThreadPoolTester); using clock = std::chrono::steady_clock; void -ThreadPoolTester::setUp() { - -} +ThreadPoolTester::setUp() +{} void -ThreadPoolTester::testThreadPool() { +ThreadPoolTester::testThreadPool() +{ dht::ThreadPool pool(16); constexpr unsigned N = 64 * 1024; std::atomic_uint count {0}; - for (unsigned i=0; irun([&] { count1++; }); executor4->run([&] { count4++; }); executor8->run([&] { count8++; }); } auto start = clock::now(); - while ((count1 != N || - count4.load() != N || - count8.load() != N) && clock::now() - start < std::chrono::seconds(20)) - { + while ((count1 != N || count4.load() != N || count8.load() != N) + && clock::now() - start < std::chrono::seconds(20)) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } executor1.reset(); @@ -90,17 +72,16 @@ ThreadPoolTester::testContext() { dht::ExecutionContext ctx(dht::ThreadPool::computation()); - for (unsigned i=0; i. - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once // cppunit @@ -23,14 +8,15 @@ namespace test { -class ThreadPoolTester : public CppUnit::TestFixture { +class ThreadPoolTester : public CppUnit::TestFixture +{ CPPUNIT_TEST_SUITE(ThreadPoolTester); CPPUNIT_TEST(testThreadPool); CPPUNIT_TEST(testExecutor); CPPUNIT_TEST(testContext); CPPUNIT_TEST_SUITE_END(); - public: +public: /** * Method automatically called before each test by CppUnit */ @@ -45,4 +31,4 @@ class ThreadPoolTester : public CppUnit::TestFixture { void testContext(); }; -} // namespace test +} // namespace test diff --git a/tests/valuetester.cpp b/tests/valuetester.cpp index f878c612..d2f08289 100644 --- a/tests/valuetester.cpp +++ b/tests/valuetester.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include "valuetester.h" @@ -27,14 +13,14 @@ namespace test { CPPUNIT_TEST_SUITE_REGISTRATION(ValueTester); void -ValueTester::setUp() { - -} +ValueTester::setUp() +{} void -ValueTester::testConstructors() { +ValueTester::testConstructors() +{ std::string the_data {"42 cats"}; - dht::Value the_dht_value {(const uint8_t*)the_data.data(), the_data.size()}; + dht::Value the_dht_value {(const uint8_t*) the_data.data(), the_data.size()}; std::string from_value {the_dht_value.data.begin(), the_dht_value.data.end()}; CPPUNIT_ASSERT_EQUAL(the_data, from_value); } @@ -44,21 +30,17 @@ ValueTester::testFilter() { dht::Value::Filter defaultFiler {}; - auto isPairSize = dht::Value::Filter([](const dht::Value& v) { - return v.data.size() % 2 == 0; - }); + auto isPairSize = dht::Value::Filter([](const dht::Value& v) { return v.data.size() % 2 == 0; }); - auto isUserTypeTest = dht::Value::Filter([](const dht::Value& v) { - return v.user_type == "test"; - }); + auto isUserTypeTest = dht::Value::Filter([](const dht::Value& v) { return v.user_type == "test"; }); std::string data1 {"42 cats"}; - dht::Value value1 {(const uint8_t*)data1.data(), data1.size()}; + dht::Value value1 {(const uint8_t*) data1.data(), data1.size()}; value1.user_type = "test"; std::string data2 {"420 cats"}; - dht::Value value2 {(const uint8_t*)data2.data(), data2.size()}; - dht::Value value3 {(const uint8_t*)data2.data(), data2.size()}; + dht::Value value2 {(const uint8_t*) data2.data(), data2.size()}; + dht::Value value3 {(const uint8_t*) data2.data(), data2.size()}; value3.user_type = "test"; CPPUNIT_ASSERT(!isPairSize(value1)); @@ -75,7 +57,6 @@ ValueTester::testFilter() } void -ValueTester::tearDown() { - -} -} // namespace test +ValueTester::tearDown() +{} +} // namespace test diff --git a/tests/valuetester.h b/tests/valuetester.h index f6154efb..69070e70 100644 --- a/tests/valuetester.h +++ b/tests/valuetester.h @@ -1,20 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ - +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #pragma once // cppunit @@ -23,13 +8,14 @@ namespace test { -class ValueTester : public CppUnit::TestFixture { +class ValueTester : public CppUnit::TestFixture +{ CPPUNIT_TEST_SUITE(ValueTester); CPPUNIT_TEST(testConstructors); CPPUNIT_TEST(testFilter); CPPUNIT_TEST_SUITE_END(); - public: +public: /** * Method automatically called before each test by CppUnit */ @@ -48,4 +34,4 @@ class ValueTester : public CppUnit::TestFixture { void testFilter(); }; -} // namespace test +} // namespace test diff --git a/tools/dhtchat.cpp b/tools/dhtchat.cpp index 9fcd01ca..53cfaa8a 100644 --- a/tools/dhtchat.cpp +++ b/tools/dhtchat.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -31,21 +17,25 @@ using namespace dht; static std::mt19937_64 rd {dht::crypto::getSeededRandomEngine()}; static std::uniform_int_distribution rand_id; -const std::string printTime(const std::time_t& now) { +const std::string +printTime(const std::time_t& now) +{ struct tm tstruct = *localtime(&now); char buf[80]; strftime(buf, sizeof(buf), "%Y-%m-%d %X", &tstruct); return buf; } -void print_usage() { +void +print_usage() +{ std::cout << "Usage: dhtchat [-n network_id] [-p local_port] [-b bootstrap_host[:port]]" << std::endl << std::endl; std::cout << "dhtchat, a simple OpenDHT command line chat client." << std::endl; std::cout << "Report bugs to: https://opendht.net" << std::endl; } int -main(int argc, char **argv) +main(int argc, char** argv) { auto params = parseArgs(argc, argv); if (params.help) { @@ -82,8 +72,7 @@ main(int argc, char **argv) using_history(); #endif - while (true) - { + while (true) { // using the GNU Readline API std::string line = readLine(connected ? PROMPT : "> "); if (!line.empty() && line[0] == '\0') @@ -95,7 +84,7 @@ main(int argc, char **argv) std::string op, idstr; iss >> op; if (not connected) { - if (op == "x" || op == "q" || op == "exit" || op == "quit") + if (op == "x" || op == "q" || op == "exit" || op == "quit") break; else if (op == "c") { iss >> idstr; @@ -107,9 +96,11 @@ main(int argc, char **argv) token = dht.listen(room, [&](dht::ImMessage&& msg) { if (msg.from != myid) - std::cout << msg.from.toString() << " at " << printTime(msg.date) - << " (took " << print_duration(std::chrono::system_clock::now() - std::chrono::system_clock::from_time_t(msg.date)) - << ") " << (msg.to == myid ? "ENCRYPTED ":"") << ": " << msg.id << " - " << msg.msg << std::endl; + std::cout << msg.from.toString() << " at " << printTime(msg.date) << " (took " + << print_duration(std::chrono::system_clock::now() + - std::chrono::system_clock::from_time_t(msg.date)) + << ") " << (msg.to == myid ? "ENCRYPTED " : "") << ": " << msg.id << " - " + << msg.msg << std::endl; return true; }); connected = true; @@ -125,25 +116,28 @@ main(int argc, char **argv) } else if (op == "e") { iss >> idstr; std::getline(iss, line); - dht.putEncrypted(room, InfoHash(idstr), dht::ImMessage(rand_id(rd), std::move(line), now), [](bool ok) { - //dht.cancelPut(room, id); - if (not ok) - std::cout << "Message publishing failed !" << std::endl; - }); + dht.putEncrypted(room, + InfoHash(idstr), + dht::ImMessage(rand_id(rd), std::move(line), now), + [](bool ok) { + // dht.cancelPut(room, id); + if (not ok) + std::cout << "Message publishing failed !" << std::endl; + }); } else { dht.putSigned(room, dht::ImMessage(rand_id(rd), std::move(line), now), [](bool ok) { - //dht.cancelPut(room, id); + // dht.cancelPut(room, id); if (not ok) std::cout << "Message publishing failed !" << std::endl; }); } } } - } catch(const std::exception&e) { - std::cerr << std::endl << e.what() << std::endl; + } catch (const std::exception& e) { + std::cerr << std::endl << e.what() << std::endl; } - std::cout << std::endl << "Stopping node..." << std::endl; + std::cout << std::endl << "Stopping node..." << std::endl; dht.join(); #ifdef _MSC_VER gnutls_global_deinit(); diff --git a/tools/dhtcnode.c b/tools/dhtcnode.c index 40b501e4..57320441 100644 --- a/tools/dhtcnode.c +++ b/tools/dhtcnode.c @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include diff --git a/tools/dhtnode.cpp b/tools/dhtnode.cpp index 8c5163bd..52b15587 100644 --- a/tools/dhtnode.cpp +++ b/tools/dhtnode.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -32,40 +18,56 @@ extern "C" { using namespace dht; -void print_info() { +void +print_info() +{ std::cout << "dhtnode, a simple OpenDHT command line node runner." << std::endl; std::cout << "Report bugs to: https://opendht.net" << std::endl; } -void print_version() { +void +print_version() +{ std::cout << "OpenDHT version " << dht::version() << std::endl; print_info(); } -void print_usage() { - std::cout << "Usage: dhtnode [-v [-l logfile]] [-i] [-d] [-n network_id] [-p local_port] [-b bootstrap_host[:port]] [--proxyserver local_port] [--proxyserverssl local_port] [--bundleid bundleid] [--pushserver endpoint]" << std::endl << std::endl; +void +print_usage() +{ + std::cout + << "Usage: dhtnode [-v [-l logfile]] [-i] [-d] [-n network_id] [-p local_port] [-b bootstrap_host[:port]] " + "[--proxyserver local_port] [--proxyserverssl local_port] [--bundleid bundleid] [--pushserver endpoint]" + << std::endl + << std::endl; print_info(); } -void print_id_req() { +void +print_id_req() +{ std::cout << "An identity is required to perform this operation (run with -i)" << std::endl; } -void print_help() { +void +print_help() +{ std::cout << "OpenDHT command line interface (CLI)" << std::endl; std::cout << "Possible commands:" << std::endl << " h, help Print this help message." << std::endl << " x, quit Quit the program." << std::endl << " log Start/stop printing DHT logs." << std::endl; - std::cout << std::endl << "Node information:" << std::endl + std::cout << std::endl + << "Node information:" << std::endl << " ll Print basic information and stats about the current node." << std::endl << " ls [key] Print basic information about current search(es)." << std::endl << " ld [key] Print basic information about currenty stored values on this node (or key)." << std::endl << " lr Print the full current routing table of this node." << std::endl; #ifdef OPENDHT_PROXY_SERVER - std::cout << std::endl << "Operations with the proxy:" << std::endl + std::cout << std::endl + << "Operations with the proxy:" << std::endl #ifdef OPENDHT_PUSH_NOTIFICATIONS << " pst [port] Start the proxy interface on port." << std::endl #else @@ -73,10 +75,11 @@ void print_help() { << " psx [port] Start the proxy ssl interface on port." << std::endl #endif // OPENDHT_PUSH_NOTIFICATIONS << " psp [port] Stop the proxy interface on port." << std::endl; -#endif //OPENDHT_PROXY_SERVER +#endif // OPENDHT_PROXY_SERVER #ifdef OPENDHT_PROXY_CLIENT - std::cout << std::endl << "Operations with the proxy:" << std::endl + std::cout << std::endl + << "Operations with the proxy:" << std::endl #ifdef OPENDHT_PUSH_NOTIFICATIONS << " stt [server_address] Start the proxy client." << std::endl << " rs [token] Resubscribe to opendht." << std::endl @@ -85,32 +88,41 @@ void print_help() { << " stt [server_address] Start the proxy client." << std::endl #endif // OPENDHT_PUSH_NOTIFICATIONS << " stp Stop the proxy client." << std::endl; -#endif //OPENDHT_PROXY_CLIENT +#endif // OPENDHT_PROXY_CLIENT - std::cout << std::endl << "Operations on the DHT:" << std::endl - << " b Ping potential node at given IP address/port." << std::endl - << " g Get values at ." << std::endl - << " l Listen for value changes at ." << std::endl - << " cl Cancel listen for and ." << std::endl - << " p Put string value at ." << std::endl - << " pp Put string value at (persistent version)." << std::endl - << " cpp Cancel persistent put operation for and value ." << std::endl - << " s Put string value at , signed with our generated private key." << std::endl - << " e Put string value at , encrypted for with its public key (if found)." << std::endl - << " cc Trigger connectivity changed signal." << std::endl; + std::cout + << std::endl + << "Operations on the DHT:" << std::endl + << " b Ping potential node at given IP address/port." << std::endl + << " g Get values at ." << std::endl + << " l Listen for value changes at ." << std::endl + << " cl Cancel listen for and ." << std::endl + << " p Put string value at ." << std::endl + << " pp Put string value at (persistent version)." << std::endl + << " cpp Cancel persistent put operation for and value ." << std::endl + << " s Put string value at , signed with our generated private key." << std::endl + << " e Put string value at , encrypted for with its public key (if found)." + << std::endl + << " cc Trigger connectivity changed signal." << std::endl; #ifdef OPENDHT_INDEXATION - std::cout << std::endl << "Indexation operations on the DHT:" << std::endl - << " il [exact match] Lookup the index named with the key ." << std::endl - << " Set [exact match] to 'false' for inexact match lookup." << std::endl - << " ii Inserts the value under the key in the index named ." << std::endl - << std::endl; + std::cout + << std::endl + << "Indexation operations on the DHT:" << std::endl + << " il [exact match] Lookup the index named with the key ." << std::endl + << " Set [exact match] to 'false' for inexact match lookup." << std::endl + << " ii Inserts the value under the key in the index named ." + << std::endl + << std::endl; #endif } -void cmd_loop(std::shared_ptr& node, dht_params& params +void +cmd_loop(std::shared_ptr& node, + dht_params& params #ifdef OPENDHT_PROXY_SERVER - , std::map>& proxies + , + std::map>& proxies #endif ) { @@ -126,8 +138,7 @@ void cmd_loop(std::shared_ptr& node, dht_params& params std::map indexes; #endif - while (true) - { + while (true) { // using the GNU Readline API std::string line = readLine(); if (!line.empty() && line[0] == '\0') @@ -146,7 +157,8 @@ void cmd_loop(std::shared_ptr& node, dht_params& params node->getNodeInfo([&](const std::shared_ptr& nodeInfo) { print_node_info(*nodeInfo); std::cout << nodeInfo->ongoing_ops << " ongoing operations" << std::endl; - std::cout << "Storage has " << nodeInfo->storage_values << " values, using " << (nodeInfo->storage_size/1024) << " KB" << std::endl; + std::cout << "Storage has " << nodeInfo->storage_values << " values, using " + << (nodeInfo->storage_size / 1024) << " KB" << std::endl; std::cout << "IPv4 stats:" << std::endl; std::cout << nodeInfo->ipv4.toString() << std::endl; std::cout << "IPv6 stats:" << std::endl; @@ -184,7 +196,7 @@ void cmd_loop(std::shared_ptr& node, dht_params& params else std::cout << node->getSearchesLog() << std::endl; continue; - } else if (op == "la") { + } else if (op == "la") { std::cout << "Reported public addresses:" << std::endl; auto addrs = node->getPublicAddressStr(); for (const auto& addr : addrs) @@ -214,9 +226,9 @@ void cmd_loop(std::shared_ptr& node, dht_params& params #ifdef OPENDHT_PROXY_SERVER else if (op == "pst") { #ifdef OPENDHT_PUSH_NOTIFICATIONS - iss >> idstr >> pushServer; + iss >> idstr >> pushServer; #else - iss >> idstr; + iss >> idstr; #endif // OPENDHT_PUSH_NOTIFICATIONS try { in_port_t port = std::stoi(idstr); @@ -224,27 +236,28 @@ void cmd_loop(std::shared_ptr& node, dht_params& params serverConfig.port = port; serverConfig.pushServer = pushServer; proxies.emplace(port, std::make_unique(node, serverConfig)); - } catch (...) { } + } catch (...) { + } continue; } else if (op == "psx") { #ifdef OPENDHT_PUSH_NOTIFICATIONS - iss >> idstr >> pushServer; + iss >> idstr >> pushServer; #else - iss >> idstr; + iss >> idstr; #endif // OPENDHT_PUSH_NOTIFICATIONS try { - if (params.proxy_id.first and params.proxy_id.second){ + if (params.proxy_id.first and params.proxy_id.second) { in_port_t port = std::stoi(idstr); ProxyServerConfig serverConfig; serverConfig.identity = params.proxy_id; serverConfig.port = port; serverConfig.pushServer = pushServer; proxies.emplace(port, std::make_unique(node, serverConfig)); - } - else { + } else { std::cerr << "Missing Identity private key or certificate" << std::endl; } - } catch (...) { } + } catch (...) { + } continue; } else if (op == "psp") { iss >> idstr; @@ -252,10 +265,11 @@ void cmd_loop(std::shared_ptr& node, dht_params& params auto it = proxies.find(std::stoi(idstr)); if (it != proxies.end()) proxies.erase(it); - } catch (...) { } + } catch (...) { + } continue; } -#endif //OPENDHT_PROXY_SERVER +#endif // OPENDHT_PROXY_SERVER #ifdef OPENDHT_PROXY_CLIENT else if (op == "stt") { node->enableProxy(true); @@ -267,16 +281,19 @@ void cmd_loop(std::shared_ptr& node, dht_params& params #ifdef OPENDHT_PUSH_NOTIFICATIONS else if (op == "rp") { iss >> value; - node->pushNotificationReceived({{"to", "dhtnode"}, {"token", value}}); + node->pushNotificationReceived({ + {"to", "dhtnode"}, + {"token", value } + }); continue; } #endif // OPENDHT_PUSH_NOTIFICATIONS -#endif //OPENDHT_PROXY_CLIENT +#endif // OPENDHT_PROXY_CLIENT if (op.empty()) continue; - static const std::set VALID_OPS {"g", "l", "cl", "il", "ii", "p", "pp", "cpp", "s", "e", "a", "q"}; + static const std::set VALID_OPS {"g", "l", "cl", "il", "ii", "p", "pp", "cpp", "s", "e", "a", "q"}; if (VALID_OPS.find(op) == VALID_OPS.cend()) { std::cout << "Unknown command: " << op << std::endl; std::cout << " (type 'h' or 'help' for a list of possible commands)" << std::endl; @@ -284,15 +301,18 @@ void cmd_loop(std::shared_ptr& node, dht_params& params } dht::InfoHash id; - if (false) {} + if (false) { + } #ifdef OPENDHT_INDEXATION else if (op == "il" or op == "ii") { // Pht syntax iss >> index >> keystr; - auto new_index = std::find_if(indexes.begin(), indexes.end(), - [&](std::pair& i) { - return i.first == index; - }) == indexes.end(); + auto new_index = std::find_if(indexes.begin(), + indexes.end(), + [&](std::pair& i) { + return i.first == index; + }) + == indexes.end(); if (not index.size()) { std::cerr << "You must enter the index name." << std::endl; continue; @@ -305,7 +325,9 @@ void cmd_loop(std::shared_ptr& node, dht_params& params return std::make_pair(f.first, f.second.size()); }); indexes.emplace(index, Pht {index, std::move(ks), node}); - } catch (std::invalid_argument& e) { std::cout << e.what() << std::endl; } + } catch (std::invalid_argument& e) { + std::cout << e.what() << std::endl; + } } } #endif @@ -329,47 +351,63 @@ void cmd_loop(std::shared_ptr& node, dht_params& params std::string rem; std::getline(iss, rem); auto total = std::make_shared(); - node->get(id, [start, total](const std::vector>& values) { - auto now = std::chrono::high_resolution_clock::now(); - (*total) += values.size(); - std::cout << "Get: found " << values.size() << " value(s) after " << print_duration(now-start) << " (total " << *total << ')' << std::endl; - for (const auto& value : values) - std::cout << "\t" << *value << std::endl; - return true; - }, [start, total](bool ok) { - auto end = std::chrono::high_resolution_clock::now(); - std::cout << "Get: " << (ok ? "completed" : "failure") << ", took " << print_duration(end-start) << " (total " << *total << ')' << std::endl; - }, {}, dht::Where {rem}); - } - else if (op == "q") { + node->get( + id, + [start, total](const std::vector>& values) { + auto now = std::chrono::high_resolution_clock::now(); + (*total) += values.size(); + std::cout << "Get: found " << values.size() << " value(s) after " << print_duration(now - start) + << " (total " << *total << ')' << std::endl; + for (const auto& value : values) + std::cout << "\t" << *value << std::endl; + return true; + }, + [start, total](bool ok) { + auto end = std::chrono::high_resolution_clock::now(); + std::cout << "Get: " << (ok ? "completed" : "failure") << ", took " << print_duration(end - start) + << " (total " << *total << ')' << std::endl; + }, + {}, + dht::Where {rem}); + } else if (op == "q") { std::string rem; std::getline(iss, rem); - node->query(id, [start](const std::vector>& field_value_indexes) { - auto now = std::chrono::high_resolution_clock::now(); - for (auto& index : field_value_indexes) { - std::cout << "Query: found field value index after " << print_duration(now-start) << std::endl; - std::cout << "\t" << *index << std::endl; - } - return true; - }, [start](bool ok) { - auto end = std::chrono::high_resolution_clock::now(); - std::cout << "Query: " << (ok ? "completed" : "failure") << ", took " << print_duration(end-start) << std::endl; - }, dht::Query {rem}); - } - else if (op == "l") { + node->query( + id, + [start](const std::vector>& field_value_indexes) { + auto now = std::chrono::high_resolution_clock::now(); + for (auto& index : field_value_indexes) { + std::cout << "Query: found field value index after " << print_duration(now - start) + << std::endl; + std::cout << "\t" << *index << std::endl; + } + return true; + }, + [start](bool ok) { + auto end = std::chrono::high_resolution_clock::now(); + std::cout << "Query: " << (ok ? "completed" : "failure") << ", took " << print_duration(end - start) + << std::endl; + }, + dht::Query {rem}); + } else if (op == "l") { std::string rem; std::getline(iss, rem); auto total = std::make_shared(); - auto token = node->listen(id, [total](const std::vector>& values, bool expired) { - if (expired) - (*total) -= values.size(); - else - (*total) += values.size(); - std::cout << "Listen: found " << values.size() << " values" << (expired ? " expired" : "") << " (total " << *total << ')' << std::endl; - for (const auto& value : values) - std::cout << "\t" << *value << std::endl; - return true; - }, {}, dht::Where {rem}); + auto token = node->listen( + id, + [total](const std::vector>& values, bool expired) { + if (expired) + (*total) -= values.size(); + else + (*total) += values.size(); + std::cout << "Listen: found " << values.size() << " values" << (expired ? " expired" : "") + << " (total " << *total << ')' << std::endl; + for (const auto& value : values) + std::cout << "\t" << *value << std::endl; + return true; + }, + {}, + dht::Where {rem}); auto t = token.get(); std::cout << "Listening, token: " << t << std::endl; } @@ -379,47 +417,47 @@ void cmd_loop(std::shared_ptr& node, dht_params& params size_t token; try { token = std::stoul(rem); - } catch(...) { + } catch (...) { std::cerr << "Syntax: cl [key] [token]" << std::endl; continue; } node->cancelListen(id, token); - } - else if (op == "p") { + } else if (op == "p") { std::string v; iss >> v; - auto value = std::make_shared( - dht::ValueType::USER_DATA.id, - std::vector {v.begin(), v.end()}); + auto value = std::make_shared(dht::ValueType::USER_DATA.id, + std::vector {v.begin(), v.end()}); value->user_type = "text/plain"; node->put(id, value, [start, value](bool ok) { auto end = std::chrono::high_resolution_clock::now(); auto flags(std::cout.flags()); - std::cout << "Put: " << (ok ? "success" : "failure") << ", took " << print_duration(end-start) << ". Value ID: " << std::hex << value->id << std::endl; + std::cout << "Put: " << (ok ? "success" : "failure") << ", took " << print_duration(end - start) + << ". Value ID: " << std::hex << value->id << std::endl; std::cout.flags(flags); }); - } - else if (op == "pp") { + } else if (op == "pp") { std::string v; iss >> v; - auto value = std::make_shared( - dht::ValueType::USER_DATA.id, - std::vector {v.begin(), v.end()} - ); + auto value = std::make_shared(dht::ValueType::USER_DATA.id, + std::vector {v.begin(), v.end()}); value->user_type = "text/plain"; - node->put(id, value, [start, value](bool ok) { - auto end = std::chrono::high_resolution_clock::now(); - auto flags(std::cout.flags()); - std::cout << "Put: " << (ok ? "success" : "failure") << ", took " << print_duration(end-start) << ". Value ID: " << std::hex << value->id << std::endl; - std::cout.flags(flags); - }, time_point::max(), true); - } - else if (op == "cpp") { + node->put( + id, + value, + [start, value](bool ok) { + auto end = std::chrono::high_resolution_clock::now(); + auto flags(std::cout.flags()); + std::cout << "Put: " << (ok ? "success" : "failure") << ", took " << print_duration(end - start) + << ". Value ID: " << std::hex << value->id << std::endl; + std::cout.flags(flags); + }, + time_point::max(), + true); + } else if (op == "cpp") { std::string rem; iss >> rem; node->cancelPut(id, std::stoul(rem, nullptr, 16)); - } - else if (op == "s") { + } else if (op == "s") { if (not params.id.first) { print_id_req(); continue; @@ -431,10 +469,10 @@ void cmd_loop(std::shared_ptr& node, dht_params& params value->user_type = "text/plain"; node->putSigned(id, std::move(value), [start](bool ok) { auto end = std::chrono::high_resolution_clock::now(); - std::cout << "Put signed: " << (ok ? "success" : "failure") << " (took " << print_duration(end-start) << "s)" << std::endl; + std::cout << "Put signed: " << (ok ? "success" : "failure") << " (took " << print_duration(end - start) + << "s)" << std::endl; }); - } - else if (op == "e") { + } else if (op == "e") { if (not params.id.first) { print_id_req(); continue; @@ -442,23 +480,24 @@ void cmd_loop(std::shared_ptr& node, dht_params& params std::string tostr; std::string v; iss >> tostr >> v; - auto value = std::make_shared( - dht::ValueType::USER_DATA.id, - std::vector {v.begin(), v.end()} - ); + auto value = std::make_shared(dht::ValueType::USER_DATA.id, + std::vector {v.begin(), v.end()}); value->user_type = "text/plain"; node->putEncrypted(id, InfoHash(tostr), std::move(value), [start](bool ok) { auto end = std::chrono::high_resolution_clock::now(); - std::cout << "Put encrypted: " << (ok ? "success" : "failure") << " (took " << print_duration(end-start) << ')' << std::endl; + std::cout << "Put encrypted: " << (ok ? "success" : "failure") << " (took " + << print_duration(end - start) << ')' << std::endl; }); - } - else if (op == "a") { + } else if (op == "a") { in_port_t port; iss >> port; - node->put(id, dht::Value {dht::IpServiceAnnouncement::TYPE.id, dht::IpServiceAnnouncement(port)}, [start](bool ok) { - auto end = std::chrono::high_resolution_clock::now(); - std::cout << "Announce: " << (ok ? "success" : "failure") << " (took " << print_duration(end-start) << std::endl; - }); + node->put(id, + dht::Value {dht::IpServiceAnnouncement::TYPE.id, dht::IpServiceAnnouncement(port)}, + [start](bool ok) { + auto end = std::chrono::high_resolution_clock::now(); + std::cout << "Announce: " << (ok ? "success" : "failure") << " (took " + << print_duration(end - start) << std::endl; + }); } #ifdef OPENDHT_INDEXATION else if (op == "il") { @@ -466,7 +505,8 @@ void cmd_loop(std::shared_ptr& node, dht_params& params iss >> exact_match; try { auto key = createPhtKey(parseStringMap(keystr)); - indexes.at(index).lookup(key, + indexes.at(index).lookup( + key, [=](std::vector>& vals, indexation::Prefix p) { if (vals.empty()) return; @@ -475,20 +515,20 @@ void cmd_loop(std::shared_ptr& node, dht_params& params << " hash: " << p.hash() << std::endl; std::cout << " entries:" << std::endl; for (const auto& v : vals) - std::cout << " " << v->first.toString() << "[vid: " << std::hex << v->second << std::dec << "]" << std::endl; + std::cout << " " << v->first.toString() << "[vid: " << std::hex << v->second + << std::dec << "]" << std::endl; }, [start](bool ok) { auto end = std::chrono::high_resolution_clock::now(); - std::cout << "Pht::lookup: " << (ok ? "done." : "failed.") - << " took " << print_duration(end-start) << std::endl; - - }, exact_match.size() != 0 and exact_match == "false" ? false : true - ); + std::cout << "Pht::lookup: " << (ok ? "done." : "failed.") << " took " + << print_duration(end - start) << std::endl; + }, + exact_match.size() != 0 and exact_match == "false" ? false : true); + } catch (std::invalid_argument& e) { + std::cout << e.what() << std::endl; + } catch (std::out_of_range& e) { } - catch (std::invalid_argument& e) { std::cout << e.what() << std::endl; } - catch (std::out_of_range& e) { } - } - else if (op == "ii") { + } else if (op == "ii") { iss >> idstr; InfoHash h {idstr}; if (not isInfoHash(h)) @@ -497,23 +537,22 @@ void cmd_loop(std::shared_ptr& node, dht_params& params indexation::Value v {h, 0}; try { auto key = createPhtKey(parseStringMap(keystr)); - indexes.at(index).insert(key, v, - [=](bool ok) { - std::cout << "Pht::insert: " << (ok ? "done." : "failed.") << std::endl; - } - ); + indexes.at(index).insert(key, v, [=](bool ok) { + std::cout << "Pht::insert: " << (ok ? "done." : "failed.") << std::endl; + }); + } catch (std::invalid_argument& e) { + std::cout << e.what() << std::endl; + } catch (std::out_of_range& e) { } - catch (std::invalid_argument& e) { std::cout << e.what() << std::endl; } - catch (std::out_of_range& e) { } } #endif } - std::cout << std::endl << "Stopping node..." << std::endl; + std::cout << std::endl << "Stopping node..." << std::endl; } int -main(int argc, char **argv) +main(int argc, char** argv) { #ifdef _WIN32 SetConsoleOutputCP(CP_UTF8); @@ -559,19 +598,21 @@ main(int argc, char **argv) serverConfig.pushServer = params.pushserver; serverConfig.bundleId = params.bundle_id; serverConfig.address = params.proxy_address; - if (params.proxyserverssl and params.proxy_id.first and params.proxy_id.second){ + if (params.proxyserverssl and params.proxy_id.first and params.proxy_id.second) { serverConfig.identity = params.proxy_id; serverConfig.port = params.proxyserverssl; if (not params.persist_path.empty()) serverConfig.persistStatePath = params.persist_path + '_' + std::to_string(serverConfig.port); - proxies.emplace(params.proxyserverssl, std::make_unique(node, serverConfig, dhtConf.second.logger)); + proxies.emplace(params.proxyserverssl, + std::make_unique(node, serverConfig, dhtConf.second.logger)); } if (params.proxyserver) { serverConfig.identity = {}; serverConfig.port = params.proxyserver; if (not params.persist_path.empty()) serverConfig.persistStatePath = params.persist_path + '_' + std::to_string(serverConfig.port); - proxies.emplace(params.proxyserver, std::make_unique(node, serverConfig, dhtConf.second.logger)); + proxies.emplace(params.proxyserver, + std::make_unique(node, serverConfig, dhtConf.second.logger)); } #else std::cerr << "DHT proxy server requested but OpenDHT built without proxy server support." << std::endl; @@ -580,31 +621,33 @@ main(int argc, char **argv) } if (params.daemonize or params.service) - while (runner.wait()); + while (runner.wait()) + ; else - cmd_loop(node, params + cmd_loop(node, + params #ifdef OPENDHT_PROXY_SERVER - , proxies + , + proxies #endif ); - } catch(const std::exception&e) { - std::cerr << std::endl << e.what() << std::endl; + } catch (const std::exception& e) { + std::cerr << std::endl << e.what() << std::endl; } std::condition_variable cv; std::mutex m; bool done {false}; - node->shutdown([&]() - { + node->shutdown([&]() { done = true; cv.notify_all(); }); // wait for shutdown std::unique_lock lk(m); - cv.wait(lk, [&](){ return done; }); + cv.wait(lk, [&]() { return done; }); node->join(); #ifdef _MSC_VER diff --git a/tools/dhtscanner.cpp b/tools/dhtscanner.cpp index a953b158..91ee4c1d 100644 --- a/tools/dhtscanner.cpp +++ b/tools/dhtscanner.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -31,17 +17,20 @@ extern "C" { using namespace dht; -void print_usage() { - fmt::print( - "Usage: dhtscanner [-n network_id] [-p local_port] [-b bootstrap_host[:port]]\n" - "dhtscanner: a simple OpenDHT command line utility generating scan result the network.\n" - "Report bugs to: https://opendht.net\n"); +void +print_usage() +{ + fmt::print("Usage: dhtscanner [-n network_id] [-p local_port] [-b bootstrap_host[:port]]\n" + "dhtscanner: a simple OpenDHT command line utility generating scan result the network.\n" + "Report bugs to: https://opendht.net\n"); } -struct snode_compare { - bool operator() (const std::shared_ptr& lhs, const std::shared_ptr& rhs) const{ - return (lhs->id < rhs->id) || - (lhs->id == rhs->id && lhs->getFamily() == AF_INET && rhs->getFamily() == AF_INET6); +struct snode_compare +{ + bool operator()(const std::shared_ptr& lhs, const std::shared_ptr& rhs) const + { + return (lhs->id < rhs->id) + || (lhs->id == rhs->id && lhs->getFamily() == AF_INET && rhs->getFamily() == AF_INET6); } }; @@ -53,37 +42,48 @@ step(DhtRunner& dht, std::atomic_uint& done, std::shared_ptr all_nodes, { fmt::print("step at {}, depth {}\n", cur_h.to_view(), cur_depth); done++; - dht.get(cur_h, [](const std::vector>& /*values*/) { return true; }, [&, - all_nodes, + dht.get( cur_h, - cur_depth, - start_time = std::chrono::steady_clock::now() - ] (bool ok, const std::vector>& nodes) { - auto took = std::chrono::steady_clock::now() - start_time; - if (not ok) { - fmt::print("Error while getting nodes for hash {} after {}\n", cur_h.to_view(), dht::print_duration(took)); - } - all_nodes->insert(nodes.begin(), nodes.end()); - NodeSet sbuck {nodes.begin(), nodes.end()}; - if (not sbuck.empty()) { - unsigned bdepth = sbuck.size()==1 ? 0u : InfoHash::commonBits((*sbuck.begin())->id, (*sbuck.rbegin())->id); - unsigned target_depth = std::min(8u, bdepth+6u); - fmt::print("Found {} nodes for hash {}, target depth is {}\n", nodes.size(), cur_h.to_view(), target_depth); - for (unsigned b = cur_depth ; b < target_depth; b++) { - auto new_h = cur_h; - new_h.setBit(b, 1); - step(dht, done, all_nodes, new_h, b+1); + [](const std::vector>& /*values*/) { return true; }, + [&, + all_nodes, + cur_h, + cur_depth, + start_time = std::chrono::steady_clock::now()](bool ok, const std::vector>& nodes) { + auto took = std::chrono::steady_clock::now() - start_time; + if (not ok) { + fmt::print("Error while getting nodes for hash {} after {}\n", + cur_h.to_view(), + dht::print_duration(took)); } - } - done--; - fmt::print("Step for {} ended after {}. Ongoing operations: {}. Total nodes: {}\n", - cur_h.to_view(), dht::print_duration(took), done.load(), all_nodes->size()); - cv.notify_one(); - }); + all_nodes->insert(nodes.begin(), nodes.end()); + NodeSet sbuck {nodes.begin(), nodes.end()}; + if (not sbuck.empty()) { + unsigned bdepth = sbuck.size() == 1 ? 0u + : InfoHash::commonBits((*sbuck.begin())->id, (*sbuck.rbegin())->id); + unsigned target_depth = std::min(8u, bdepth + 6u); + fmt::print("Found {} nodes for hash {}, target depth is {}\n", + nodes.size(), + cur_h.to_view(), + target_depth); + for (unsigned b = cur_depth; b < target_depth; b++) { + auto new_h = cur_h; + new_h.setBit(b, 1); + step(dht, done, all_nodes, new_h, b + 1); + } + } + done--; + fmt::print("Step for {} ended after {}. Ongoing operations: {}. Total nodes: {}\n", + cur_h.to_view(), + dht::print_duration(took), + done.load(), + all_nodes->size()); + cv.notify_one(); + }); } int -main(int argc, char **argv) +main(int argc, char** argv) { #ifdef _MSC_VER if (auto err = gnutls_global_init()) { @@ -112,7 +112,7 @@ main(int argc, char **argv) // Set hash to 1 because 0 is the null hash dht::InfoHash cur_h {}; - cur_h.setBit(8*HASH_LEN-1, 1); + cur_h.setBit(8 * HASH_LEN - 1, 1); std::this_thread::sleep_for(std::chrono::seconds(2)); @@ -122,15 +122,13 @@ main(int argc, char **argv) { std::mutex m; std::unique_lock lk(m); - cv.wait(lk, [&](){ - return done.load() == 0; - }); + cv.wait(lk, [&]() { return done.load() == 0; }); } fmt::print("Scan ended: {} nodes found.\n", all_nodes->size()); for (const auto& n : *all_nodes) fmt::print("Node {}: {}\n", n->id.to_view(), n->getAddrStr()); - } catch(const std::exception&e) { + } catch (const std::exception& e) { fmt::print(stderr, "\n{}\n", e.what()); } diff --git a/tools/durl.cpp b/tools/durl.cpp index 1abf0221..3a7bac1c 100644 --- a/tools/durl.cpp +++ b/tools/durl.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #include #include @@ -26,30 +12,37 @@ using namespace dht; -void print_info() { +void +print_info() +{ std::cout << "durl, a simple http(s) client." << std::endl; std::cout << "Report bugs to: https://opendht.net" << std::endl; } -void print_version() { +void +print_version() +{ std::cout << "OpenDHT version " << dht::version() << std::endl; print_info(); } -void print_usage() { +void +print_usage() +{ std::cout << "Usage: durl url" << std::endl << std::endl; print_info(); } static const constexpr struct option long_options[] = { - {"help", no_argument , nullptr, 'h'}, - {"headers", no_argument , nullptr, 'H'}, - {"verbose", no_argument , nullptr, 'v'}, - {"version", no_argument , nullptr, 'V'}, - {nullptr, 0 , nullptr, 0} + {"help", no_argument, nullptr, 'h'}, + {"headers", no_argument, nullptr, 'H'}, + {"verbose", no_argument, nullptr, 'v'}, + {"version", no_argument, nullptr, 'V'}, + {nullptr, 0, nullptr, 0 } }; -struct durl_params { +struct durl_params +{ std::string url; bool help {false}; bool log {false}; @@ -58,7 +51,8 @@ struct durl_params { }; durl_params -parseArgs(int argc, char **argv) { +parseArgs(int argc, char** argv) +{ durl_params params; int opt; while ((opt = getopt_long(argc, argv, "hvVH", long_options, nullptr)) != -1) { @@ -79,7 +73,7 @@ parseArgs(int argc, char **argv) { break; } } - + if (optind < argc) { params.url = argv[optind++]; } @@ -88,7 +82,7 @@ parseArgs(int argc, char **argv) { } int -main(int argc, char **argv) +main(int argc, char** argv) { auto params = parseArgs(argc, argv); if (params.help) { @@ -106,15 +100,19 @@ main(int argc, char **argv) } asio::io_context ctx; - auto request = std::make_shared(ctx, params.url, [&](const dht::http::Response& response){ - if (params.headers) { - for (const auto& header : response.headers) - std::cout << header.first << ": " << header.second << std::endl; - std::cout << std::endl; - } - std::cout << response.body << std::endl; - ctx.stop(); - }, logger); + auto request = std::make_shared( + ctx, + params.url, + [&](const dht::http::Response& response) { + if (params.headers) { + for (const auto& header : response.headers) + std::cout << header.first << ": " << header.second << std::endl; + std::cout << std::endl; + } + std::cout << response.body << std::endl; + ctx.stop(); + }, + logger); request->send(); auto work = asio::make_work_guard(ctx); ctx.run(); diff --git a/tools/perftest.cpp b/tools/perftest.cpp index 960ca15a..401550c3 100644 --- a/tools/perftest.cpp +++ b/tools/perftest.cpp @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -28,7 +14,9 @@ extern "C" { #include #include -void print_usage() { +void +print_usage() +{ std::cout << "Usage: perftest" << std::endl << std::endl; std::cout << "perftest, a simple OpenDHT basic performance tester." << std::endl; std::cout << "Report bugs to: https://opendht.net" << std::endl; @@ -42,7 +30,8 @@ using clock = std::chrono::high_resolution_clock; using duration = clock::duration; duration -benchPingPong(unsigned netSize, unsigned n_parallel) { +benchPingPong(unsigned netSize, unsigned n_parallel) +{ DhtRunner::Config config {}; config.dht_config.node_config.max_peer_req_per_sec = -1; config.dht_config.node_config.max_req_per_sec = -1; @@ -51,7 +40,7 @@ benchPingPong(unsigned netSize, unsigned n_parallel) { std::vector> locs; locs.reserve(n_parallel); - for (unsigned i=0; i> nodes; nodes.reserve(netSize); - for (unsigned i=0; i(); node->run(0, config); node->bootstrap(bindAddr); @@ -80,19 +69,19 @@ benchPingPong(unsigned netSize, unsigned n_parallel) { auto ping = [&](DhtRunner& node, InfoHash h) { std::lock_guard lk(m); - if (i < max) { + if (i < max) { i++; node.put(h, Value("hey")); } cv.notify_one(); }; - for (unsigned i=0; i&){ + for (unsigned i = 0; i < n_parallel; i++) { + ping_node.listen(locs[i].first, [&, i](const std::shared_ptr&) { ping(pong_node, locs[i].second); return true; }); - pong_node.listen(locs[i].second, [&,i](const std::shared_ptr&){ + pong_node.listen(locs[i].second, [&, i](const std::shared_ptr&) { ping(ping_node, locs[i].first); return true; }); @@ -100,12 +89,12 @@ benchPingPong(unsigned netSize, unsigned n_parallel) { auto start = clock::now(); - for (unsigned i=0; i lk(m); - if (not cv.wait_for(lk, std::chrono::minutes(1), [&](){ return i == max; })) { + if (not cv.wait_for(lk, std::chrono::minutes(1), [&]() { return i == max; })) { throw std::runtime_error(std::string("Timeout: ") + std::to_string(i)); } } @@ -122,13 +111,13 @@ benchPingPong(unsigned netSize, unsigned n_parallel) { ping_node.join(); pong_node.join(); - return end-start; + return end - start; } -} +} // namespace tests int -main(int argc, char **argv) +main(int argc, char** argv) { #ifdef _MSC_VER if (auto err = gnutls_global_init()) { @@ -145,17 +134,18 @@ main(int argc, char **argv) duration totalTime {0}; unsigned totalOps {0}; - for (unsigned nparallel = 1; nparallel <= 32; nparallel *= 2) { + for (unsigned nparallel = 1; nparallel <= 32; nparallel *= 2) { unsigned max = PINGPONG_MAX * nparallel; std::vector results {}; results.reserve(8); duration total {0}; - for (unsigned i=2; i<32; i *= 2) { + for (unsigned i = 2; i < 32; i *= 2) { auto dt = tests::benchPingPong(i - 2, nparallel); std::cout << "Network size: " << i << std::endl; std::cout << max << " ping-pong done, took " << print_duration(dt) << std::endl; - std::cout << print_duration(dt/max) << " per rt, " - << max/std::chrono::duration(dt).count() << " ping per s" << std::endl << std::endl; + std::cout << print_duration(dt / max) << " per rt, " << max / std::chrono::duration(dt).count() + << " ping per s" << std::endl + << std::endl; total += dt; totalOps += max; results.emplace_back(dt); @@ -164,15 +154,17 @@ main(int argc, char **argv) totalTime += total; std::cout << "Total for " << nparallel << std::endl; - auto totNum = max*results.size(); + auto totNum = max * results.size(); std::cout << totNum << " ping-pong done, took " << print_duration(total) << std::endl; - std::cout << print_duration(total/totNum) << " per rt, " - << totNum/std::chrono::duration(total).count() << " ping per s" << std::endl << std::endl; + std::cout << print_duration(total / totNum) << " per rt, " + << totNum / std::chrono::duration(total).count() << " ping per s" << std::endl + << std::endl; } std::cout << std::endl << "Grand total: " << print_duration(totalTime) << " for " << totalOps << std::endl; - std::cout << print_duration(totalTime/totalOps) << " per rt, " - << totalOps/std::chrono::duration(totalTime).count() << " ping per s" << std::endl << std::endl; + std::cout << print_duration(totalTime / totalOps) << " per rt, " + << totalOps / std::chrono::duration(totalTime).count() << " ping per s" << std::endl + << std::endl; #ifdef _MSC_VER gnutls_global_deinit(); diff --git a/tools/proxy_loadtester.py b/tools/proxy_loadtester.py index b54134c6..e4698976 100644 --- a/tools/proxy_loadtester.py +++ b/tools/proxy_loadtester.py @@ -1,17 +1,5 @@ # Copyright (c) 2014-2026 Savoir-faire Linux Inc. -# -# 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 . +# SPDX-License-Identifier: MIT # # Manually run with Web UI: # locust -f tester.py --host http://127.0.0.1:8080 diff --git a/tools/tools_common.h b/tools/tools_common.h index 30a97823..eb454ea3 100644 --- a/tools/tools_common.h +++ b/tools/tools_common.h @@ -1,19 +1,5 @@ -/* - * Copyright (c) 2014-2026 Savoir-faire Linux Inc. - * - * 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 . - */ +// Copyright (c) 2014-2026 Savoir-faire Linux Inc. +// SPDX-License-Identifier: MIT // Common utility methods used by C++ OpenDHT tools. #pragma once @@ -32,26 +18,26 @@ #include #ifndef _WIN32 - #include - #include - #include +#include +#include +#include #else - #ifdef _MSC_VER - #pragma message("Building on WIN32 platform using MSVC, linking wingetopt") - #include "wingetopt.h" - #endif - #if defined(__MINGW32__) || defined (__MINGW64__) - #pragma message "Building on MinGW, linking system-wide getopt" - #include - #include - #include - #endif +#ifdef _MSC_VER +#pragma message("Building on WIN32 platform using MSVC, linking wingetopt") +#include "wingetopt.h" +#endif +#if defined(__MINGW32__) || defined(__MINGW64__) +#pragma message "Building on MinGW, linking system-wide getopt" +#include +#include +#include +#endif #endif -#if defined(_MSC_VER) || defined(__MINGW32__) || defined (__MINGW64__) - #define SIGHUP 0 - #include - #define DISABLE_SIGNALS +#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__MINGW64__) +#define SIGHUP 0 +#include +#define DISABLE_SIGNALS #endif #include @@ -73,7 +59,9 @@ * * k1:v1[,k2:v2[,...]] */ -std::map parseStringMap(std::string mapString) { +std::map +parseStringMap(std::string mapString) +{ std::istringstream keySs(mapString); std::string mapStr; std::map map; @@ -84,14 +72,16 @@ std::map parseStringMap(std::string mapString) { while (std::getline(mapSs, key, ':')) { std::getline(mapSs, value, ':'); - map[key] = { value }; + map[key] = {value}; } } return map; } #ifdef OPENDHT_INDEXATION -dht::indexation::Pht::Key createPhtKey(std::map pht_key_str_map) { +dht::indexation::Pht::Key +createPhtKey(std::map pht_key_str_map) +{ dht::indexation::Pht::Key pht_key; for (auto f : pht_key_str_map) { dht::Blob prefix {f.second.begin(), f.second.end()}; @@ -101,7 +91,9 @@ dht::indexation::Pht::Key createPhtKey(std::map pht_ke } #endif -bool isInfoHash(const dht::InfoHash& h) { +bool +isInfoHash(const dht::InfoHash& h) +{ if (not h) { std::cout << "Syntax error: invalid InfoHash." << std::endl; return false; @@ -115,19 +107,20 @@ loadFile(const std::string& path) std::vector buffer; std::ifstream file(path, std::ios::binary); if (!file) - throw std::runtime_error("Can't read file: "+path); + throw std::runtime_error("Can't read file: " + path); file.seekg(0, std::ios::end); auto size = file.tellg(); if (size > std::numeric_limits::max()) - throw std::runtime_error("File is too big: "+path); + throw std::runtime_error("File is too big: " + path); buffer.resize(size); file.seekg(0, std::ios::beg); - if (!file.read((char*)buffer.data(), size)) - throw std::runtime_error("Can't load file: "+path); + if (!file.read((char*) buffer.data(), size)) + throw std::runtime_error("Can't load file: " + path); return buffer; } -struct dht_params { +struct dht_params +{ bool help {false}; // print help and exit bool version {false}; bool generate_identity {false}; @@ -209,7 +202,9 @@ getDhtConfig(dht_params& params) return {std::move(config), std::move(context)}; } -void print_node_info(const dht::NodeInfo& info) { +void +print_node_info(const dht::NodeInfo& info) +{ std::cout << "OpenDHT node " << info.node_id << " running on "; if (info.bound4 == info.bound6) std::cout << "port " << info.bound4 << std::endl; @@ -220,40 +215,41 @@ void print_node_info(const dht::NodeInfo& info) { } static const constexpr struct option long_options[] = { - {"help", no_argument , nullptr, 'h'}, - {"port", required_argument, nullptr, 'p'}, - {"net", required_argument, nullptr, 'n'}, - {"bootstrap", required_argument, nullptr, 'b'}, - {"identity", no_argument , nullptr, 'i'}, - {"save-identity", required_argument, nullptr, 'I'}, - {"certificate", required_argument, nullptr, 'c'}, - {"privkey", required_argument, nullptr, 'k'}, - {"privkey-password", required_argument, nullptr, 'm'}, - {"verbose", no_argument , nullptr, 'v'}, - {"daemonize", no_argument , nullptr, 'd'}, - {"service", no_argument , nullptr, 's'}, - {"peer-discovery", no_argument , nullptr, 'D'}, - {"no-rate-limit", no_argument , nullptr, 'U'}, - {"public-stable", no_argument , nullptr, 'P'}, - {"persist", required_argument, nullptr, 'f'}, - {"logfile", required_argument, nullptr, 'l'}, - {"syslog", no_argument , nullptr, 'L'}, - {"proxyserver", required_argument, nullptr, 'S'}, - {"proxyserverssl", required_argument, nullptr, 'e'}, - {"proxy-addr", required_argument, nullptr, 'a'}, - {"proxy-certificate", required_argument, nullptr, 'w'}, - {"proxy-privkey", required_argument, nullptr, 'K'}, - {"proxy-privkey-password", required_argument, nullptr, 'M'}, - {"proxyclient", required_argument, nullptr, 'C'}, - {"pushserver", required_argument, nullptr, 'y'}, - {"devicekey", required_argument, nullptr, 'z'}, - {"bundleid", required_argument, nullptr, 'u'}, - {"version", no_argument , nullptr, 'V'}, - {nullptr, 0 , nullptr, 0} + {"help", no_argument, nullptr, 'h'}, + {"port", required_argument, nullptr, 'p'}, + {"net", required_argument, nullptr, 'n'}, + {"bootstrap", required_argument, nullptr, 'b'}, + {"identity", no_argument, nullptr, 'i'}, + {"save-identity", required_argument, nullptr, 'I'}, + {"certificate", required_argument, nullptr, 'c'}, + {"privkey", required_argument, nullptr, 'k'}, + {"privkey-password", required_argument, nullptr, 'm'}, + {"verbose", no_argument, nullptr, 'v'}, + {"daemonize", no_argument, nullptr, 'd'}, + {"service", no_argument, nullptr, 's'}, + {"peer-discovery", no_argument, nullptr, 'D'}, + {"no-rate-limit", no_argument, nullptr, 'U'}, + {"public-stable", no_argument, nullptr, 'P'}, + {"persist", required_argument, nullptr, 'f'}, + {"logfile", required_argument, nullptr, 'l'}, + {"syslog", no_argument, nullptr, 'L'}, + {"proxyserver", required_argument, nullptr, 'S'}, + {"proxyserverssl", required_argument, nullptr, 'e'}, + {"proxy-addr", required_argument, nullptr, 'a'}, + {"proxy-certificate", required_argument, nullptr, 'w'}, + {"proxy-privkey", required_argument, nullptr, 'K'}, + {"proxy-privkey-password", required_argument, nullptr, 'M'}, + {"proxyclient", required_argument, nullptr, 'C'}, + {"pushserver", required_argument, nullptr, 'y'}, + {"devicekey", required_argument, nullptr, 'z'}, + {"bundleid", required_argument, nullptr, 'u'}, + {"version", no_argument, nullptr, 'V'}, + {nullptr, 0, nullptr, 0 } }; dht_params -parseArgs(int argc, char **argv) { +parseArgs(int argc, char** argv) +{ dht_params params; int opt; std::string privkey; @@ -261,29 +257,26 @@ parseArgs(int argc, char **argv) { while ((opt = getopt_long(argc, argv, "hidsvODUPp:n:b:f:l:", long_options, nullptr)) != -1) { switch (opt) { case 'p': { - int port_arg = atoi(optarg); - if (port_arg >= 0 && port_arg < 0x10000) - params.port = port_arg; - else - std::cout << "Invalid port: " << port_arg << std::endl; - } - break; + int port_arg = atoi(optarg); + if (port_arg >= 0 && port_arg < 0x10000) + params.port = port_arg; + else + std::cout << "Invalid port: " << port_arg << std::endl; + } break; case 'S': { - int port_arg = atoi(optarg); - if (port_arg >= 0 && port_arg < 0x10000) - params.proxyserver = port_arg; - else - std::cout << "Invalid port: " << port_arg << std::endl; - } - break; + int port_arg = atoi(optarg); + if (port_arg >= 0 && port_arg < 0x10000) + params.proxyserver = port_arg; + else + std::cout << "Invalid port: " << port_arg << std::endl; + } break; case 'e': { - int port_arg = atoi(optarg); - if (port_arg >= 0 && port_arg < 0x10000) - params.proxyserverssl = port_arg; - else - std::cout << "Invalid port: " << port_arg << std::endl; - } - break; + int port_arg = atoi(optarg); + if (port_arg >= 0 && port_arg < 0x10000) + params.proxyserverssl = port_arg; + else + std::cout << "Invalid port: " << port_arg << std::endl; + } break; case 'D': params.peer_discovery = true; break; @@ -312,7 +305,7 @@ parseArgs(int argc, char **argv) { params.public_stable = true; break; case 'b': - params.bootstrap = (optarg[0] == '=') ? optarg+1 : optarg; + params.bootstrap = (optarg[0] == '=') ? optarg + 1 : optarg; break; case 'V': params.version = true; @@ -379,8 +372,7 @@ parseArgs(int argc, char **argv) { } if (not privkey.empty()) { try { - params.id.first = std::make_shared(loadFile(privkey), - params.privkey_pwd); + params.id.first = std::make_shared(loadFile(privkey), params.privkey_pwd); } catch (const std::exception& e) { throw std::runtime_error(std::string("Error loading private key: ") + e.what()); } @@ -411,21 +403,25 @@ readLine(const char* prefix = PROMPT) #else char line_read[512]; std::cout << PROMPT; - fgets(line_read, 512 , stdin); + fgets(line_read, 512, stdin); #endif return line_read ? std::string(line_read) : std::string("\0", 1); } -struct ServiceRunner { - bool wait() { +struct ServiceRunner +{ + bool wait() + { std::unique_lock lock(m); - cv.wait(lock, [&]{return terminate.load();}); + cv.wait(lock, [&] { return terminate.load(); }); return !terminate; } - void kill() { + void kill() + { terminate = true; cv.notify_all(); } + private: std::condition_variable cv; std::mutex m; @@ -435,9 +431,10 @@ private: ServiceRunner runner; #ifndef DISABLE_SIGNALS -void signal_handler(int sig) +void +signal_handler(int sig) { - switch(sig) { + switch (sig) { case SIGHUP: break; case SIGINT: @@ -450,25 +447,29 @@ void signal_handler(int sig) } #endif -void setupSignals() +void +setupSignals() { #ifndef DISABLE_SIGNALS - signal(SIGCHLD,SIG_IGN); /* ignore child */ - signal(SIGTSTP,SIG_IGN); /* ignore tty signals */ - signal(SIGTTOU,SIG_IGN); - signal(SIGTTIN,SIG_IGN); - signal(SIGHUP,signal_handler); /* catch hangup signal */ - signal(SIGINT,signal_handler); /* catch interrupt signal */ - signal(SIGTERM,signal_handler); /* catch kill signal */ + signal(SIGCHLD, SIG_IGN); /* ignore child */ + signal(SIGTSTP, SIG_IGN); /* ignore tty signals */ + signal(SIGTTOU, SIG_IGN); + signal(SIGTTIN, SIG_IGN); + signal(SIGHUP, signal_handler); /* catch hangup signal */ + signal(SIGINT, signal_handler); /* catch interrupt signal */ + signal(SIGTERM, signal_handler); /* catch kill signal */ #endif } -void daemonize() +void +daemonize() { #ifndef DISABLE_SIGNALS pid_t pid = fork(); - if (pid < 0) exit(EXIT_FAILURE); - if (pid > 0) exit(EXIT_SUCCESS); + if (pid < 0) + exit(EXIT_FAILURE); + if (pid > 0) + exit(EXIT_SUCCESS); umask(0); diff --git a/vcpkg.json b/vcpkg.json index ba37d625..809b248d 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -4,7 +4,7 @@ "port-version": 1, "description": "OpenDHT: A lightweight C++17 Distributed Hash Table library.", "homepage": "https://opendht.net", - "license": "GPL-3.0-or-later", + "license": "MIT", "dependencies": [ { "name": "vcpkg-cmake",