pax_global_header00006660000000000000000000000064122015202020014474gustar00rootroot0000000000000052 comment=f6223debed37cd3e95a30a2d2942a9ea921dd0a9 zurl-1.0.0/000077500000000000000000000000001220152020200124665ustar00rootroot00000000000000zurl-1.0.0/.gitignore000066400000000000000000000001361220152020200144560ustar00rootroot00000000000000*.swp *~ qrc_* *.moc *.o *.pdb ui_* moc_* *.pyc /Makefile conf.log conf.pri zurl src/Makefile zurl-1.0.0/.gitmodules000066400000000000000000000002511220152020200146410ustar00rootroot00000000000000[submodule "src/qzmq"] path = src/qzmq url = git://github.com/jkarneges/qzmq.git [submodule "src/common"] path = src/common url = git://github.com/fanout/common.git zurl-1.0.0/COPYING000066400000000000000000001047211220152020200135260ustar00rootroot00000000000000 This program is released under the GPL with the additional exemption that compiling, linking, and/or using OpenSSL is allowed. 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 . zurl-1.0.0/README000066400000000000000000000016501220152020200133500ustar00rootroot00000000000000Zurl 1.0.0 ---------- Date: August 10th, 2013 Author: Justin Karneges Mailing List: http://lists.fanout.io/listinfo.cgi/fanout-users-fanout.io HTTP client worker with ZeroMQ interface, written in Qt/C++. License: - Zurl is offered under the GNU GPL. See the COPYING file. Features: - Request HTTP and HTTPS URLs - Completely event-driven, using JDNS and Libcurl - Handle thousands of simultaneous outbound connections - Two access methods: REQ and PUSH/SUB (think Mongrel2 in reverse!) - Streaming requests and responses - Packet format uses TNetStrings - Set access policies (e.g. block requests to 10.*) Requirements: qt >= 4.7 libzmq >= 2.0 libcurl >= 7.20 If accessing from Git, be sure to pull submodules: git submodule init git submodule update Build: ./configure make Run: ./zurl --verbose --config=zurl.conf.example Test: python tools/get.py http://fanout.io/ zurl-1.0.0/configure000077500000000000000000000714201220152020200144010ustar00rootroot00000000000000#!/bin/sh # # Generated by qconf 1.5 ( http://delta.affinix.com/qconf/ ) # show_usage() { cat </dev/null` if echo $WHICH | grep 'shell built-in command' >/dev/null 2>&1; then WHICH=which elif [ -z "$WHICH" ]; then if which which >/dev/null 2>&1; then WHICH=which else for a in /usr/ucb /usr/bin /bin /usr/local/bin; do if [ -x $a/which ]; then WHICH=$a/which break; fi done fi fi if [ -z "$WHICH" ]; then OLD_IFS=$IFS IFS=: for a in $PATH; do if [ -x $a/$1 ]; then echo "$a/$1" IFS=$OLD_IFS export IFS HOME=$OLD_HOME export HOME return 0 fi done IFS=$OLD_IFS export IFS else a=`"$WHICH" "$1" 2>/dev/null` if [ ! -z "$a" -a -x "$a" ]; then echo "$a" HOME=$OLD_HOME export HOME return 0 fi fi HOME=$OLD_HOME export HOME return 1 } WHICH=which_command # find a make command if [ -z "$MAKE" ]; then MAKE= for mk in gmake make; do if $WHICH $mk >/dev/null 2>&1; then MAKE=`$WHICH $mk` break fi done if [ -z "$MAKE" ]; then echo "You don't seem to have 'make' or 'gmake' in your PATH." echo "Cannot proceed." exit 1 fi fi show_qt_info() { printf "Be sure you have a proper Qt 4.0 build environment set up. This means not\n" printf "just Qt, but also a C++ compiler, a make tool, and any other packages\n" printf "necessary for compiling C++ programs.\n" printf "\n" printf "If you are certain everything is installed, then it could be that Qt 4 is not\n" printf "being recognized or that a different version of Qt is being detected by\n" printf "mistake (for example, this could happen if \$QTDIR is pointing to a Qt 3\n" printf "installation). At least one of the following conditions must be satisfied:\n" printf "\n" printf " 1) --qtdir is set to the location of Qt\n" printf " 2) \$QTDIR is set to the location of Qt\n" printf " 3) QtCore is in the pkg-config database\n" printf " 4) qmake is in the \$PATH\n" printf "\n" printf "This script will use the first one it finds to be true, checked in the above\n" printf "order. #3 and #4 are the recommended options. #1 and #2 are mainly for\n" printf "overriding the system configuration.\n" printf "\n" } while [ $# -gt 0 ]; do optarg=`expr "x$1" : 'x[^=]*=\(.*\)'` case "$1" in --prefix=*) PREFIX=$optarg shift ;; --bindir=*) BINDIR=$optarg shift ;; --qtdir=*) EX_QTDIR=$optarg shift ;; --verbose) QC_VERBOSE="Y" shift ;; --help) show_usage; exit ;; *) show_usage; exit ;; esac done PREFIX=${PREFIX:-/usr/local} BINDIR=${BINDIR:-$PREFIX/bin} echo "Configuring Zurl ..." if [ "$QC_VERBOSE" = "Y" ]; then echo echo PREFIX=$PREFIX echo BINDIR=$BINDIR echo EX_QTDIR=$EX_QTDIR echo fi printf "Verifying Qt 4 build environment ... " # run qmake -v and check version qmake_check_v4() { if [ -x "$1" ]; then if echo `$1 -v 2>&1` | grep "Qt version 4\." >/dev/null 2>&1; then return 0 elif [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: $1 not for Qt 4" fi fi return 1 } if [ "$QC_VERBOSE" = "Y" ]; then echo fi qm="" names="qmake-qt4 qmake4 qmake" # qt4 check: --qtdir if [ -z "$qm" ] && [ ! -z "$EX_QTDIR" ]; then for n in $names; do qstr=$EX_QTDIR/bin/$n if qmake_check_v4 "$qstr"; then qm=$qstr break; fi done fi if [ -z "$qm" ] && [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: qmake not found via --qtdir" fi # qt4 check: QTDIR if [ -z "$qm" ] && [ ! -z "$QTDIR" ]; then for n in $names; do qstr=$QTDIR/bin/$n if qmake_check_v4 "$qstr"; then qm=$qstr break; fi done fi if [ -z "$qm" ] && [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: qmake not found via \$QTDIR" fi # qt4 check: pkg-config if [ -z "$qm" ]; then str=`pkg-config QtCore --variable=exec_prefix 2>/dev/null` if [ ! -z "$str" ]; then for n in $names; do qstr=$str/bin/$n if qmake_check_v4 "$qstr"; then qm=$qstr break; fi done fi fi if [ -z "$qm" ] && [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: qmake not found via pkg-config" fi # qt4 check: PATH if [ -z "$qm" ]; then for n in $names; do qstr=`$WHICH $n 2>/dev/null` if qmake_check_v4 "$qstr"; then qm=$qstr break; fi done fi if [ -z "$qm" ] && [ "$QC_VERBOSE" = "Y" ]; then echo "Warning: qmake not found via \$PATH" fi if [ -z "$qm" ]; then if [ "$QC_VERBOSE" = "Y" ]; then echo " -> fail" else echo "fail" fi printf "\n" printf "Reason: Unable to find the 'qmake' tool for Qt 4.\n" printf "\n" show_qt_info exit 1; fi if [ "$QC_VERBOSE" = "Y" ]; then echo qmake found in $qm fi # try to determine the active makespec defmakespec=$QMAKESPEC if [ -z "$defmakespec" ]; then if $WHICH readlink >/dev/null 2>&1; then READLINK=`$WHICH readlink` fi if [ ! -z "$READLINK" ]; then qt_mkspecsdir=`$qm -query QT_INSTALL_DATA`/mkspecs if [ -d "$qt_mkspecsdir" ] && [ -h "$qt_mkspecsdir/default" ]; then defmakespec=`$READLINK $qt_mkspecsdir/default` fi fi fi if [ "$QC_VERBOSE" = "Y" ]; then echo makespec is $defmakespec fi qm_spec="" # if the makespec is macx-xcode, force macx-g++ if [ "$defmakespec" = "macx-xcode" ]; then qm_spec=macx-g++ QMAKESPEC=$qm_spec export QMAKESPEC if [ "$QC_VERBOSE" = "Y" ]; then echo overriding makespec to $qm_spec fi fi gen_files() { cat >$1/modules.cpp <= 4.7.0 -----END QCMOD----- */ class qc_qt47 : public ConfObj { public: qc_qt47(Conf *c) : ConfObj(c) {} QString name() const { return "Qt >= 4.7.0"; } QString shortname() const { return "qt47"; } bool exec() { return(QT_VERSION >= 0x040700); } }; EOT cat >$1/modules_new.cpp <required = true; o->disabled = false; o = new qc_internal_pkgconfig(conf, "libcurl", "libcurl >= 7.19", VersionMin, "7.19"); o->required = true; o->disabled = false; o = new qc_internal_pkgconfig(conf, "libzmq", "libzmq >= 2.0", VersionMin, "2.0"); o->required = true; o->disabled = false; EOT cat >$1/conf4.h < class Conf; enum VersionMode { VersionMin, VersionExact, VersionMax, VersionAny }; // ConfObj // // Subclass ConfObj to create a new configuration module. class ConfObj { public: Conf *conf; bool required; bool disabled; bool success; ConfObj(Conf *c); virtual ~ConfObj(); // long or descriptive name of what is being checked/performed // example: "KDE >= 3.3" virtual QString name() const = 0; // short name // example: "kde" virtual QString shortname() const = 0; // string to display during check // default: "Checking for [name] ..." virtual QString checkString() const; // string to display after check // default: "yes" or "no", based on result of exec() virtual QString resultString() const; // this is where the checking code goes virtual bool exec() = 0; }; // Conf // // Interact with this class from your ConfObj to perform detection // operations and to output configuration parameters. class Conf { public: bool debug_enabled; QString qmake_path; QString qmakespec; QString maketool; QString DEFINES; QString INCLUDEPATH; QString LIBS; QString extra; QList list; QMap vars; Conf(); ~Conf(); QString getenv(const QString &var); QString qvar(const QString &s); bool exec(); void debug(const QString &s); QString expandIncludes(const QString &inc); QString expandLibs(const QString &lib); int doCommand(const QString &s, QByteArray *out = 0); int doCommand(const QString &prog, const QStringList &args, QByteArray *out = 0); bool doCompileAndLink(const QString &filedata, const QStringList &incs, const QString &libs, const QString &proextra, int *retcode = 0); bool checkHeader(const QString &path, const QString &h); bool findHeader(const QString &h, const QStringList &ext, QString *inc); bool checkLibrary(const QString &path, const QString &name); bool findLibrary(const QString &name, QString *lib); QString findProgram(const QString &prog); bool findSimpleLibrary(const QString &incvar, const QString &libvar, const QString &incname, const QString &libname, QString *incpath, QString *libs); bool findFooConfig(const QString &path, QString *version, QStringList *incs, QString *libs, QString *otherflags); bool findPkgConfig(const QString &name, VersionMode mode, const QString &req_version, QString *version, QStringList *incs, QString *libs, QString *otherflags); void addDefine(const QString &str); void addLib(const QString &str); void addIncludePath(const QString &str); void addExtra(const QString &str); private: bool first_debug; friend class ConfObj; void added(ConfObj *o); }; #endif EOT cat >$1/conf4.cpp < #include class MocTestObject : public QObject { Q_OBJECT public: MocTestObject() {} }; QString qc_getenv(const QString &var) { char *p = ::getenv(var.toLatin1().data()); if(!p) return QString(); return QString(p); } QStringList qc_pathlist() { QStringList list; QString path = qc_getenv("PATH"); if(!path.isEmpty()) { #ifdef Q_OS_WIN list = path.split(';', QString::SkipEmptyParts); #else list = path.split(':', QString::SkipEmptyParts); #endif } #ifdef Q_OS_WIN list.prepend("."); #endif return list; } QString qc_findprogram(const QString &prog) { QString out; QStringList list = qc_pathlist(); for(int n = 0; n < list.count(); ++n) { QFileInfo fi(list[n] + '/' + prog); if(fi.exists() && fi.isExecutable()) { out = fi.filePath(); break; } #ifdef Q_OS_WIN // on windows, be sure to look for .exe if(prog.right(4).toLower() != ".exe") { fi = QFileInfo(list[n] + '/' + prog + ".exe"); if(fi.exists() && fi.isExecutable()) { out = fi.filePath(); break; } } #endif } return out; } QString qc_findself(const QString &argv0) { #ifdef Q_OS_WIN if(argv0.contains('\\\\')) #else if(argv0.contains('/')) #endif return argv0; else return qc_findprogram(argv0); } int qc_run_program_or_command(const QString &prog, const QStringList &args, const QString &command, QByteArray *out, bool showOutput) { if(out) out->clear(); QProcess process; process.setReadChannel(QProcess::StandardOutput); if(!prog.isEmpty()) process.start(prog, args); else if(!command.isEmpty()) process.start(command); else return -1; if(!process.waitForStarted(-1)) return -1; QByteArray buf; while(process.waitForReadyRead(-1)) { buf = process.readAllStandardOutput(); if(out) out->append(buf); if(showOutput) fprintf(stdout, "%s", buf.data()); buf = process.readAllStandardError(); if(showOutput) fprintf(stderr, "%s", buf.data()); } buf = process.readAllStandardError(); if(showOutput) fprintf(stderr, "%s", buf.data()); // calling waitForReadyRead will cause the process to eventually be // marked as finished, so we should not need to separately call // waitForFinished. however, we will do it anyway just to be safe. // we won't check the return value since false could still mean // success (if the process had already been marked as finished). process.waitForFinished(-1); if(process.exitStatus() != QProcess::NormalExit) return -1; return process.exitCode(); } int qc_runcommand(const QString &command, QByteArray *out, bool showOutput) { return qc_run_program_or_command(QString(), QStringList(), command, out, showOutput); } int qc_runprogram(const QString &prog, const QStringList &args, QByteArray *out, bool showOutput) { return qc_run_program_or_command(prog, args, QString(), out, showOutput); } bool qc_removedir(const QString &dirPath) { QDir dir(dirPath); if(!dir.exists()) return false; QStringList list = dir.entryList(); foreach(QString s, list) { if(s == "." || s == "..") continue; QFileInfo fi(dir.filePath(s)); if(fi.isDir()) { if(!qc_removedir(fi.filePath())) return false; } else { if(!dir.remove(s)) return false; } } QString dirName = dir.dirName(); if(!dir.cdUp()) return false; if(!dir.rmdir(dirName)) return false; return true; } void qc_splitcflags(const QString &cflags, QStringList *incs, QStringList *otherflags) { incs->clear(); otherflags->clear(); QStringList cflagsList = cflags.split(" "); for(int n = 0; n < cflagsList.count(); ++n) { QString str = cflagsList[n]; if(str.startsWith("-I")) { // we want everything except the leading "-I" incs->append(str.remove(0, 2)); } else { // we want whatever is left otherflags->append(str); } } } QString qc_escapeArg(const QString &str) { QString out; for(int n = 0; n < (int)str.length(); ++n) { if(str[n] == '-') out += '_'; else out += str[n]; } return out; } //---------------------------------------------------------------------------- // ConfObj //---------------------------------------------------------------------------- ConfObj::ConfObj(Conf *c) { conf = c; conf->added(this); required = false; disabled = false; success = false; } ConfObj::~ConfObj() { } QString ConfObj::checkString() const { return QString("Checking for %1 ...").arg(name()); } QString ConfObj::resultString() const { if(success) return "yes"; else return "no"; } //---------------------------------------------------------------------------- // qc_internal_pkgconfig //---------------------------------------------------------------------------- class qc_internal_pkgconfig : public ConfObj { public: QString pkgname, desc; VersionMode mode; QString req_ver; qc_internal_pkgconfig(Conf *c, const QString &_name, const QString &_desc, VersionMode _mode, const QString &_req_ver) : ConfObj(c) { pkgname = _name; desc = _desc; mode = _mode; req_ver = _req_ver; } QString name() const { return desc; } QString shortname() const { return pkgname; } bool exec() { QStringList incs; QString version, libs, other; if(!conf->findPkgConfig(pkgname, mode, req_ver, &version, &incs, &libs, &other)) return false; for(int n = 0; n < incs.count(); ++n) conf->addIncludePath(incs[n]); if(!libs.isEmpty()) conf->addLib(libs); //if(!other.isEmpty()) // conf->addExtra(QString("QMAKE_CFLAGS += %1\n").arg(other)); return true; } }; //---------------------------------------------------------------------------- // Conf //---------------------------------------------------------------------------- Conf::Conf() { // TODO: no more vars? //vars.insert("QMAKE_INCDIR_X11", new QString(X11_INC)); //vars.insert("QMAKE_LIBDIR_X11", new QString(X11_LIBDIR)); //vars.insert("QMAKE_LIBS_X11", new QString(X11_LIB)); //vars.insert("QMAKE_CC", CC); debug_enabled = false; } Conf::~Conf() { qDeleteAll(list); } void Conf::added(ConfObj *o) { list.append(o); } QString Conf::getenv(const QString &var) { return qc_getenv(var); } void Conf::debug(const QString &s) { if(debug_enabled) { if(first_debug) printf("\n"); first_debug = false; printf(" * %s\n", qPrintable(s)); } } bool Conf::exec() { for(int n = 0; n < list.count(); ++n) { ConfObj *o = list[n]; // if this was a disabled-by-default option, check if it was enabled if(o->disabled) { QString v = QString("QC_ENABLE_") + qc_escapeArg(o->shortname()); if(getenv(v) != "Y") continue; } // and the opposite? else { QString v = QString("QC_DISABLE_") + qc_escapeArg(o->shortname()); if(getenv(v) == "Y") continue; } bool output = true; QString check = o->checkString(); if(check.isEmpty()) output = false; if(output) { printf("%s", check.toLatin1().data()); fflush(stdout); } first_debug = true; bool ok = o->exec(); o->success = ok; if(output) { QString result = o->resultString(); if(!first_debug) printf(" -> %s\n", result.toLatin1().data()); else printf(" %s\n", result.toLatin1().data()); } if(!ok && o->required) { printf("\nError: need %s!\n", o->name().toLatin1().data()); return false; } } return true; } QString Conf::qvar(const QString &s) { return vars.value(s); } QString Conf::expandIncludes(const QString &inc) { return QString("-I") + inc; } QString Conf::expandLibs(const QString &lib) { return QString("-L") + lib; } int Conf::doCommand(const QString &s, QByteArray *out) { debug(QString("[%1]").arg(s)); int r = qc_runcommand(s, out, debug_enabled); debug(QString("returned: %1").arg(r)); return r; } int Conf::doCommand(const QString &prog, const QStringList &args, QByteArray *out) { QString fullcmd = prog; QString argstr = args.join(" "); if(!argstr.isEmpty()) fullcmd += QString(" ") + argstr; debug(QString("[%1]").arg(fullcmd)); int r = qc_runprogram(prog, args, out, debug_enabled); debug(QString("returned: %1").arg(r)); return r; } bool Conf::doCompileAndLink(const QString &filedata, const QStringList &incs, const QString &libs, const QString &proextra, int *retcode) { #ifdef Q_OS_WIN QDir tmp("qconftemp"); #else QDir tmp(".qconftemp"); #endif if(!tmp.mkdir("atest")) { debug("unable to create atest dir"); return false; } QDir dir(tmp.filePath("atest")); if(!dir.exists()) { debug("atest dir does not exist"); return false; } QString fname = dir.filePath("atest.cpp"); QString out = "atest"; QFile f(fname); if(!f.open(QFile::WriteOnly | QFile::Truncate)) { debug("unable to open atest.cpp for writing"); return false; } if(f.write(filedata.toLatin1()) == -1) { debug("error writing to atest.cpp"); return false; } f.close(); debug(QString("Wrote atest.cpp:\n%1").arg(filedata)); QString pro = QString( "CONFIG += console\n" "CONFIG -= qt app_bundle\n" "DESTDIR = \$\$PWD\n" "SOURCES += atest.cpp\n"); QString inc = incs.join(" "); if(!inc.isEmpty()) pro += "INCLUDEPATH += " + inc + '\n'; if(!libs.isEmpty()) pro += "LIBS += " + libs + '\n'; pro += proextra; fname = dir.filePath("atest.pro"); f.setFileName(fname); if(!f.open(QFile::WriteOnly | QFile::Truncate)) { debug("unable to open atest.pro for writing"); return false; } if(f.write(pro.toLatin1()) == -1) { debug("error writing to atest.pro"); return false; } f.close(); debug(QString("Wrote atest.pro:\n%1").arg(pro)); QString oldpath = QDir::currentPath(); QDir::setCurrent(dir.path()); bool ok = false; int r = doCommand(qmake_path, QStringList() << "atest.pro"); if(r == 0) { r = doCommand(maketool, QStringList()); if(r == 0) { ok = true; if(retcode) { QString runatest = out; #ifdef Q_OS_UNIX runatest.prepend("./"); #endif *retcode = doCommand(runatest, QStringList()); } } r = doCommand(maketool, QStringList() << "distclean"); if(r != 0) debug("error during atest distclean"); } QDir::setCurrent(oldpath); // cleanup //dir.remove("atest.pro"); //dir.remove("atest.cpp"); //tmp.rmdir("atest"); // remove whole dir since distclean doesn't always work qc_removedir(tmp.filePath("atest")); if(!ok) return false; return true; } bool Conf::checkHeader(const QString &path, const QString &h) { QFileInfo fi(path + '/' + h); if(fi.exists()) return true; return false; } bool Conf::findHeader(const QString &h, const QStringList &ext, QString *inc) { if(checkHeader("/usr/include", h)) { *inc = ""; return true; } QStringList dirs; dirs += "/usr/local/include"; dirs += ext; for(QStringList::ConstIterator it = dirs.begin(); it != dirs.end(); ++it) { if(checkHeader(*it, h)) { *inc = *it; return true; } } return false; } bool Conf::checkLibrary(const QString &path, const QString &name) { QString str = //"#include \n" "int main()\n" "{\n" //" printf(\"library checker running\\\\n\");\n" " return 0;\n" "}\n"; QString libs; if(!path.isEmpty()) libs += QString("-L") + path + ' '; libs += QString("-l") + name; if(!doCompileAndLink(str, QStringList(), libs, QString())) return false; return true; } bool Conf::findLibrary(const QString &name, QString *lib) { if(checkLibrary("", name)) { *lib = ""; return true; } if(checkLibrary("/usr/local/lib", name)) { *lib = "/usr/local/lib"; return true; } return false; } QString Conf::findProgram(const QString &prog) { return qc_findprogram(prog); } bool Conf::findSimpleLibrary(const QString &incvar, const QString &libvar, const QString &incname, const QString &libname, QString *incpath, QString *libs) { QString inc, lib; QString s; s = getenv(incvar); if(!s.isEmpty()) { if(!checkHeader(s, incname)) return false; inc = s; } else { if(!findHeader(incname, QStringList(), &s)) return false; inc = s; } s = getenv(libvar); if(!s.isEmpty()) { if(!checkLibrary(s, libname)) return false; lib = s; } else { if(!findLibrary(libname, &s)) return false; lib = s; } QString lib_out; if(!lib.isEmpty()) lib_out += QString("-L") + s; lib_out += QString("-l") + libname; *incpath = inc; *libs = lib_out; return true; } bool Conf::findFooConfig(const QString &path, QString *version, QStringList *incs, QString *libs, QString *otherflags) { QStringList args; QByteArray out; int ret; args += "--version"; ret = doCommand(path, args, &out); if(ret != 0) return false; QString version_out = QString::fromLatin1(out).trimmed(); args.clear(); args += "--libs"; ret = doCommand(path, args, &out); if(ret != 0) return false; QString libs_out = QString::fromLatin1(out).trimmed(); args.clear(); args += "--cflags"; ret = doCommand(path, args, &out); if(ret != 0) return false; QString cflags = QString::fromLatin1(out).trimmed(); QStringList incs_out, otherflags_out; qc_splitcflags(cflags, &incs_out, &otherflags_out); *version = version_out; *incs = incs_out; *libs = libs_out; *otherflags = otherflags_out.join(" "); return true; } bool Conf::findPkgConfig(const QString &name, VersionMode mode, const QString &req_version, QString *version, QStringList *incs, QString *libs, QString *otherflags) { QStringList args; QByteArray out; int ret; args += name; args += "--exists"; ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; if(mode != VersionAny) { args.clear(); args += name; if(mode == VersionMin) args += QString("--atleast-version=%1").arg(req_version); else if(mode == VersionMax) args += QString("--max-version=%1").arg(req_version); else args += QString("--exact-version=%1").arg(req_version); ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; } args.clear(); args += name; args += "--modversion"; ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; QString version_out = QString::fromLatin1(out).trimmed(); args.clear(); args += name; args += "--libs"; ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; QString libs_out = QString::fromLatin1(out).trimmed(); args.clear(); args += name; args += "--cflags"; ret = doCommand("pkg-config", args, &out); if(ret != 0) return false; QString cflags = QString::fromLatin1(out).trimmed(); QStringList incs_out, otherflags_out; qc_splitcflags(cflags, &incs_out, &otherflags_out); *version = version_out; *incs = incs_out; *libs = libs_out; *otherflags = otherflags_out.join(" "); return true; } void Conf::addDefine(const QString &str) { if(DEFINES.isEmpty()) DEFINES = str; else DEFINES += QString(" ") + str; debug(QString("DEFINES += %1").arg(str)); } void Conf::addLib(const QString &str) { if(LIBS.isEmpty()) LIBS = str; else LIBS += QString(" ") + str; debug(QString("LIBS += %1").arg(str)); } void Conf::addIncludePath(const QString &str) { if(INCLUDEPATH.isEmpty()) INCLUDEPATH = str; else INCLUDEPATH += QString(" ") + str; debug(QString("INCLUDEPATH += %1").arg(str)); } void Conf::addExtra(const QString &str) { extra += str + '\n'; debug(QString("extra += %1").arg(str)); } //---------------------------------------------------------------------------- // main //---------------------------------------------------------------------------- #include "conf4.moc" #ifdef HAVE_MODULES # include"modules.cpp" #endif int main() { Conf *conf = new Conf; ConfObj *o = 0; Q_UNUSED(o); #ifdef HAVE_MODULES # include"modules_new.cpp" #endif conf->debug_enabled = (qc_getenv("QC_VERBOSE") == "Y") ? true: false; if(conf->debug_enabled) printf(" -> ok\n"); else printf("ok\n"); QString confCommand = qc_getenv("QC_COMMAND"); QString proName = qc_getenv("QC_PROFILE"); conf->qmake_path = qc_getenv("QC_QMAKE"); conf->qmakespec = qc_getenv("QC_QMAKESPEC"); conf->maketool = qc_getenv("QC_MAKETOOL"); if(conf->debug_enabled) printf("conf command: [%s]\n", qPrintable(confCommand)); QString confPath = qc_findself(confCommand); if(confPath.isEmpty()) { printf("Error: cannot find myself; rerun with an absolute path\n"); return 1; } QString srcdir = QFileInfo(confPath).absolutePath(); QString builddir = QDir::current().absolutePath(); QString proPath = QDir(srcdir).filePath(proName); if(conf->debug_enabled) { printf("conf path: [%s]\n", qPrintable(confPath)); printf("srcdir: [%s]\n", qPrintable(srcdir)); printf("builddir: [%s]\n", qPrintable(builddir)); printf("profile: [%s]\n", qPrintable(proPath)); printf("qmake path: [%s]\n", qPrintable(conf->qmake_path)); printf("qmakespec: [%s]\n", qPrintable(conf->qmakespec)); printf("make tool: [%s]\n", qPrintable(conf->maketool)); printf("\n"); } bool success = false; if(conf->exec()) { QFile f("conf.pri"); if(!f.open(QFile::WriteOnly | QFile::Truncate)) { printf("Error writing %s\n", qPrintable(f.fileName())); return 1; } QString str; str += "# qconf\n\n"; QString var; var = qc_getenv("PREFIX"); if(!var.isEmpty()) str += QString("PREFIX = %1\n").arg(var); var = qc_getenv("BINDIR"); if(!var.isEmpty()) str += QString("BINDIR = %1\n").arg(var); var = qc_getenv("INCDIR"); if(!var.isEmpty()) str += QString("INCDIR = %1\n").arg(var); var = qc_getenv("LIBDIR"); if(!var.isEmpty()) str += QString("LIBDIR = %1\n").arg(var); var = qc_getenv("DATADIR"); if(!var.isEmpty()) str += QString("DATADIR = %1\n").arg(var); str += '\n'; if(qc_getenv("QC_STATIC") == "Y") str += "CONFIG += staticlib\n"; // TODO: don't need this? //str += "QT_PATH_PLUGINS = " + QString(qInstallPathPlugins()) + '\n'; if(!conf->DEFINES.isEmpty()) str += "DEFINES += " + conf->DEFINES + '\n'; if(!conf->INCLUDEPATH.isEmpty()) str += "INCLUDEPATH += " + conf->INCLUDEPATH + '\n'; if(!conf->LIBS.isEmpty()) str += "LIBS += " + conf->LIBS + '\n'; if(!conf->extra.isEmpty()) str += conf->extra; str += '\n'; QByteArray cs = str.toLatin1(); f.write(cs); f.close(); success = true; } QString qmake_path = conf->qmake_path; QString qmakespec = conf->qmakespec; delete conf; if(!success) return 1; // run qmake on the project file QStringList args; if(!qmakespec.isEmpty()) { args += "-spec"; args += qmakespec; } args += proPath; int ret = qc_runprogram(qmake_path, args, 0, true); if(ret != 0) return 1; return 0; } EOT cat >$1/conf4.pro </dev/null else $qm conf4.pro >/dev/null fi $MAKE clean >/dev/null 2>&1 $MAKE >../conf.log 2>&1 ) if [ "$?" != "0" ]; then rm -rf .qconftemp if [ "$QC_VERBOSE" = "Y" ]; then echo " -> fail" else echo "fail" fi printf "\n" printf "Reason: There was an error compiling 'conf'. See conf.log for details.\n" printf "\n" show_qt_info if [ "$QC_VERBOSE" = "Y" ]; then echo "conf.log:" cat conf.log fi exit 1; fi QC_COMMAND=$0 export QC_COMMAND QC_PROFILE=zurl.pro export QC_PROFILE QC_QMAKE=$qm export QC_QMAKE QC_QMAKESPEC=$qm_spec export QC_QMAKESPEC QC_MAKETOOL=$MAKE export QC_MAKETOOL .qconftemp/conf ret="$?" if [ "$ret" = "1" ]; then rm -rf .qconftemp echo exit 1; else if [ "$ret" != "0" ]; then rm -rf .qconftemp if [ "$QC_VERBOSE" = "Y" ]; then echo " -> fail" else echo "fail" fi echo echo "Reason: Unexpected error launching 'conf'" echo exit 1; fi fi rm -rf .qconftemp echo echo "Good, your configure finished. Now run $MAKE." echo zurl-1.0.0/qcm/000077500000000000000000000000001220152020200132465ustar00rootroot00000000000000zurl-1.0.0/qcm/qt47.qcm000066400000000000000000000004431220152020200145500ustar00rootroot00000000000000/* -----BEGIN QCMOD----- name: Qt >= 4.7.0 -----END QCMOD----- */ class qc_qt47 : public ConfObj { public: qc_qt47(Conf *c) : ConfObj(c) {} QString name() const { return "Qt >= 4.7.0"; } QString shortname() const { return "qt47"; } bool exec() { return(QT_VERSION >= 0x040700); } }; zurl-1.0.0/src/000077500000000000000000000000001220152020200132555ustar00rootroot00000000000000zurl-1.0.0/src/app.cpp000066400000000000000000000305661220152020200145530ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "app.h" #include #include #include #include #include #include #ifdef USE_QNAM #include #endif #include "jdnsshared.h" #include "qzmqsocket.h" #include "qzmqreqmessage.h" #include "qzmqvalve.h" #include "processquit.h" #include "tnetstring.h" #include "zhttpresponsepacket.h" #include "appconfig.h" #include "log.h" #include "worker.h" #define VERSION "1.0.0" static void cleanStringList(QStringList *in) { for(int n = 0; n < in->count(); ++n) { if(in->at(n).isEmpty()) { in->removeAt(n); --n; // adjust position } } } class App::Private : public QObject { Q_OBJECT public: App *q; JDnsShared *dns; QZmq::Socket *in_sock; QZmq::Socket *in_stream_sock; QZmq::Socket *out_sock; QZmq::Socket *in_req_sock; QZmq::Valve *in_valve; QZmq::Valve *in_req_valve; AppConfig config; QSet workers; QHash streamWorkersByRid; QHash > reqHeadersByWorker; Private(App *_q) : QObject(_q), q(_q), in_sock(0), in_stream_sock(0), out_sock(0), in_req_sock(0), in_valve(0), in_req_valve(0) { connect(ProcessQuit::instance(), SIGNAL(quit()), SLOT(doQuit())); } ~Private() { } void start() { #ifdef USE_QNAM if(!QCA::isSupported("cert")) { log_error("missing qca \"cert\" feature. install qca-ossl"); emit q->quit(); return; } #endif QStringList args = QCoreApplication::instance()->arguments(); args.removeFirst(); // options QHash options; for(int n = 0; n < args.count(); ++n) { if(args[n] == "--") { break; } else if(args[n].startsWith("--")) { QString opt = args[n].mid(2); QString var, val; int at = opt.indexOf("="); if(at != -1) { var = opt.mid(0, at); val = opt.mid(at + 1); } else var = opt; options[var] = val; args.removeAt(n); --n; // adjust position } } if(options.contains("version")) { printf("Zurl %s\n", VERSION); emit q->quit(); return; } if(options.contains("verbose")) log_setOutputLevel(LOG_LEVEL_DEBUG); else log_setOutputLevel(LOG_LEVEL_INFO); log_info("starting..."); QString configFile = options["config"]; if(configFile.isEmpty()) configFile = "/etc/zurl.conf"; // QSettings doesn't inform us if the config file doesn't exist, so do that ourselves { QFile file(configFile); if(!file.open(QIODevice::ReadOnly)) { log_error("failed to open %s, and --config not passed", qPrintable(configFile)); emit q->quit(); return; } } QSettings settings(configFile, QSettings::IniFormat); config.clientId = settings.value("instance_id").toString().toUtf8(); if(config.clientId.isEmpty()) config.clientId = QUuid::createUuid().toString().toLatin1(); QString in_url = settings.value("in_spec").toString(); QString in_stream_url = settings.value("in_stream_spec").toString(); QString out_url = settings.value("out_spec").toString(); QString in_req_url = settings.value("in_req_spec").toString(); config.maxWorkers = settings.value("max_open_requests", -1).toInt(); config.sessionBufferSize = settings.value("buffer_size", 200000).toInt(); config.sessionTimeout = settings.value("timeout", 600).toInt(); int inHwm = settings.value("in_hwm", 1000).toInt(); int outHwm = settings.value("out_hwm", 1000).toInt(); if((!in_url.isEmpty() || !in_stream_url.isEmpty() || !out_url.isEmpty()) && (in_url.isEmpty() || in_stream_url.isEmpty() || out_url.isEmpty())) { log_error("if any of in_spec, in_stream_spec, or out_spec are set then all of them must be set"); emit q->quit(); return; } if(in_url.isEmpty() && in_req_url.isEmpty()) { log_error("must set at least in_spec+in_stream_spec+out_spec or in_req_spec"); emit q->quit(); return; } config.defaultPolicy = settings.value("defpolicy").toString(); if(config.defaultPolicy != "allow" && config.defaultPolicy != "deny") { log_error("must set defpolicy to either \"allow\" or \"deny\""); emit q->quit(); return; } config.allowExps = settings.value("allow").toStringList(); config.denyExps = settings.value("deny").toStringList(); cleanStringList(&config.allowExps); cleanStringList(&config.denyExps); dns = new JDnsShared(JDnsShared::UnicastInternet, this); dns->addInterface(QHostAddress::Any); dns->addInterface(QHostAddress::AnyIPv6); if(!in_url.isEmpty()) { in_sock = new QZmq::Socket(QZmq::Socket::Pull, this); in_sock->setHwm(inHwm); if(!in_sock->bind(in_url)) { log_error("unable to bind to in_spec: %s", qPrintable(in_url)); emit q->quit(); return; } in_valve = new QZmq::Valve(in_sock, this); connect(in_valve, SIGNAL(readyRead(const QList &)), SLOT(in_readyRead(const QList &))); } if(!in_stream_url.isEmpty()) { in_stream_sock = new QZmq::Socket(QZmq::Socket::Dealer, this); in_stream_sock->setIdentity(config.clientId); in_stream_sock->setHwm(inHwm); connect(in_stream_sock, SIGNAL(readyRead()), SLOT(in_stream_readyRead())); if(!in_stream_sock->bind(in_stream_url)) { log_error("unable to bind to in_stream_spec: %s", qPrintable(in_stream_url)); emit q->quit(); return; } } if(!out_url.isEmpty()) { out_sock = new QZmq::Socket(QZmq::Socket::Pub, this); out_sock->setWriteQueueEnabled(false); out_sock->setHwm(outHwm); if(!out_sock->bind(out_url)) { log_error("unable to bind to out_spec: %s", qPrintable(out_url)); emit q->quit(); return; } } if(!in_req_url.isEmpty()) { in_req_sock = new QZmq::Socket(QZmq::Socket::Router, this); in_req_sock->setHwm(inHwm); if(!in_req_sock->bind(in_req_url)) { log_error("unable to bind to in_req_spec: %s", qPrintable(in_req_url)); emit q->quit(); return; } in_req_valve = new QZmq::Valve(in_req_sock, this); connect(in_req_valve, SIGNAL(readyRead(const QList &)), SLOT(in_req_readyRead(const QList &))); } if(in_valve) in_valve->open(); if(in_req_valve) in_req_valve->open(); log_info("started"); } // normally responses are handled by Workers, but in some routing // cases we need to be able to respond with an error at this layer void respondCancel(const QByteArray &receiver, const QByteArray &rid) { ZhttpResponsePacket out; out.id = rid; out.type = ZhttpResponsePacket::Cancel; QByteArray part = QByteArray("T") + TnetString::fromVariant(out.toVariant()); out_sock->write(QList() << (receiver + ' ' + part)); } private slots: void in_readyRead(const QList &message) { if(message.count() != 1) { log_warning("received message with parts != 1, skipping"); return; } if(message[0].length() < 1 || message[0][0] != 'T') { log_warning("received message with invalid format (wrong type), skipping"); return; } bool ok; QVariant data = TnetString::toVariant(message[0].mid(1), 0, &ok); if(!ok) { log_warning("received message with invalid format (tnetstring parse failed), skipping"); return; } log_debug("recv: %s", qPrintable(TnetString::variantToString(data, -1))); QVariantHash vhash = data.toHash(); QByteArray rid = vhash.value("id").toByteArray(); if(rid.isEmpty()) { log_warning("received stream message without request id, skipping"); return; } if(streamWorkersByRid.contains(rid)) { log_warning("received request for id already in use, skipping"); return; } Worker *w = new Worker(dns, &config, this); connect(w, SIGNAL(readyRead(const QByteArray &, const QVariant &)), SLOT(worker_readyRead(const QByteArray &, const QVariant &))); connect(w, SIGNAL(finished()), SLOT(worker_finished())); workers += w; streamWorkersByRid[rid] = w; if(config.maxWorkers != -1 && workers.count() >= config.maxWorkers) { in_valve->close(); // also close in_req_valve, if we have it if(in_req_valve) in_req_valve->close(); } w->start(data, Worker::Stream); } void in_stream_readyRead() { // message from DEALER socket will have two parts, with first part empty QList message = in_stream_sock->read(); if(message.count() != 2) { log_warning("received message with parts != 2, skipping"); return; } if(!message[0].isEmpty()) { log_warning("received message with non-empty first part, skipping"); return; } if(message[1].length() < 1 || message[1][0] != 'T') { log_warning("received message with invalid format (wrong type), skipping"); return; } bool ok; QVariant data = TnetString::toVariant(message[1].mid(1), 0, &ok); if(!ok) { log_warning("received message with invalid format (tnetstring parse failed), skipping"); return; } log_debug("recv-stream: %s", qPrintable(TnetString::variantToString(data, -1))); QVariantHash vhash = data.toHash(); QByteArray rid = vhash.value("id").toByteArray(); if(rid.isEmpty()) { log_warning("received stream message without request id, skipping"); return; } Worker *w = streamWorkersByRid.value(rid); if(!w) { QByteArray from = vhash.value("from").toByteArray(); QByteArray type = vhash.value("type").toByteArray(); if(!from.isEmpty() && type != "error" && type != "cancel") respondCancel(from, rid); return; } w->write(data); } void in_req_readyRead(const QList &message) { QZmq::ReqMessage reqMessage(message); if(reqMessage.content().count() != 1) { log_warning("received message with parts != 1, skipping"); return; } QByteArray msg = reqMessage.content()[0]; if(msg.length() < 1 || msg[0] != 'T') { log_warning("received message with invalid format (wrong type), skipping"); return; } bool ok; QVariant data = TnetString::toVariant(msg.mid(1), 0, &ok); if(!ok) { log_warning("received message with invalid format (tnetstring parse failed), skipping"); return; } log_debug("recv-req: %s", qPrintable(TnetString::variantToString(data, -1))); Worker *w = new Worker(dns, &config, this); connect(w, SIGNAL(readyRead(const QByteArray &, const QVariant &)), SLOT(worker_readyRead(const QByteArray &, const QVariant &))); connect(w, SIGNAL(finished()), SLOT(worker_finished())); workers += w; reqHeadersByWorker[w] = reqMessage.headers(); if(config.maxWorkers != -1 && workers.count() >= config.maxWorkers) { in_req_valve->close(); // also close in_valve, if we have it if(in_valve) in_valve->close(); } w->start(data, Worker::Single); } void worker_readyRead(const QByteArray &receiver, const QVariant &response) { Worker *w = (Worker *)sender(); QByteArray part = QByteArray("T") + TnetString::fromVariant(response); if(!receiver.isEmpty()) { log_debug("send: %s", qPrintable(TnetString::variantToString(response, -1))); out_sock->write(QList() << (receiver + ' ' + part)); } else { log_debug("send-req: %s", qPrintable(TnetString::variantToString(response, -1))); assert(reqHeadersByWorker.contains(w)); QList reqHeaders = reqHeadersByWorker.value(w); in_req_sock->write(QZmq::ReqMessage(reqHeaders, QList() << part).toRawMessage()); } } void worker_finished() { Worker *w = (Worker *)sender(); streamWorkersByRid.remove(w->rid()); reqHeadersByWorker.remove(w); workers.remove(w); delete w; // ensure the valves are open if(in_valve) in_valve->open(); if(in_req_valve) in_req_valve->open(); } void doQuit() { log_info("stopping..."); // remove the handler, so if we get another signal then we crash out ProcessQuit::cleanup(); log_info("stopped"); emit q->quit(); } }; App::App(QObject *parent) : QObject(parent) { d = new Private(this); } App::~App() { delete d; } void App::start() { d->start(); } #include "app.moc" zurl-1.0.0/src/app.h000066400000000000000000000016601220152020200142110ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef APP_H #define APP_H #include class App : public QObject { Q_OBJECT public: App(QObject *parent = 0); ~App(); void start(); signals: void quit(); private: class Private; friend class Private; Private *d; }; #endif zurl-1.0.0/src/appconfig.h000066400000000000000000000017011220152020200153730ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef APPCONFIG_H #define APPCONFIG_H #include #include class AppConfig { public: QByteArray clientId; QString defaultPolicy; QStringList allowExps, denyExps; int maxWorkers; int sessionBufferSize; int sessionTimeout; }; #endif zurl-1.0.0/src/common/000077500000000000000000000000001220152020200145455ustar00rootroot00000000000000zurl-1.0.0/src/httprequest.h000066400000000000000000000034451220152020200160240ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef HTTPREQUEST_H #define HTTPREQUEST_H #include #include "httpheaders.h" class QHostAddress; class QUrl; class JDnsShared; class HttpRequest : public QObject { Q_OBJECT public: enum ErrorCondition { ErrorGeneric, ErrorPolicy, ErrorConnect, ErrorTls, ErrorTimeout, ErrorBodyNotAllowed }; HttpRequest(JDnsShared *dns, QObject *parent = 0); ~HttpRequest(); void setConnectHost(const QString &host); void setIgnoreTlsErrors(bool on); void start(const QString &method, const QUrl &uri, const HttpHeaders &headers); // may call this multiple times void writeBody(const QByteArray &body); void endBody(); int bytesAvailable() const; bool isFinished() const; ErrorCondition errorCondition() const; int responseCode() const; QByteArray responseReason() const; HttpHeaders responseHeaders() const; QByteArray readResponseBody(int size = -1); // takes from the buffer signals: void nextAddress(const QHostAddress &addr); void readyRead(); void bytesWritten(int count); void error(); private: class ReqBodyDevice; class Private; friend class Private; Private *d; }; #endif zurl-1.0.0/src/httprequest_curl.cpp000066400000000000000000000552111220152020200174020ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "httprequest.h" #include #include #include #include #include #include "jdnsshared.h" #include "bufferlist.h" #include "log.h" #define BUFFER_SIZE 200000 // workaround for earlier curl versions #define UNPAUSE_WORKAROUND 1 static const char *socketActionToString(int x) { switch(x) { case CURL_POLL_NONE: return "CURL_POLL_NONE"; case CURL_POLL_IN: return "CURL_POLL_IN"; case CURL_POLL_OUT: return "CURL_POLL_OUT"; case CURL_POLL_INOUT: return "CURL_POLL_INOUT"; case CURL_POLL_REMOVE: return "CURL_POLL_REMOVE"; default: return 0; } } class CurlConnection : public QObject { Q_OBJECT public: CURLSH *share; CURL *easy; QString method; bool expectBody; bool bodyReadFrom; struct curl_slist *dnsCache; struct curl_slist *headersList; int pauseBits; BufferList in; BufferList out; bool inFinished; bool outFinished; bool haveStatusLine; int responseCode; QByteArray responseReason; bool haveResponseHeaders; HttpHeaders responseHeaders; bool newlyReadOrEof; int newlyWritten; bool pendingUpdate; CURLcode result; CurlConnection() : expectBody(false), bodyReadFrom(false), dnsCache(NULL), headersList(NULL), pauseBits(0), inFinished(false), outFinished(false), haveStatusLine(false), haveResponseHeaders(false), newlyReadOrEof(false), newlyWritten(0), pendingUpdate(false) { share = curl_share_init(); easy = curl_easy_init(); // we use jdns for resolving and cache, so isolate curl's own // caching to this request only curl_share_setopt(share, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS); curl_easy_setopt(easy, CURLOPT_SHARE, share); curl_easy_setopt(easy, CURLOPT_PRIVATE, this); curl_easy_setopt(easy, CURLOPT_DEBUGFUNCTION, debugFunction_cb); curl_easy_setopt(easy, CURLOPT_DEBUGDATA, this); curl_easy_setopt(easy, CURLOPT_WRITEFUNCTION, writeFunction_cb); curl_easy_setopt(easy, CURLOPT_WRITEDATA, this); curl_easy_setopt(easy, CURLOPT_READFUNCTION, readFunction_cb); curl_easy_setopt(easy, CURLOPT_READDATA, this); curl_easy_setopt(easy, CURLOPT_HEADERFUNCTION, headerFunction_cb); curl_easy_setopt(easy, CURLOPT_HEADERDATA, this); curl_easy_setopt(easy, CURLOPT_BUFFERSIZE, BUFFER_SIZE); curl_easy_setopt(easy, CURLOPT_ACCEPT_ENCODING, ""); curl_easy_setopt(easy, CURLOPT_HTTP_CONTENT_DECODING, 1); if(log_outputLevel() >= LOG_LEVEL_DEBUG) curl_easy_setopt(easy, CURLOPT_VERBOSE, 1); } ~CurlConnection() { curl_easy_cleanup(easy); curl_slist_free_all(dnsCache); curl_slist_free_all(headersList); curl_share_cleanup(share); } void setupMethod(const QString &_method) { method = _method; if(method == "OPTIONS") { expectBody = false; curl_easy_setopt(easy, CURLOPT_NOBODY, 1); curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, "OPTIONS"); } else if(method == "HEAD") { expectBody = false; curl_easy_setopt(easy, CURLOPT_NOBODY, 1); curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, NULL); } else if(method == "GET") { expectBody = false; curl_easy_setopt(easy, CURLOPT_HTTPGET, 1); curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, NULL); } else if(method == "POST") { expectBody = true; //curl_easy_setopt(easy, CURLOPT_POST, 1); //curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, NULL); curl_easy_setopt(easy, CURLOPT_UPLOAD, 1); curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, "POST"); } else if(method == "PUT") { expectBody = true; curl_easy_setopt(easy, CURLOPT_UPLOAD, 1); curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, NULL); } else if(method == "DELETE") { expectBody = false; curl_easy_setopt(easy, CURLOPT_NOBODY, 1); curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, "DELETE"); } else { expectBody = true; curl_easy_setopt(easy, CURLOPT_UPLOAD, 1); curl_easy_setopt(easy, CURLOPT_CUSTOMREQUEST, method.toLatin1().data()); } } void setup(const QUrl &uri, const HttpHeaders &_headers, const QHostAddress &connectAddr = QHostAddress(), int connectPort = -1) { assert(!method.isEmpty()); QUrl tmp = uri; if(connectPort != -1) tmp.setPort(connectPort); else if(tmp.port() == -1) { if(uri.scheme() == "https") tmp.setPort(443); else tmp.setPort(80); } curl_easy_setopt(easy, CURLOPT_URL, tmp.toEncoded().data()); if(!connectAddr.isNull()) { curl_slist_free_all(dnsCache); QByteArray cacheEntry = tmp.encodedHost() + ':' + QByteArray::number(tmp.port()) + ':' + connectAddr.toString().toUtf8(); dnsCache = curl_slist_append(dnsCache, cacheEntry.data()); curl_easy_setopt(easy, CURLOPT_RESOLVE, dnsCache); } HttpHeaders headers = _headers; bool chunked = false; if(headers.contains("Content-Length")) { curl_off_t content_len = (curl_off_t)headers.get("Content-Length").toLongLong(); /*if(method == "POST") curl_easy_setopt(easy, CURLOPT_POSTFIELDSIZE_LARGE, content_len); else*/ curl_easy_setopt(easy, CURLOPT_INFILESIZE_LARGE, content_len); // curl will set this for us headers.removeAll("Content-Length"); } else if(expectBody) chunked = true; curl_slist_free_all(headersList); foreach(const HttpHeader &h, headers) { QByteArray i = h.first + ": " + h.second; headersList = curl_slist_append(headersList, i.data()); } if(chunked && !headers.contains("Transfer-Encoding")) headersList = curl_slist_append(headersList, "Transfer-Encoding: chunked"); // disable expect usage as it appears to be buggy curl_slist_append(headersList, "Expect:"); curl_easy_setopt(easy, CURLOPT_HTTPHEADER, headersList); } void update() { if(!pendingUpdate) { pendingUpdate = true; QMetaObject::invokeMethod(this, "doUpdate", Qt::QueuedConnection); } } static size_t debugFunction_cb(CURL *easy, curl_infotype type, char *ptr, size_t size, void *userdata) { CurlConnection *self = (CurlConnection *)userdata; return self->debugFunction(easy, type, ptr, size); } static size_t writeFunction_cb(char *ptr, size_t size, size_t nmemb, void *userdata) { CurlConnection *self = (CurlConnection *)userdata; return self->writeFunction(ptr, size * nmemb); } static size_t readFunction_cb(void *ptr, size_t size, size_t nmemb, void *userdata) { CurlConnection *self = (CurlConnection *)userdata; return self->readFunction((char *)ptr, size * nmemb); } static size_t headerFunction_cb(void *ptr, size_t size, size_t nmemb, void *userdata) { CurlConnection *self = (CurlConnection *)userdata; return self->headerFunction((char *)ptr, size * nmemb); } size_t debugFunction(CURL *easy, curl_infotype type, char *ptr, size_t size) { Q_UNUSED(easy); if(type == CURLINFO_TEXT) { QByteArray str(ptr, size); if(str[str.length() - 1] == '\n') str.truncate(str.length() - 1); log_debug("curl: %s", str.data()); } return 0; } size_t writeFunction(char *p, size_t size) { if(size == 0) return 0; if(in.size() + size > BUFFER_SIZE) { // pause if we can't fit the data log_debug("writeFunction: pausing"); pauseBits |= CURLPAUSE_RECV; return CURL_WRITEFUNC_PAUSE; } else { log_debug("writeFunction: accepting %d bytes", size); in += QByteArray(p, size); newlyReadOrEof = true; update(); } return size; } size_t readFunction(char *p, size_t size) { QByteArray buf = out.take(size); if(!buf.isEmpty()) { bodyReadFrom = true; memcpy(p, buf.data(), buf.size()); newlyWritten += buf.size(); log_debug("readFunction: providing %d bytes", buf.size()); update(); return buf.size(); } else { if(outFinished) { log_debug("readFunction: eof"); return 0; } else { log_debug("readFunction: pausing"); pauseBits |= CURLPAUSE_SEND; return CURL_READFUNC_PAUSE; } } } size_t headerFunction(char *p, size_t size) { assert(p[size - 1] == '\n'); // curl doesn't protect us from \n vs \r\n int len; if(p[size - 2] == '\r') len = size - 2; else len = size - 1; QByteArray line(p, len); if(line.isEmpty()) { haveResponseHeaders = true; // grab the status code long l; curl_easy_getinfo(easy, CURLINFO_RESPONSE_CODE, &l); responseCode = (int)l; if(responseCode == 100) { log_debug("got code 100, ignoring this header block"); haveStatusLine = false; haveResponseHeaders = false; } else { // if a content-encoding was used, don't provide content-length QByteArray contentEncoding = responseHeaders.get("Content-Encoding"); if(!contentEncoding.isEmpty() && contentEncoding != "identity") responseHeaders.removeAll("Content-Length"); // tell the app we've got the header block update(); } } else if(!haveResponseHeaders) { if(haveStatusLine) { int at = line.indexOf(": "); if(at == -1) return -1; log_debug("response header: %s", line.data()); responseHeaders += HttpHeader(line.mid(0, at), line.mid(at + 2)); } else { // status reason we have to parse ourselves int at = line.indexOf(' '); if(at == -1) return -1; at = line.indexOf(' ', at + 1); if(at == -1) return -1; responseReason = line.mid(at + 1); haveStatusLine = true; } } return size; } void done(CURLcode _result) { inFinished = true; result = _result; newlyReadOrEof = true; update(); } signals: void updated(); public slots: void doUpdate() { pendingUpdate = false; emit updated(); } }; class CurlConnectionManager : public QObject { Q_OBJECT public: class SocketInfo { public: QSocketNotifier *snRead; QSocketNotifier *snWrite; SocketInfo() : snRead(0), snWrite(0) { } ~SocketInfo() { delete snRead; delete snWrite; } }; CURLM *multi; QHash snMap; QTimer *timer; bool pendingUpdate; CurlConnectionManager(QObject *parent = 0) : QObject(parent), timer(0), pendingUpdate(false) { timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(timer_timeout())); timer->setSingleShot(true); curl_global_init(CURL_GLOBAL_ALL); multi = curl_multi_init(); curl_multi_setopt(multi, CURLMOPT_SOCKETFUNCTION, socketFunction_cb); curl_multi_setopt(multi, CURLMOPT_SOCKETDATA, this); curl_multi_setopt(multi, CURLMOPT_TIMERFUNCTION, timerFunction_cb); curl_multi_setopt(multi, CURLMOPT_TIMERDATA, this); } ~CurlConnectionManager() { curl_multi_cleanup(multi); curl_global_cleanup(); } void update() { if(!pendingUpdate) { pendingUpdate = true; QMetaObject::invokeMethod(this, "doUpdate", Qt::QueuedConnection); } } static int socketFunction_cb(CURL *easy, curl_socket_t s, int action, void *userp, void *socketp) { CurlConnectionManager *self = (CurlConnectionManager *)userp; return self->socketFunction(easy, s, action, socketp); } static void timerFunction_cb(CURLM *multi, long timeout_ms, void *userp) { CurlConnectionManager *self = (CurlConnectionManager *)userp; self->timerFunction(multi, timeout_ms); } int socketFunction(CURL *easy, curl_socket_t s, int action, void *socketp) { Q_UNUSED(easy); const char *str = socketActionToString(action); if(!str) { log_debug("socketFunction: unknown action: %d fd=%d", action, s); return 0; } log_debug("socketFunction: %s %d", str, s); if(action == CURL_POLL_REMOVE) { SocketInfo *si = (SocketInfo *)socketp; snMap.remove(si->snRead); snMap.remove(si->snWrite); delete si; return 0; } SocketInfo *si = (SocketInfo *)socketp; if(!si) { si = new SocketInfo; si->snRead = new QSocketNotifier(s, QSocketNotifier::Read, this); si->snRead->setEnabled(false); connect(si->snRead, SIGNAL(activated(int)), SLOT(snRead_activated(int))); snMap.insert(si->snRead, si); si->snWrite = new QSocketNotifier(s, QSocketNotifier::Write, this); si->snWrite->setEnabled(false); connect(si->snWrite, SIGNAL(activated(int)), SLOT(snWrite_activated(int))); snMap.insert(si->snWrite, si); curl_multi_assign(multi, s, si); } if(action == CURL_POLL_IN || action == CURL_POLL_INOUT) si->snRead->setEnabled(true); else si->snRead->setEnabled(false); if(action == CURL_POLL_OUT || action == CURL_POLL_INOUT) si->snWrite->setEnabled(true); else si->snWrite->setEnabled(false); return 0; } void timerFunction(CURLM *multi, long timeout_ms) { Q_UNUSED(multi); if(timeout_ms >= 0) log_debug("timerFunction: wake up in %dms", (int)timeout_ms); else log_debug("timerFunction: cancel timer"); if(timeout_ms == -1) { if(timer) timer->stop(); } else if(timeout_ms == 0) { timer_timeout(); } else { timer->start((int)timeout_ms); } } void doSocketAction(bool all, int sockfd, int ev_bitmask) { int running; if(!all) curl_multi_socket_action(multi, sockfd, ev_bitmask, &running); else curl_multi_socket_all(multi, &running); processMessages(); } void processMessages() { while(true) { int pending; CURLMsg *m = curl_multi_info_read(multi, &pending); if(!m || !m->msg) break; if(m->msg == CURLMSG_DONE) { CurlConnection *conn; curl_easy_getinfo(m->easy_handle, CURLINFO_PRIVATE, &conn); conn->done(m->data.result); } else log_debug("unknown message: %d\n", m->msg); } } public slots: void snRead_activated(int socket) { QSocketNotifier *sn = (QSocketNotifier *)sender(); SocketInfo *si = snMap.value(sn); assert(si); doSocketAction(false, socket, CURL_CSELECT_IN); } void snWrite_activated(int socket) { QSocketNotifier *sn = (QSocketNotifier *)sender(); SocketInfo *si = snMap.value(sn); assert(si); doSocketAction(false, socket, CURL_CSELECT_OUT); } void timer_timeout() { doSocketAction(false, CURL_SOCKET_TIMEOUT, 0); } void doUpdate() { pendingUpdate = false; #ifdef UNPAUSE_WORKAROUND doSocketAction(true, 0, 0); #else doSocketAction(false, CURL_SOCKET_TIMEOUT, 0); #endif } }; static CurlConnectionManager *g_man = 0; class HttpRequest::Private : public QObject { Q_OBJECT public: HttpRequest *q; JDnsShared *dns; QString connectHost; bool ignoreTlsErrors; HttpRequest::ErrorCondition errorCondition; QString method; QUrl uri; HttpHeaders headers; QString host; QList addrs; HttpRequest::ErrorCondition mostSignificantError; bool ignoreBody; CurlConnection *conn; bool handleAdded; Private(HttpRequest *_q, JDnsShared *_dns) : QObject(_q), q(_q), dns(_dns), ignoreTlsErrors(false), mostSignificantError(HttpRequest::ErrorGeneric), ignoreBody(false), conn(0), handleAdded(false) { if(!g_man) g_man = new CurlConnectionManager(QCoreApplication::instance()); } ~Private() { cleanup(); } void cleanup() { if(conn) { if(handleAdded) curl_multi_remove_handle(g_man->multi, conn->easy); delete conn; conn = 0; handleAdded = false; } } // remake the connection object for retrying void remakeConn() { if(conn) { // take the request body with us BufferList out = conn->out; bool outFinished = conn->outFinished; cleanup(); conn = new CurlConnection; connect(conn, SIGNAL(updated()), SLOT(conn_updated())); conn->setupMethod(method); conn->out = out; conn->outFinished = outFinished; } } void start(const QString &_method, const QUrl &_uri, const HttpHeaders &_headers) { if(_method.isEmpty() || (_uri.scheme() != "https" && _uri.scheme() != "http")) { ignoreBody = true; errorCondition = HttpRequest::ErrorGeneric; QMetaObject::invokeMethod(q, "error", Qt::QueuedConnection); return; } conn = new CurlConnection; connect(conn, SIGNAL(updated()), SLOT(conn_updated())); method = _method; uri = _uri; headers = _headers; // eat any transport headers as they'd likely break things headers.removeAll("Connection"); headers.removeAll("Keep-Alive"); headers.removeAll("Accept-Encoding"); headers.removeAll("Content-Encoding"); headers.removeAll("Transfer-Encoding"); headers.removeAll("Expect"); conn->setupMethod(method); // if we aren't expecting a body, then we'll eat any input and start // the connect after endBody() is called. if(conn->expectBody) startConnect(); } void writeBody(const QByteArray &body) { if(body.isEmpty() || ignoreBody) return; assert(conn); if(conn->expectBody) { conn->out += body; if(conn->pauseBits & CURLPAUSE_SEND) { log_debug("send unpausing"); conn->pauseBits &= ~CURLPAUSE_SEND; curl_easy_pause(conn->easy, conn->pauseBits); g_man->update(); } } else { ignoreBody = true; errorCondition = HttpRequest::ErrorBodyNotAllowed; QMetaObject::invokeMethod(q, "error", Qt::QueuedConnection); } } void endBody() { if(ignoreBody) return; assert(conn); if(conn->expectBody) { if(conn->pauseBits & CURLPAUSE_SEND) { log_debug("send unpausing"); conn->outFinished = true; conn->pauseBits &= ~CURLPAUSE_SEND; curl_easy_pause(conn->easy, conn->pauseBits); g_man->update(); } } else { startConnect(); } } QByteArray readResponseBody(int size) { if(conn) { QByteArray out = conn->in.take(size); if(out.isEmpty()) return out; if(conn->pauseBits & CURLPAUSE_RECV) { log_debug("recv unpausing"); conn->pauseBits &= ~CURLPAUSE_RECV; curl_easy_pause(conn->easy, conn->pauseBits); g_man->update(); } return out; } else return QByteArray(); } void startConnect() { if(!connectHost.isEmpty()) host = connectHost; else host = uri.host(); QHostAddress addr(host); if(!addr.isNull()) { addrs += addr; QMetaObject::invokeMethod(this, "tryNextAddress", Qt::QueuedConnection); } else { JDnsSharedRequest *dreq = new JDnsSharedRequest(dns); connect(dreq, SIGNAL(resultsReady()), SLOT(dreq_resultsReady())); dreq->query(QUrl::toAce(host), QJDns::A); } } // the idea with the priorities here is that an error is considered // more significant the closer the request was to succeeding. e.g. // ErrorTls means the server was actually reached. ErrorPolicy means // we didn't even attempt to try connecting. static int errorPriority(HttpRequest::ErrorCondition e) { if(e == HttpRequest::ErrorTls) return 100; else if(e == HttpRequest::ErrorConnect) return 99; else if(e == HttpRequest::ErrorTimeout) return 98; else if(e == HttpRequest::ErrorPolicy) return 97; else return 0; } private slots: // this method emits signals, so don't call directly from start() void tryNextAddress() { QPointer self = this; if(addrs.isEmpty()) { errorCondition = mostSignificantError; emit q->error(); return; } QHostAddress addr = addrs.takeFirst(); log_debug("trying %s", qPrintable(addr.toString())); emit q->nextAddress(addr); if(!self) return; conn->setup(uri, headers, addr); if(ignoreTlsErrors) { curl_easy_setopt(conn->easy, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(conn->easy, CURLOPT_SSL_VERIFYHOST, 0); } handleAdded = true; curl_multi_add_handle(g_man->multi, conn->easy); // kick the engine g_man->doSocketAction(false, CURL_SOCKET_TIMEOUT, 0); } void dreq_resultsReady() { JDnsSharedRequest *dreq = (JDnsSharedRequest *)sender(); if(dreq->success()) { QList results = dreq->results(); foreach(const QJDns::Record &r, results) { if(r.type == QJDns::A) addrs += r.address; } delete dreq; tryNextAddress(); } else { delete dreq; errorCondition = HttpRequest::ErrorConnect; emit q->error(); } } void conn_updated() { if(conn->inFinished && conn->result != CURLE_OK) { log_debug("curl result: %d", conn->result); bool tryAgain = true; HttpRequest::ErrorCondition curError; switch(conn->result) { case CURLE_COULDNT_CONNECT: curError = HttpRequest::ErrorConnect; break; case CURLE_SSL_CACERT: curError = HttpRequest::ErrorTls; break; case CURLE_OPERATION_TIMEDOUT: // NOTE: if we get this then there may be a chance the request // was actually sent off curError = HttpRequest::ErrorTimeout; break; default: tryAgain = false; curError = HttpRequest::ErrorGeneric; } if(errorPriority(curError) > errorPriority(mostSignificantError)) mostSignificantError = curError; // don't try again if we know we sent off a request if(conn->bodyReadFrom || conn->haveResponseHeaders) tryAgain = false; if(tryAgain) { remakeConn(); tryNextAddress(); } else { errorCondition = mostSignificantError; emit q->error(); return; } } else { QPointer self = this; if(conn->newlyReadOrEof) { conn->newlyReadOrEof = false; emit q->readyRead(); if(!self) return; } if(conn->newlyWritten > 0) { int x = conn->newlyWritten; conn->newlyWritten = 0; emit q->bytesWritten(x); } } } }; HttpRequest::HttpRequest(JDnsShared *dns, QObject *parent) : QObject(parent) { d = new Private(this, dns); } HttpRequest::~HttpRequest() { delete d; } void HttpRequest::setConnectHost(const QString &host) { d->connectHost = host; } void HttpRequest::setIgnoreTlsErrors(bool on) { d->ignoreTlsErrors = on; } void HttpRequest::start(const QString &method, const QUrl &uri, const HttpHeaders &headers) { d->start(method, uri, headers); } void HttpRequest::writeBody(const QByteArray &body) { d->writeBody(body); } void HttpRequest::endBody() { d->endBody(); } int HttpRequest::bytesAvailable() const { if(d->conn) return d->conn->in.size(); else return 0; } bool HttpRequest::isFinished() const { if(d->conn) return d->conn->inFinished; else return false; } HttpRequest::ErrorCondition HttpRequest::errorCondition() const { return d->errorCondition; } int HttpRequest::responseCode() const { if(d->conn) return d->conn->responseCode; else return -1; } QByteArray HttpRequest::responseReason() const { if(d->conn) return d->conn->responseReason; else return QByteArray(); } HttpHeaders HttpRequest::responseHeaders() const { if(d->conn) return d->conn->responseHeaders; else return HttpHeaders(); } QByteArray HttpRequest::readResponseBody(int size) { return d->readResponseBody(size); } #include "httprequest_curl.moc" zurl-1.0.0/src/httprequest_qnam.cpp000066400000000000000000000264371220152020200174010ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "httprequest.h" #include #include #include #include #include #include #include #include "jdnsshared.h" #include "log.h" class HttpRequest::ReqBodyDevice : public QIODevice { Q_OBJECT public: QByteArray buf; bool finished; bool accessed; ReqBodyDevice(QObject *parent = 0) : QIODevice(parent), finished(false), accessed(false) { } bool wasAccessed() const { return accessed; } void append(const QByteArray &in) { buf += in; QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection); } void end() { finished = true; QMetaObject::invokeMethod(this, "readChannelFinished", Qt::QueuedConnection); } // reimplemented virtual bool open(OpenMode mode) { return QIODevice::open(mode); } // reimplemented virtual bool isSequential() const { return true; } // reimplemented virtual bool atEnd() const { return (finished && buf.isEmpty()); } // reimplemented virtual qint64 bytesAvailable() const { return buf.size(); } protected: // reimplemented virtual qint64 readData(char *data, qint64 maxSize) { accessed = true; qint64 size = qMin((qint64)buf.size(), maxSize); memcpy(data, buf.data(), size); buf = buf.mid(size); if(size > 0) emit bytesTaken((int)size); return size; } // reimplemented virtual qint64 writeData(const char *data, qint64 maxSize) { Q_UNUSED(data); Q_UNUSED(maxSize); return -1; } signals: void bytesTaken(int count); }; static QNetworkAccessManager *g_nam = 0; class HttpRequest::Private : public QObject { Q_OBJECT public: HttpRequest *q; JDnsShared *dns; QString connectHost; bool ignoreTlsErrors; HttpRequest::ErrorCondition errorCondition; QString method; QUrl uri; HttpHeaders headers; ReqBodyDevice *outdev; QString host; QList addrs; QNetworkReply *reply; int bytesReceived; HttpRequest::ErrorCondition mostSignificantError; bool ignoreEnd; Private(HttpRequest *_q, JDnsShared *_dns) : QObject(_q), q(_q), dns(_dns), ignoreTlsErrors(false), outdev(0), reply(0), bytesReceived(0), mostSignificantError(HttpRequest::ErrorGeneric), ignoreEnd(false) { if(!g_nam) g_nam = new QNetworkAccessManager(QCoreApplication::instance()); } ~Private() { if(reply) { reply->disconnect(this); reply->setParent(0); reply->deleteLater(); } if(outdev) { outdev->disconnect(this); outdev->setParent(0); outdev->deleteLater(); } } void start(const QString &_method, const QUrl &_uri, const HttpHeaders &_headers) { method = _method; uri = _uri; headers = _headers; if(method == "POST" || method == "PUT") { outdev = new ReqBodyDevice(this); connect(outdev, SIGNAL(bytesTaken(int)), SLOT(outdev_bytesTaken(int))); outdev->open(QIODevice::ReadOnly); startConnect(); } // for all other method types, outdev will be 0 and we'll // start the request once endBody() is called. this unifies // the class usage regardless of method type. } void writeBody(const QByteArray &body) { if(outdev) { outdev->append(body); } else { // set this so a follow-up endBody() call does nothing ignoreEnd = true; errorCondition = HttpRequest::ErrorBodyNotAllowed; QMetaObject::invokeMethod(q, "error", Qt::QueuedConnection); } } void endBody() { if(outdev) { outdev->end(); } else { if(!ignoreEnd) startConnect(); } } void startConnect() { if(!connectHost.isEmpty()) host = connectHost; else host = uri.host(); QHostAddress addr(host); if(!addr.isNull()) { addrs += addr; QMetaObject::invokeMethod(this, "tryNextAddress", Qt::QueuedConnection); } else { JDnsSharedRequest *dreq = new JDnsSharedRequest(dns); connect(dreq, SIGNAL(resultsReady()), SLOT(dreq_resultsReady())); dreq->query(QUrl::toAce(host), QJDns::A); } } // the idea with the priorities here is that an error is considered // more significant the closer the request was to succeeding. e.g. // ErrorTls means the server was actually reached. ErrorPolicy means // we didn't even attempt to try connecting. static int errorPriority(HttpRequest::ErrorCondition e) { if(e == HttpRequest::ErrorTls) return 100; else if(e == HttpRequest::ErrorConnect) return 99; else if(e == HttpRequest::ErrorTimeout) return 98; else if(e == HttpRequest::ErrorPolicy) return 97; else return 0; } private slots: // this method emits signals, so don't call directly from start() void tryNextAddress() { QPointer self = this; if(addrs.isEmpty()) { errorCondition = mostSignificantError; emit q->error(); return; } QHostAddress addr = addrs.takeFirst(); emit q->nextAddress(addr); if(!self) return; QNetworkRequest request; QUrl tmpUrl = uri; tmpUrl.setHost(addr.toString()); request.setUrl(tmpUrl); request.setRawHeader("Host", uri.host().toUtf8()); bool haveContentType = false; bool haveContentLength = false; foreach(const HttpHeader &h, headers) { QByteArray lname = h.first.toLower(); if(lname == "content-type") haveContentType = true; else if(lname == "content-length") haveContentLength = true; request.setRawHeader(h.first, h.second); } if(outdev) { if(!haveContentType) request.setRawHeader("Content-Type", "application/octet-stream"); assert(haveContentLength); } request.setAttribute(QNetworkRequest::DoNotBufferUploadDataAttribute, true); if(method == "HEAD") reply = g_nam->head(request); else if(method == "GET") reply = g_nam->get(request); else if(method == "POST") reply = g_nam->post(request, outdev); else if(method == "PUT") reply = g_nam->put(request, outdev); else if(method == "DELETE") reply = g_nam->deleteResource(request); else if(method == "OPTIONS") reply = g_nam->sendCustomRequest(request, "OPTIONS"); else { errorCondition = HttpRequest::ErrorGeneric; emit q->error(); return; } reply->setParent(this); connect(reply, SIGNAL(readyRead()), SLOT(reply_readyRead())); connect(reply, SIGNAL(finished()), SLOT(reply_finished())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(reply_error(QNetworkReply::NetworkError))); connect(reply, SIGNAL(sslErrors(const QList &)), SLOT(reply_sslErrors(const QList &))); } void dreq_resultsReady() { JDnsSharedRequest *dreq = (JDnsSharedRequest *)sender(); if(dreq->success()) { QList results = dreq->results(); foreach(const QJDns::Record &r, results) { if(r.type == QJDns::A) addrs += r.address; } delete dreq; tryNextAddress(); } else { delete dreq; errorCondition = HttpRequest::ErrorConnect; emit q->error(); } } void reply_readyRead() { emit q->readyRead(); } void reply_finished() { emit q->readyRead(); } void reply_error(QNetworkReply::NetworkError code) { log_debug("HttpRequest::reply_error: %d", (int)code); QVariant v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute); if(v.isValid()) { // qnetworkreply will signal error even if we got a response. so, let's // ignore the error if it looks like we got a response. return; } // Note: it is essential that QNetworkReply::TimeoutError only // occurs during connect and not after a request has been // sent. As far as I can tell from reading Qt's code, this // should be the case. bool tryAgain = true; HttpRequest::ErrorCondition curError; if(code == QNetworkReply::ConnectionRefusedError) curError = HttpRequest::ErrorConnect; else if(code == QNetworkReply::SslHandshakeFailedError) curError = HttpRequest::ErrorTls; else if(code == QNetworkReply::TimeoutError) curError = HttpRequest::ErrorTimeout; else { tryAgain = false; curError = HttpRequest::ErrorGeneric; } if(errorPriority(curError) > errorPriority(mostSignificantError)) mostSignificantError = curError; if(tryAgain) { tryNextAddress(); } else { errorCondition = mostSignificantError; emit q->error(); return; } } void reply_sslErrors(const QList &errors) { QStringList strs; foreach(const QSslError e, errors) strs += e.errorString(); log_debug("HttpRequest::reply_sslErrors: %s", qPrintable(strs.join(", "))); // we'll almost always get a host mismatch error since we replace the host with ip address bool hostMismatchOk = false; if(errors.count() == 1 && errors[0].error() == QSslError::HostNameMismatch) { // in that case, do our own host matching using qca QSslCertificate qtCert = reply->sslConfiguration().peerCertificate(); QCA::Certificate qcaCert = QCA::Certificate::fromDER(qtCert.toDer()); if(qcaCert.matchesHostName(uri.host())) hostMismatchOk = true; } if(ignoreTlsErrors || hostMismatchOk) reply->ignoreSslErrors(); } void outdev_bytesTaken(int count) { emit q->bytesWritten(count); } }; HttpRequest::HttpRequest(JDnsShared *dns, QObject *parent) : QObject(parent) { d = new Private(this, dns); } HttpRequest::~HttpRequest() { delete d; } void HttpRequest::setConnectHost(const QString &host) { d->connectHost = host; } void HttpRequest::setIgnoreTlsErrors(bool on) { d->ignoreTlsErrors = on; } void HttpRequest::start(const QString &method, const QUrl &uri, const HttpHeaders &headers) { d->start(method, uri, headers); } void HttpRequest::writeBody(const QByteArray &body) { d->writeBody(body); } void HttpRequest::endBody() { d->endBody(); } int HttpRequest::bytesAvailable() const { if(d->reply) return d->reply->bytesAvailable(); else return 0; } bool HttpRequest::isFinished() const { if(d->reply) return d->reply->isFinished(); else return false; } HttpRequest::ErrorCondition HttpRequest::errorCondition() const { return d->errorCondition; } int HttpRequest::responseCode() const { if(d->reply) return d->reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); else return -1; } QByteArray HttpRequest::responseReason() const { if(d->reply) return d->reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toByteArray(); else return QByteArray(); } HttpHeaders HttpRequest::responseHeaders() const { if(d->reply) { HttpHeaders out; QList< QPair > headerPairs = d->reply->rawHeaderPairs(); for(int n = 0; n < headerPairs.count(); ++n) out += HttpHeader(headerPairs[n].first, headerPairs[n].second); return out; } else return HttpHeaders(); } QByteArray HttpRequest::readResponseBody(int size) { if(d->reply) { if(size != -1) return d->reply->read(size); else return d->reply->readAll(); } else return QByteArray(); } #include "httprequest.moc" zurl-1.0.0/src/jdns/000077500000000000000000000000001220152020200142135ustar00rootroot00000000000000zurl-1.0.0/src/jdns/README000066400000000000000000000067501220152020200151030ustar00rootroot00000000000000JDNS ---- Date: October 1st, 2005 Author: Justin Karneges JDNS is a simple DNS implementation that can perform normal DNS queries of any record type (notably SRV), as well as Multicast DNS queries and advertising. Multicast support is based on Jeremie Miller's "mdnsd" implementation. For maximum flexibility, JDNS is written in C with no direct dependencies, and is licensed under the MIT license. Your application must supply functionality to JDNS, such as UDP sending/receiving, via callbacks. For Qt users there is a wrapper available called QJDns. jdns.pri can be used to include everything into a qmake project. jdns.pro will build the sample Qt-based commandline tool 'jdns'. Features: - DNS client "stub" resolver - Can fetch any record type, but provides handy decoding for many known types: A, AAAA, SRV, MX, TXT, etc. - Performs retries, caching/expiration, and CNAME following - Algorithm logic adapted from Q3Dns - Multicast queries - Multicast advertising Why? - Trolltech is phasing out the Qt DNS implementation, which in Qt 4 has been relegated to the Qt3Support module. A replacement was desired. - While there are many DNS libraries available, at the time of this writing it was (and still may be) hard to find one that satisfies three essential conditions: cross-platform friendliness (and this includes Windows 9x!), the ability to integrate into existing eventloops, sensible licensing (ie, not GPL). How to use: - Prepare callbacks and call jdns_session_new() - Call jdns_init_unicast() or jdns_init_multicast(), depending on if you want regular or multicast DNS. If you want both kinds, you can always make two sessions. - Make queries and have fun - Call jdns_step() at the right times to advance JDNS processing What is left to you: - The callback functions, obviously. - Querying for several "qualified" names. Here is what Q3Dns does: Query for name as provided Query for name + '.domain' (for every domain the computer is in) - Detecting for '.local' in a name to be queried, and using that to decide whether to query via Multicast or normal DNS. - Recognition of IP addresses. If you want an IP address to resolve to itself, then do that yourself. Passing an IP address as a DNS name to JDNS won't work (especially since it wouldn't make any sense in some contexts, like SRV). - Recognition of known hosts. If you want this, compare inputs against jdns_system_dnsparams(). - For zeroconf/Bonjour, keep in mind that JDNS only provides Multicast DNS capability. DNS-SD and any higher layers would be your job. Using a custom DNS implementation has the drawback that it is difficult to take advantage of platform-specific features (for example, an OS-wide DNS cache or LDAP integration). An application strategy for normal DNS should probably be: - If an A or AAAA record is desired, use a native lookup. - Else, if the platform has advanced DNS features already (ie, res_query), use those. - Else, use JDNS. However, it may not be a bad idea at first to use JDNS for all occasions, so that it can be debugged. For Multicast DNS, awareness of the platform is doubly important. There should only be one Multicast DNS "Responder" per computer, and using JDNS at the same time could result in a conflict. An application strategy for Multicast DNS should be: - If the platform has a Multicast DNS daemon installed already, use it somehow. - Else, use JDNS. Have fun! zurl-1.0.0/src/jdns/TODO000066400000000000000000000017171220152020200147110ustar00rootroot00000000000000(nothing) but, this stuff couldn't hurt: fields that need to be an explicit size should use int16_t, etc support for other DNS record types (SOA, NSPTR) detect CNAME loops, rather than looping max times in order to fail don't follow CNAME for SRV (or so I'm told?) if it is not possible to implement DNSSEC outside of jdns, then add the minimal number of hooks to jdns so that it becomes possible use hash tables to speed up the list lookups unit tests qjdns debug lines reworking: init should emit debugLinesReady, and debug should be available immediately after call (the emit will break SS/DS, put a note about this in a comment about init()) anywhere else, debugLines should conform to SS, but be emitted at the proper time, not deferred. currently, the debug arrives out of sequence with the other signals, resulting in strange output in the commandline tool. consideration for these changes in jdnsshared zurl-1.0.0/src/jdns/jdns.c000066400000000000000000002320521220152020200153210ustar00rootroot00000000000000/* * Copyright (C) 2005-2008 Justin Karneges * * 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. */ #include "jdns_p.h" #include #include "jdns_packet.h" #include "jdns_mdnsd.h" #define JDNS_UDP_UNI_OUT_MAX 512 #define JDNS_UDP_UNI_IN_MAX 16384 #define JDNS_UDP_MUL_OUT_MAX 9000 #define JDNS_UDP_MUL_IN_MAX 16384 // cache no more than 7 days #define JDNS_TTL_MAX (86400 * 7) #define JDNS_CACHE_MAX 16384 #define JDNS_CNAME_MAX 16 #define JDNS_QUERY_MAX 4096 //---------------------------------------------------------------------------- // util //---------------------------------------------------------------------------- // declare this here, but implement it later after we define jdns_session_t static void _debug_line(jdns_session_t *s, const char *format, ...); static unsigned char _hex_nibble(unsigned char c) { if(c <= 9) return '0' + c; else if(c <= 15) return 'a' + (c - 10); else return '?'; } static void _hex_byte(unsigned char c, unsigned char *dest) { dest[0] = _hex_nibble((unsigned char)(c >> 4)); dest[1] = _hex_nibble((unsigned char)(c & 0x0f)); } static jdns_string_t *_make_printable(const unsigned char *str, int size) { unsigned char *buf; int n, i; jdns_string_t *out; if(size == 0) { out = jdns_string_new(); jdns_string_set_cstr(out, ""); return out; } // make room for the largest possible result buf = (unsigned char *)malloc(size * 4); i = 0; for(n = 0; n < size; ++n) { unsigned char c = str[n]; if(c == '\\') { buf[i++] = '\\'; buf[i++] = '\\'; } else if(c >= 0x20 && c < 0x7f) { buf[i++] = c; } else { buf[i++] = '\\'; buf[i++] = 'x'; _hex_byte(c, buf + i); i += 2; } } out = jdns_string_new(); jdns_string_set(out, buf, i); free(buf); return out; } static jdns_string_t *_make_printable_str(const jdns_string_t *str) { return _make_printable(str->data, str->size); } static jdns_string_t *_make_printable_cstr(const char *str) { return _make_printable((const unsigned char *)str, strlen(str)); } static unsigned char *_fix_input(const unsigned char *in) { unsigned char *out; int len; // truncate len = _ustrlen(in); if(len > 254) len = 254; // add a dot to the end if needed if(in[len - 1] != '.' && len < 254) { out = (unsigned char *)malloc(len + 2); // a dot and a zero memcpy(out, in, len); out[len] = '.'; out[len+1] = 0; ++len; } else { out = (unsigned char *)malloc(len + 1); // a zero memcpy(out, in, len); out[len] = 0; } return out; } static const char *_qtype2str(int qtype) { const char *str; switch(qtype) { case JDNS_RTYPE_A: str = "A"; break; case JDNS_RTYPE_AAAA: str = "AAAA"; break; case JDNS_RTYPE_MX: str = "MX"; break; case JDNS_RTYPE_SRV: str = "SRV"; break; case JDNS_RTYPE_CNAME: str = "CNAME"; break; case JDNS_RTYPE_PTR: str = "PTR"; break; case JDNS_RTYPE_TXT: str = "TXT"; break; case JDNS_RTYPE_HINFO: str = "HINFO"; break; case JDNS_RTYPE_NS: str = "NS"; break; case JDNS_RTYPE_ANY: str = "ANY"; break; default: str = ""; break; } return str; } static int _cmp_rdata(const jdns_rr_t *a, const jdns_rr_t *b) { if(a->rdlength != b->rdlength) return 0; if(memcmp(a->rdata, b->rdata, a->rdlength) != 0) return 0; return 1; } static int _cmp_rr(const jdns_rr_t *a, const jdns_rr_t *b) { if(a->type != b->type) return 0; if(!jdns_domain_cmp(a->owner, b->owner)) return 0; switch(a->type) { case JDNS_RTYPE_A: if(!jdns_address_cmp(a->data.address, b->data.address)) return 0; break; case JDNS_RTYPE_AAAA: if(!_cmp_rdata(a, b)) return 0; break; case JDNS_RTYPE_MX: // unsupported return 0; case JDNS_RTYPE_SRV: if(a->data.server->port != b->data.server->port || a->data.server->priority != b->data.server->priority || a->data.server->weight != b->data.server->weight || !jdns_domain_cmp(a->data.server->name, b->data.server->name) ) return 0; break; case JDNS_RTYPE_CNAME: if(!jdns_domain_cmp(a->data.name, b->data.name)) return 0; break; case JDNS_RTYPE_PTR: if(!jdns_domain_cmp(a->data.name, b->data.name)) return 0; break; case JDNS_RTYPE_TXT: if(!_cmp_rdata(a, b)) return 0; break; case JDNS_RTYPE_HINFO: if(!_cmp_rdata(a, b)) return 0; break; case JDNS_RTYPE_NS: // unsupported return 0; default: if(!_cmp_rdata(a, b)) return 0; break; } return 1; } static jdns_response_t *_packet2response(const jdns_packet_t *packet, const unsigned char *qname, int qtype, int classmask) { int n; jdns_response_t *r; r = jdns_response_new(); for(n = 0; n < packet->answerRecords->count; ++n) { jdns_packet_resource_t *res = (jdns_packet_resource_t *)packet->answerRecords->item[n]; jdns_rr_t *rr; int put_in_answer; if((res->qclass & classmask) != 0x0001) continue; rr = jdns_rr_from_resource(res, packet); if(!rr) continue; // if qname is set, restrict answers to those that match // the question put_in_answer = 1; if(qname) { // name must match. type must either match or be CNAME, // unless the query was for any type if((qtype != JDNS_RTYPE_ANY && res->qtype != qtype && res->qtype != JDNS_RTYPE_CNAME) || !jdns_domain_cmp(res->qname->data, qname)) { // put unusable records in additional section put_in_answer = 0; } } if(put_in_answer) jdns_response_append_answer(r, rr); else jdns_response_append_additional(r, rr); jdns_rr_delete(rr); } for(n = 0; n < packet->authorityRecords->count; ++n) { jdns_packet_resource_t *res = (jdns_packet_resource_t *)packet->authorityRecords->item[n]; jdns_rr_t *rr; if((res->qclass & classmask) != 0x0001) continue; rr = jdns_rr_from_resource(res, packet); if(!rr) continue; jdns_response_append_authority(r, rr); jdns_rr_delete(rr); } for(n = 0; n < packet->additionalRecords->count; ++n) { jdns_packet_resource_t *res = (jdns_packet_resource_t *)packet->additionalRecords->item[n]; jdns_rr_t *rr; if((res->qclass & classmask) != 0x0001) continue; rr = jdns_rr_from_resource(res, packet); if(!rr) continue; jdns_response_append_additional(r, rr); jdns_rr_delete(rr); } return r; } // size must be 1 to 16 static void _print_hexdump_line(jdns_session_t *s, const unsigned char *buf, int size) { char line[67]; // 3 * 16 + 2 + 16 + zero byte int n; memset(line, ' ', 66); line[66] = 0; if(size > 16) size = 16; for(n = 0; n < size; ++n) { unsigned char c = buf[n]; _hex_byte(c, ((unsigned char *)line) + n * 3); line[n * 3 + 2] = ' '; if(c >= 0x20 && c < 0x7f) line[50 + n] = c; else line[50 + n] = '.'; } _debug_line(s, " %s", line); } static void _print_hexdump(jdns_session_t *s, const unsigned char *buf, int size) { int n; int lines; int at, len; lines = size / 16; if(size % 16 != 0) ++lines; for(n = 0; n < lines; ++n) { at = n * 16; if(at + 16 <= size) len = 16; else len = size - at; _print_hexdump_line(s, buf + at, len); } } static void _print_packet_resources(jdns_session_t *s, const jdns_list_t *reslist) { int n; for(n = 0; n < reslist->count; ++n) { jdns_packet_resource_t *r; jdns_string_t *str; r = (jdns_packet_resource_t *)reslist->item[n]; str = _make_printable_str(r->qname); _debug_line(s, " %04x/%04x [%s] ttl=%ld size=%d", r->qclass, r->qtype, str->data, r->ttl, r->rdlength); jdns_string_delete(str); } } static void _print_packet(jdns_session_t *s, const jdns_packet_t *packet) { int n; _debug_line(s, "Packet:"); _debug_line(s, " id: %d", packet->id); _debug_line(s, " opts: qr:%d, opcode:%d, aa:%d, tc:%d, rd:%d, ra:%d, z:%d, rcode:%d", packet->opts.qr, packet->opts.opcode, packet->opts.aa, packet->opts.tc, packet->opts.rd, packet->opts.ra, packet->opts.z, packet->opts.rcode); _debug_line(s, " qdcount=%d, ancount=%d, nscount=%d, arcount=%d", packet->qdcount, packet->ancount, packet->nscount, packet->arcount); if(packet->questions->count > 0) { _debug_line(s, " questions: (class/type name)"); for(n = 0; n < packet->questions->count; ++n) { jdns_packet_question_t *q; jdns_string_t *str; q = (jdns_packet_question_t *)packet->questions->item[n]; str = _make_printable_str(q->qname); _debug_line(s, " %04x/%04x [%s]", q->qclass, q->qtype, str->data); jdns_string_delete(str); } } if(packet->answerRecords->count > 0) { _debug_line(s, " answerRecords: (class/type owner ttl size)"); _print_packet_resources(s, packet->answerRecords); } if(packet->authorityRecords->count > 0) { _debug_line(s, " authorityRecords: (class/type owner ttl size)"); _print_packet_resources(s, packet->authorityRecords); } if(packet->additionalRecords->count > 0) { _debug_line(s, " additionalRecords: (class/type owner ttl size)"); _print_packet_resources(s, packet->additionalRecords); } } static void _print_rr(jdns_session_t *s, const jdns_rr_t *rr, const unsigned char *owner) { int n; jdns_string_t *ownerstr; ownerstr = jdns_string_new(); // not the expected owner? if(!owner || !jdns_domain_cmp(owner, rr->owner)) { unsigned char *buf; jdns_string_t *str = _make_printable_cstr((const char *)rr->owner); buf = (unsigned char *)malloc(str->size + 3); // " [%s]" buf[0] = ' '; buf[1] = '['; memcpy(buf + 2, str->data, str->size); buf[str->size + 2] = ']'; jdns_string_set(ownerstr, buf, str->size + 3); jdns_string_delete(str); free(buf); } else jdns_string_set_cstr(ownerstr, ""); switch(rr->type) { case JDNS_RTYPE_A: { _debug_line(s, " A: [%s] (ttl=%d)%s", rr->data.address->c_str, rr->ttl, ownerstr->data); break; } case JDNS_RTYPE_AAAA: { _debug_line(s, " AAAA: [%s] (ttl=%d)%s", rr->data.address->c_str, rr->ttl, ownerstr->data); break; } case JDNS_RTYPE_MX: { jdns_string_t *str = _make_printable_cstr((const char *)rr->data.server->name); _debug_line(s, " MX: [%s] priority=%d (ttl=%d)%s", str->data, rr->data.server->priority, rr->ttl, ownerstr->data); jdns_string_delete(str); break; } case JDNS_RTYPE_SRV: { jdns_string_t *str = _make_printable_cstr((const char *)rr->data.server->name); _debug_line(s, " SRV: [%s] port=%d priority=%d weight=%d (ttl=%d)%s", str->data, rr->data.server->port, rr->data.server->priority, rr->data.server->weight, rr->ttl, ownerstr->data); jdns_string_delete(str); break; } case JDNS_RTYPE_CNAME: { jdns_string_t *str = _make_printable_cstr((const char *)rr->data.name); _debug_line(s, " CNAME: [%s] (ttl=%d)%s", str->data, rr->ttl, ownerstr->data); jdns_string_delete(str); break; } case JDNS_RTYPE_PTR: { jdns_string_t *str = _make_printable_cstr((const char *)rr->data.name); _debug_line(s, " PTR: [%s] (ttl=%d)%s", str->data, rr->ttl, ownerstr->data); jdns_string_delete(str); break; } case JDNS_RTYPE_TXT: { _debug_line(s, " TXT: count=%d (ttl=%d)%s", rr->data.texts->count, rr->ttl, ownerstr->data); for(n = 0; n < rr->data.texts->count; ++n) { jdns_string_t *str, *pstr; str = rr->data.texts->item[n]; pstr = _make_printable_str(str); _debug_line(s, " len=%d [%s]", str->size, pstr->data); jdns_string_delete(pstr); } break; } case JDNS_RTYPE_HINFO: { jdns_string_t *cpu, *os; cpu = _make_printable_str(rr->data.hinfo.cpu); os = _make_printable_str(rr->data.hinfo.os); _debug_line(s, " HINFO: [%s] [%s] (ttl=%d)%s", cpu->data, os->data, rr->ttl, ownerstr->data); jdns_string_delete(cpu); jdns_string_delete(os); break; } case JDNS_RTYPE_NS: { jdns_string_t *str = _make_printable_cstr((const char *)rr->data.name); _debug_line(s, " NS: [%s] (ttl=%d)%s", str->data, rr->ttl, ownerstr->data); jdns_string_delete(str); break; } default: { _debug_line(s, " Unknown (%d): %d bytes (ttl=%d)%s", rr->type, rr->rdlength, rr->ttl, ownerstr->data); break; } } jdns_string_delete(ownerstr); } static void _print_records(jdns_session_t *s, const jdns_response_t *r, const unsigned char *owner) { int n; _debug_line(s, "Records:"); _debug_line(s, " Answer Records: %d", r->answerCount); for(n = 0; n < r->answerCount; ++n) _print_rr(s, r->answerRecords[n], owner); _debug_line(s, " Authority Records: %d", r->authorityCount); for(n = 0; n < r->authorityCount; ++n) _print_rr(s, r->authorityRecords[n], owner); _debug_line(s, " Additional Records: %d", r->additionalCount); for(n = 0; n < r->additionalCount; ++n) _print_rr(s, r->additionalRecords[n], owner); } static int _min(int a, int b) { return (a < b) ? a : b; } //---------------------------------------------------------------------------- // jdns_event //---------------------------------------------------------------------------- jdns_event_t *jdns_event_new() { jdns_event_t *e = alloc_type(jdns_event_t); e->response = 0; return e; } void jdns_event_delete(jdns_event_t *e) { if(!e) return; jdns_response_delete(e->response); jdns_free(e); } //---------------------------------------------------------------------------- // jdns - internal types //---------------------------------------------------------------------------- typedef struct list_item { void (*dtor)(void *); } list_item_t; typedef struct list { int count; list_item_t **item; } list_t; static list_t *list_new() { list_t *l = alloc_type(list_t); l->count = 0; l->item = 0; return l; } static void list_delete(list_t *l) { int n; if(!l) return; for(n = 0; n < l->count; ++n) l->item[n]->dtor(l->item[n]); if(l->item) free(l->item); jdns_free(l); } static void list_insert(list_t *l, void *item, int pos) { list_item_t *i = (list_item_t *)item; if(!l->item) l->item = (list_item_t **)malloc(sizeof(list_item_t *)); else l->item = (list_item_t **)realloc(l->item, sizeof(list_item_t *) * (l->count + 1)); if(pos != -1) memmove(l->item + pos + 1, l->item + pos, (l->count - pos) * sizeof(list_item_t *)); else pos = l->count; l->item[pos] = i; ++l->count; } static void list_remove(list_t *l, void *item) { int n; list_item_t *i = (list_item_t *)item; int pos = -1; for(n = 0; n < l->count; ++n) { if(l->item[n] == i) { pos = n; break; } } if(pos == -1) return; i->dtor(i); if(l->count > 1) { memmove(l->item + pos, l->item + pos + 1, (l->count - pos - 1) * sizeof(list_item_t *)); --l->count; } else { free(l->item); l->item = 0; l->count = 0; } } typedef struct name_server { void (*dtor)(struct name_server *); int id; jdns_address_t *address; int port; } name_server_t; static void name_server_delete(name_server_t *ns); static name_server_t *name_server_new() { name_server_t *ns = alloc_type(name_server_t); ns->dtor = name_server_delete; ns->address = 0; return ns; } void name_server_delete(name_server_t *ns) { if(!ns) return; jdns_address_delete(ns->address); jdns_free(ns); } int _intarray_indexOf(int *array, int count, int val) { int n; for(n = 0; n < count; ++n) { if(array[n] == val) return n; } return -1; } int _intarray_add(int **array, int *count, int val) { int *p; if(!*array) p = (int *)malloc(sizeof(int)); else p = (int *)realloc(*array, sizeof(int) * (*count + 1)); if(!p) return 0; *array = p; (*array)[*count] = val; ++(*count); return 1; } void _intarray_remove(int **array, int *count, int pos) { int *p; if(*count > 1) { memmove(*array + pos, *array + pos + 1, (*count - pos - 1) * sizeof(int)); --(*count); p = (int *)realloc(*array, sizeof(int) * (*count)); if(p) *array = p; } else { free(*array); *array = 0; *count = 0; } } typedef struct query { void (*dtor)(struct query *); int id; // user request ids int req_ids_count; int *req_ids; // packet id int dns_id; // what we are looking up unsigned char *qname; int qtype; // how many transmission attempts we have done. note this // is not actually how many packets have been sent, since // it is possible for the first transmission to send many // at once. this variable lets us decide when to give up. // (idea taken from qdns). // set to -1 to deactivate (stop sending packets) int step; // which nameservers we've tried (stored as a list of ids) int servers_tried_count; int *servers_tried; // which servers we shouldn't try again int servers_failed_count; int *servers_failed; // flag to indicate whether or not we've tried all available // nameservers already. this means that all future // transmissions are likely repeats, and should be slowed // down. int retrying; // flag to indicate if we've received nxdomain as an error so far int nxdomain; // holds a timeout for the next step (time_start == -1 means no timer) int time_start; int time_next; // whether or not to look in the cache for this query int trycache; // cname subquerying. only cname_parent or cname_child may be set, // never both. int cname_chain_count; struct query *cname_parent; struct query *cname_child; // accumulates known multicast records to prevent duplicates jdns_response_t *mul_known; } query_t; void query_delete(query_t *q); query_t *query_new() { query_t *q = alloc_type(query_t); q->dtor = query_delete; q->req_ids_count = 0; q->req_ids = 0; q->qname = 0; q->servers_tried_count = 0; q->servers_tried = 0; q->servers_failed_count = 0; q->servers_failed = 0; q->nxdomain = 0; q->cname_chain_count = 0; q->cname_parent = 0; q->cname_child = 0; q->mul_known = 0; return q; } void query_delete(query_t *q) { if(!q) return; if(q->req_ids) free(q->req_ids); if(q->qname) free(q->qname); if(q->servers_tried) free(q->servers_tried); if(q->servers_failed) free(q->servers_failed); jdns_response_delete(q->mul_known); jdns_free(q); } int query_have_req_id(const query_t *q, int req_id) { if(_intarray_indexOf(q->req_ids, q->req_ids_count, req_id) != -1) return 1; return 0; } void query_add_req_id(query_t *q, int req_id) { _intarray_add(&q->req_ids, &q->req_ids_count, req_id); } void query_remove_req_id(query_t *q, int req_id) { int pos; pos = _intarray_indexOf(q->req_ids, q->req_ids_count, req_id); if(pos != -1) _intarray_remove(&q->req_ids, &q->req_ids_count, pos); } int query_server_tried(const query_t *q, int ns_id) { if(_intarray_indexOf(q->servers_tried, q->servers_tried_count, ns_id) != -1) return 1; return 0; } void query_add_server_tried(query_t *q, int ns_id) { _intarray_add(&q->servers_tried, &q->servers_tried_count, ns_id); } int query_server_failed(const query_t *q, int ns_id); void query_clear_servers_tried(query_t *q) { int n; // all failed servers must continue to be considered tried servers, so // only clear tried servers that haven't failed for(n = 0; n < q->servers_tried_count; ++n) { if(!query_server_failed(q, q->servers_tried[n])) { _intarray_remove(&q->servers_tried, &q->servers_tried_count, n); --n; // adjust position } } } int query_server_failed(const query_t *q, int ns_id) { if(_intarray_indexOf(q->servers_failed, q->servers_failed_count, ns_id) != -1) return 1; return 0; } void query_add_server_failed(query_t *q, int ns_id) { _intarray_add(&q->servers_failed, &q->servers_failed_count, ns_id); } void query_name_server_gone(query_t *q, int ns_id) { int pos; pos = _intarray_indexOf(q->servers_tried, q->servers_tried_count, ns_id); if(pos != -1) _intarray_remove(&q->servers_tried, &q->servers_tried_count, pos); pos = _intarray_indexOf(q->servers_failed, q->servers_failed_count, ns_id); if(pos != -1) _intarray_remove(&q->servers_failed, &q->servers_failed_count, pos); } typedef struct datagram { void (*dtor)(struct datagram *); int handle; jdns_address_t *dest_address; int dest_port; unsigned char *data; int size; // query association query_t *query; int query_send_type; // 0 == normal, 1 == first step send-all // name server association int ns_id; } datagram_t; void datagram_delete(datagram_t *a); datagram_t *datagram_new() { datagram_t *a = alloc_type(datagram_t); a->dtor = datagram_delete; a->dest_address = 0; a->data = 0; a->size = 0; a->query = 0; return a; } void datagram_delete(datagram_t *a) { if(!a) return; jdns_address_delete(a->dest_address); if(a->data) free(a->data); jdns_free(a); } typedef struct cache_item { void (*dtor)(struct cache_item *); unsigned char *qname; int qtype; int time_start; int ttl; jdns_rr_t *record; // if zero, nxdomain is assumed } cache_item_t; void cache_item_delete(cache_item_t *e); cache_item_t *cache_item_new() { cache_item_t *a = alloc_type(cache_item_t); a->dtor = cache_item_delete; a->qname = 0; a->record = 0; return a; } void cache_item_delete(cache_item_t *a) { if(!a) return; if(a->qname) free(a->qname); jdns_rr_delete(a->record); jdns_free(a); } typedef struct event { void (*dtor)(struct event *); jdns_event_t *event; } event_t; void event_delete(event_t *e); event_t *event_new() { event_t *e = alloc_type(event_t); e->dtor = event_delete; e->event = 0; return e; } void event_delete(event_t *e) { if(!e) return; jdns_event_delete(e->event); jdns_free(e); } typedef struct published_item { void (*dtor)(struct published_item *); int id; int mode; unsigned char *qname; int qtype; mdnsdr rec; jdns_rr_t *rr; } published_item_t; void published_item_delete(published_item_t *a); published_item_t *published_item_new() { published_item_t *a = alloc_type(published_item_t); a->dtor = published_item_delete; a->qname = 0; a->rec = 0; a->rr = 0; return a; } void published_item_delete(published_item_t *a) { if(!a) return; if(a->qname) free(a->qname); jdns_rr_delete(a->rr); jdns_free(a); } //---------------------------------------------------------------------------- // jdns //---------------------------------------------------------------------------- struct jdns_session { jdns_callbacks_t cb; int mode; int shutdown; int next_qid; int next_req_id; int last_time; int next_timer; int next_name_server_id; int handle; int handle_readable, handle_writable; int port; list_t *name_servers; list_t *queries; list_t *outgoing; list_t *events; list_t *cache; // for blocking req_ids from reuse until user explicitly releases int do_hold_req_ids; int held_req_ids_count; int *held_req_ids; // mdns mdnsd mdns; list_t *published; jdns_address_t *maddr; }; jdns_session_t *jdns_session_new(jdns_callbacks_t *callbacks) { jdns_session_t *s = alloc_type(jdns_session_t); memcpy(&s->cb, callbacks, sizeof(jdns_callbacks_t)); s->shutdown = 0; s->next_qid = 0; s->next_req_id = 1; s->last_time = 0; s->next_timer = 0; s->next_name_server_id = 0; s->handle = 0; s->handle_readable = 0; s->handle_writable = 1; s->port = 0; s->name_servers = list_new(); s->queries = list_new(); s->outgoing = list_new(); s->events = list_new(); s->cache = list_new(); s->do_hold_req_ids = 0; s->held_req_ids_count = 0; s->held_req_ids = 0; s->mdns = 0; s->published = list_new(); s->maddr = 0; return s; } void jdns_session_delete(jdns_session_t *s) { if(!s) return; if(s->handle) s->cb.udp_unbind(s, s->cb.app, s->handle); list_delete(s->name_servers); list_delete(s->queries); list_delete(s->outgoing); list_delete(s->events); list_delete(s->cache); if(s->held_req_ids) free(s->held_req_ids); if(s->mdns) mdnsd_free(s->mdns); list_delete(s->published); jdns_address_delete(s->maddr); free(s); } // declare some internal functions static int _callback_time_now(mdnsd d, void *arg); static int _callback_rand_int(mdnsd d, void *arg); static void _append_event(jdns_session_t *s, jdns_event_t *event); static void _append_event_and_hold_id(jdns_session_t *s, jdns_event_t *event); static void _remove_name_server_datagrams(jdns_session_t *s, int ns_id); static void _remove_query_datagrams(jdns_session_t *s, const query_t *q); static int _unicast_query(jdns_session_t *s, const unsigned char *name, int qtype); static void _unicast_cancel(jdns_session_t *s, query_t *q); static int _multicast_query(jdns_session_t *s, const unsigned char *name, int qtype); static void _multicast_cancel(jdns_session_t *s, int req_id); static int _multicast_publish(jdns_session_t *s, int mode, const jdns_rr_t *rr); static void _multicast_update_publish(jdns_session_t *s, int id, const jdns_rr_t *rr); static void _multicast_cancel_publish(jdns_session_t *s, int id); static void _multicast_flush(jdns_session_t *s); static int jdns_step_unicast(jdns_session_t *s, int now); static int jdns_step_multicast(jdns_session_t *s, int now); static void _hold_req_id(jdns_session_t *s, int req_id) { int pos; // make sure we don't hold an id twice pos = _intarray_indexOf(s->held_req_ids, s->held_req_ids_count, req_id); if(pos != -1) return; _intarray_add(&s->held_req_ids, &s->held_req_ids_count, req_id); } static void _unhold_req_id(jdns_session_t *s, int req_id) { int pos; pos = _intarray_indexOf(s->held_req_ids, s->held_req_ids_count, req_id); if(pos != -1) _intarray_remove(&s->held_req_ids, &s->held_req_ids_count, pos); } static void _set_hold_ids_enabled(jdns_session_t *s, int enabled) { if(enabled && !s->do_hold_req_ids) { s->do_hold_req_ids = 1; } else if(!enabled && s->do_hold_req_ids) { s->do_hold_req_ids = 0; if(s->held_req_ids) free(s->held_req_ids); s->held_req_ids = 0; s->held_req_ids_count = 0; } } static int _int_wrap(int *src, int start) { int x; x = (*src)++; if(*src < start) *src = start; return x; } // starts at 0 static int get_next_qid(jdns_session_t *s) { int n, id; id = -1; while(id == -1) { id = _int_wrap(&s->next_qid, 0); for(n = 0; n < s->queries->count; ++n) { if(((query_t *)s->queries->item[n])->id == id) { id = -1; break; } } } return id; } // starts at 1 static int get_next_req_id(jdns_session_t *s) { int n, k, id; id = -1; while(id == -1) { id = _int_wrap(&s->next_req_id, 1); // no query using this? for(n = 0; n < s->queries->count; ++n) { query_t *q = (query_t *)s->queries->item[n]; for(k = 0; k < q->req_ids_count; ++k) { if(q->req_ids[k] == id) { id = -1; break; } } if(id == -1) break; } // no publish using this? for(n = 0; n < s->published->count; ++n) { if(((published_item_t *)s->published->item[n])->id == id) { id = -1; break; } } // successful unicast queries or any kind of error result in // events for actions that are no longer active. we need // to make sure ids for these actions are not reassigned // until the user explicitly releases them for(n = 0; n < s->held_req_ids_count; ++n) { if(s->held_req_ids[n] == id) { id = -1; break; } } } return id; } // random number fitting in 16 bits static int get_next_dns_id(jdns_session_t *s) { int n, id, active_ids; active_ids = 0; id = -1; while(id == -1) { // use random number for dns id id = s->cb.rand_int(s, s->cb.app) & 0xffff; for(n = 0; n < s->queries->count; ++n) { query_t *q = (query_t *)s->queries->item[n]; if(q->dns_id != -1) { ++active_ids; if(active_ids >= JDNS_QUERY_MAX) return -1; if(q->dns_id == id) { id = -1; break; } } } } return id; } // starts at 0 static int get_next_name_server_id(jdns_session_t *s) { int n, id; id = -1; while(id == -1) { id = _int_wrap(&s->next_name_server_id, 0); for(n = 0; n < s->name_servers->count; ++n) { if(((name_server_t *)s->name_servers->item[n])->id == id) { id = -1; break; } } } return id; } int jdns_init_unicast(jdns_session_t *s, const jdns_address_t *addr, int port) { int ret; s->mode = 0; ret = s->cb.udp_bind(s, s->cb.app, addr, port, 0); if(ret <= 0) return 0; s->handle = ret; s->port = port; return 1; } int jdns_init_multicast(jdns_session_t *s, const jdns_address_t *addr, int port, const jdns_address_t *maddr) { int ret; s->mode = 1; ret = s->cb.udp_bind(s, s->cb.app, addr, port, maddr); if(ret <= 0) return 0; s->handle = ret; s->port = port; s->maddr = jdns_address_copy(maddr); // class 1. note: frame size is ignored by the jdns version of mdnsd s->mdns = mdnsd_new(0x0001, 1000, s->port, _callback_time_now, _callback_rand_int, s); return 1; } void jdns_shutdown(jdns_session_t *s) { if(s->shutdown == 0) s->shutdown = 1; // request shutdown } void jdns_set_nameservers(jdns_session_t *s, const jdns_nameserverlist_t *nslist) { int n, k; // removed? for(k = 0; k < s->name_servers->count; ++k) { name_server_t *ns = (name_server_t *)(s->name_servers->item[k]); int found = 0; for(n = 0; n < nslist->count; ++n) { jdns_nameserver_t *i = (jdns_nameserver_t *)nslist->item[n]; if(jdns_address_cmp(ns->address, i->address) && ns->port == i->port) { found = 1; break; } } if(!found) { int i; int ns_id; // remove any pending packets to this nameserver _remove_name_server_datagrams(s, ns->id); _debug_line(s, "ns [%s:%d] (id=%d) removed", ns->address->c_str, ns->port, ns->id); ns_id = ns->id; list_remove(s->name_servers, ns); --k; // adjust position for(i = 0; i < s->queries->count; ++i) query_name_server_gone((query_t *)s->queries->item[i], ns_id); } } // added? for(n = 0; n < nslist->count; ++n) { name_server_t *ns; jdns_nameserver_t *i; int found; i = (jdns_nameserver_t *)nslist->item[n]; found = 0; for(k = 0; k < s->name_servers->count; ++k) { ns = (name_server_t *)(s->name_servers->item[k]); if(jdns_address_cmp(ns->address, i->address) && ns->port == i->port) { found = 1; break; } } if(found) { _debug_line(s, "ns [%s:%d] (id=%d) still present", ns->address->c_str, ns->port, ns->id); } else { ns = name_server_new(); ns->id = get_next_name_server_id(s); ns->address = jdns_address_copy(i->address); ns->port = i->port; list_insert(s->name_servers, ns, -1); _debug_line(s, "ns [%s:%d] (id=%d) added", ns->address->c_str, ns->port, ns->id); } } // no nameservers? if(nslist->count == 0) { _debug_line(s, "nameserver count is zero, invalidating any queries"); // invalidate all of the queries! for(n = 0; n < s->queries->count; ++n) { query_t *q = (query_t *)s->queries->item[n]; // report event to any requests listening for(k = 0; k < q->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = q->req_ids[k]; event->status = JDNS_STATUS_TIMEOUT; _append_event_and_hold_id(s, event); } // this line is probably redundant, but just for // consistency we'll do it... _remove_query_datagrams(s, q); list_remove(s->queries, q); --n; // adjust position } } } void jdns_probe(jdns_session_t *s) { if(s->mode != 1) return; _multicast_flush(s); } int jdns_query(jdns_session_t *s, const unsigned char *name, int rtype) { if(s->mode == 0) return _unicast_query(s, name, rtype); else return _multicast_query(s, name, rtype); } static void _remove_events(jdns_session_t *s, int event_type, int id) { int n; for(n = 0; n < s->events->count; ++n) { event_t *e = (event_t *)s->events->item[n]; if(e->event->type == event_type && e->event->id == id) { list_remove(s->events, e); --n; // adjust position } } } void jdns_cancel_query(jdns_session_t *s, int id) { int n; _unhold_req_id(s, id); // remove any events associated with the query. this avoids any // possibility that stale events from one query are mistaken to be // events resulting from a later query that happened to reuse the // id. it also means we don't deliver events for cancelled queries, // which can simplify application logic. _remove_events(s, JDNS_EVENT_RESPONSE, id); // multicast if(s->mode == 1) { _multicast_cancel(s, id); return; } // unicast for(n = 0; n < s->queries->count; ++n) { query_t *q = (query_t *)s->queries->item[n]; if(query_have_req_id(q, id)) { query_remove_req_id(q, id); // note: calling _unicast_cancel might remove an item // from s->queries, thereby screwing up our iterator // position, but that's ok because we just break // anyway. // if no one else is depending on this request, then take action if(q->req_ids_count == 0 && !q->cname_parent) { // remove a possible cname child if(q->cname_child && q->cname_child->req_ids_count == 0) { q->cname_child->cname_parent = 0; _unicast_cancel(s, q->cname_child); q->cname_child = 0; } _unicast_cancel(s, q); } break; } } } int jdns_publish(jdns_session_t *s, int mode, const jdns_rr_t *rr) { return _multicast_publish(s, mode, rr); } void jdns_update_publish(jdns_session_t *s, int id, const jdns_rr_t *rr) { _multicast_update_publish(s, id, rr); } void jdns_cancel_publish(jdns_session_t *s, int id) { _unhold_req_id(s, id); _remove_events(s, JDNS_EVENT_PUBLISH, id); _multicast_cancel_publish(s, id); } int jdns_step(jdns_session_t *s) { int now, passed; int ret; // session is shut down if(s->shutdown == 2) return 0; now = s->cb.time_now(s, s->cb.app); passed = now - s->last_time; _debug_line(s, "passed: %d", passed); if(s->mode == 0) ret = jdns_step_unicast(s, now); else ret = jdns_step_multicast(s, now); s->last_time = now; return ret; } int jdns_next_timer(jdns_session_t *s) { return s->next_timer; } void jdns_set_handle_readable(jdns_session_t *s, int handle) { (void)handle; s->handle_readable = 1; } void jdns_set_handle_writable(jdns_session_t *s, int handle) { (void)handle; s->handle_writable = 1; } jdns_event_t *jdns_next_event(jdns_session_t *s) { jdns_event_t *event = 0; if(s->events->count > 0) { event_t *e = (event_t *)s->events->item[0]; event = e->event; e->event = 0; list_remove(s->events, e); } return event; } void jdns_set_hold_ids_enabled(jdns_session_t *s, int enabled) { _set_hold_ids_enabled(s, enabled); } //---------------------------------------------------------------------------- // jdns - internal functions //---------------------------------------------------------------------------- // we don't have vsnprintf on windows, so don't pass anything enormous to // this function. the plan is that no line should exceed 1000 bytes, // although _print_rr() might get close. a 2048 byte buffer should be // plenty then. void _debug_line(jdns_session_t *s, const char *format, ...) { char *buf = (char *)malloc(2048); va_list ap; va_start(ap, format); jdns_vsprintf_s(buf, 2048, format, ap); va_end(ap); s->cb.debug_line(s, s->cb.app, buf); free(buf); } int _callback_time_now(mdnsd d, void *arg) { jdns_session_t *s = (jdns_session_t *)arg; (void)d; // offset the time, mdnsd doesn't like starting at 0 return s->cb.time_now(s, s->cb.app) + 120 * 1000; } int _callback_rand_int(mdnsd d, void *arg) { jdns_session_t *s = (jdns_session_t *)arg; (void)d; return s->cb.rand_int(s, s->cb.app); } void _append_event(jdns_session_t *s, jdns_event_t *event) { event_t *e = event_new(); e->event = event; list_insert(s->events, e, -1); } void _append_event_and_hold_id(jdns_session_t *s, jdns_event_t *event) { if(s->do_hold_req_ids) _hold_req_id(s, event->id); _append_event(s, event); } void _remove_name_server_datagrams(jdns_session_t *s, int ns_id) { int n; for(n = 0; n < s->outgoing->count; ++n) { datagram_t *a = (datagram_t *)s->outgoing->item[n]; if(a->ns_id == ns_id) { list_remove(s->outgoing, a); --n; // adjust position } } } void _remove_query_datagrams(jdns_session_t *s, const query_t *q) { int n; for(n = 0; n < s->outgoing->count; ++n) { datagram_t *a = (datagram_t *)s->outgoing->item[n]; if(a->query == q) { list_remove(s->outgoing, a); --n; // adjust position } } } void _process_message(jdns_session_t *s, jdns_packet_t *p, int now, query_t *q, name_server_t *ns); // return 1 if 'q' should be deleted, 0 if not int _process_response(jdns_session_t *s, jdns_response_t *r, int nxdomain, int now, query_t *q); jdns_response_t *_cache_get_response(jdns_session_t *s, const unsigned char *qname, int qtype, int *_lowest_timeleft) { int n; int lowest_timeleft = -1; int now = s->cb.time_now(s, s->cb.app); jdns_response_t *r = 0; for(n = 0; n < s->cache->count; ++n) { cache_item_t *i = (cache_item_t *)s->cache->item[n]; if(jdns_domain_cmp(i->qname, qname) && i->qtype == qtype) { int passed, timeleft; if(!r) r = jdns_response_new(); if(i->record) jdns_response_append_answer(r, i->record); passed = now - i->time_start; timeleft = (i->ttl * 1000) - passed; if(lowest_timeleft == -1 || timeleft < lowest_timeleft) lowest_timeleft = timeleft; } } if(_lowest_timeleft) *_lowest_timeleft = lowest_timeleft; return r; } query_t *_find_first_active_query(jdns_session_t *s, const unsigned char *qname, int qtype) { int n; query_t *q; for(n = 0; n < s->queries->count; ++n) { q = (query_t *)s->queries->item[n]; if(jdns_domain_cmp(q->qname, qname) && q->qtype == qtype && q->step != -1) return q; } return 0; } query_t *_get_query(jdns_session_t *s, const unsigned char *qname, int qtype, int unique) { query_t *q; jdns_string_t *str; if(!unique) { q = _find_first_active_query(s, qname, qtype); if(q) { str = _make_printable_cstr((const char *)q->qname); _debug_line(s, "[%d] reusing query for: [%s] [%s]", q->id, _qtype2str(qtype), str->data); jdns_string_delete(str); return q; } } q = query_new(); q->id = get_next_qid(s); q->qname = _ustrdup(qname); q->qtype = qtype; q->step = 0; q->dns_id = -1; q->time_start = 0; q->time_next = 0; q->trycache = 1; q->retrying = 0; list_insert(s->queries, q, -1); str = _make_printable_cstr((const char *)q->qname); _debug_line(s, "[%d] querying: [%s] [%s]", q->id, _qtype2str(qtype), str->data); jdns_string_delete(str); return q; } int _unicast_query(jdns_session_t *s, const unsigned char *name, int qtype) { unsigned char *qname; query_t *q; int req_id; jdns_string_t *str; str = _make_printable_cstr((const char *)name); _debug_line(s, "query input: [%s]", str->data); jdns_string_delete(str); qname = _fix_input(name); q = _get_query(s, qname, qtype, 0); req_id = get_next_req_id(s); query_add_req_id(q, req_id); free(qname); return req_id; } void _unicast_cancel(jdns_session_t *s, query_t *q) { // didn't even do a step yet? just remove it if(q->step == 0) { _remove_query_datagrams(s, q); list_remove(s->queries, q); } // otherwise, just deactivate else { // deactivate and remain in the background for // 1 minute. this will allow us to cache a // reply, even if the user is not currently // interested. q->step = -1; q->time_start = s->cb.time_now(s, s->cb.app); q->time_next = 60000; } } void _queue_packet(jdns_session_t *s, query_t *q, const name_server_t *ns, int recurse, int query_send_type) { jdns_packet_t *packet; datagram_t *a; packet = jdns_packet_new(); packet->id = q->dns_id; packet->opts.rd = recurse; // recursion desired { jdns_packet_question_t *question = jdns_packet_question_new(); question->qname = jdns_string_new(); jdns_string_set_cstr(question->qname, (const char *)q->qname); question->qtype = q->qtype; question->qclass = 0x0001; jdns_list_insert(packet->questions, question, -1); jdns_packet_question_delete(question); } if(!jdns_packet_export(packet, JDNS_UDP_UNI_OUT_MAX)) { _debug_line(s, "outgoing packet export error, not sending"); jdns_packet_delete(packet); return; } a = datagram_new(); a->handle = s->handle; a->dest_address = jdns_address_copy(ns->address); a->dest_port = ns->port; a->data = jdns_copy_array(packet->raw_data, packet->raw_size); a->size = packet->raw_size; a->query = q; a->query_send_type = query_send_type; a->ns_id = ns->id; jdns_packet_delete(packet); list_insert(s->outgoing, a, -1); } // return 1 if packets still need to be written int _unicast_do_writes(jdns_session_t *s, int now); // return 1 if packets still need to be read int _unicast_do_reads(jdns_session_t *s, int now); int jdns_step_unicast(jdns_session_t *s, int now) { int n; int need_read = 0; int need_write = 0; int smallest_time = -1; int flags; if(s->shutdown == 1) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_SHUTDOWN; _append_event(s, event); s->shutdown = 2; return 0; } // expire cached items for(n = 0; n < s->cache->count; ++n) { cache_item_t *i = (cache_item_t *)s->cache->item[n]; if(now >= i->time_start + (i->ttl * 1000)) { jdns_string_t *str = _make_printable_cstr((const char *)i->qname); _debug_line(s, "cache exp [%s]", str->data); jdns_string_delete(str); list_remove(s->cache, i); --n; // adjust position } } need_write = _unicast_do_writes(s, now); need_read = _unicast_do_reads(s, now); // calculate next timer (based on queries and cache) for(n = 0; n < s->queries->count; ++n) { query_t *q = (query_t *)(s->queries->item[n]); if(q->time_start != -1) { int qpassed = now - q->time_start; int timeleft = q->time_next - qpassed; if(timeleft < 0) timeleft = 0; if(smallest_time == -1 || timeleft < smallest_time) smallest_time = timeleft; } } for(n = 0; n < s->cache->count; ++n) { cache_item_t *i = (cache_item_t *)(s->cache->item[n]); int passed = now - i->time_start; int timeleft = (i->ttl * 1000) - passed; if(timeleft < 0) timeleft = 0; if(smallest_time == -1 || timeleft < smallest_time) smallest_time = timeleft; } flags = 0; if(smallest_time != -1) { flags |= JDNS_STEP_TIMER; s->next_timer = smallest_time; // offset it a little bit, so that the user doesn't call // us too early, resulting in a no-op and another timer // of 1 millisecond. s->next_timer += 2; } if(need_read || need_write) flags |= JDNS_STEP_HANDLE; return flags; } int _unicast_do_writes(jdns_session_t *s, int now) { int need_write = 0; int n, k; for(n = 0; n < s->queries->count; ++n) { query_t *q; int qpassed, timeleft; int giveup; name_server_t *ns; int already_sending; q = (query_t *)s->queries->item[n]; // nothing to do if(q->time_start == -1) continue; qpassed = now - q->time_start; timeleft = q->time_next - qpassed; if(timeleft < 0) timeleft = 0; _debug_line(s, "[%d] time_start/next=%d/%d (left=%d)", q->id, q->time_start, q->time_next, timeleft); if(timeleft > 0) continue; if(q->trycache) { // is it cached? int lowest_timeleft; int qtype = q->qtype; jdns_response_t *r; r = _cache_get_response(s, q->qname, qtype, &lowest_timeleft); // not found? try cname if(!r) { qtype = JDNS_RTYPE_CNAME; r = _cache_get_response(s, q->qname, qtype, &lowest_timeleft); } if(r) { int nxdomain; _debug_line(s, "[%d] using cached answer", q->id); // are any of the records about to expire in 3 minutes? // assume the client is interested in this record and // query it again "in the background" (but only // if we are not already doing so) if(lowest_timeleft < (3 * 60 * 1000) && !_find_first_active_query(s, q->qname, q->qtype)) { query_t *new_q; _debug_line(s, "requerying for cached item about to expire"); new_q = _get_query(s, q->qname, q->qtype, 1); new_q->retrying = 1; // slow it down new_q->trycache = 0; // don't use the cache for this } nxdomain = r->answerCount == 0 ? 1 : 0; if(_process_response(s, r, nxdomain, -1, q)) { _remove_query_datagrams(s, q); list_remove(s->queries, q); --n; // adjust position } jdns_response_delete(r); continue; } } // inactive if(q->step == -1) { // time up on an inactive query? remove it _debug_line(s, "removing inactive query"); _remove_query_datagrams(s, q); list_remove(s->queries, q); --n; // adjust position continue; } giveup = 0; // too many tries, give up if(q->step == 8) giveup = 1; // no nameservers, give up // (this would happen if someone removed all nameservers // during a query) if(s->name_servers->count == 0) giveup = 1; if(giveup) { // report event to any requests listening for(k = 0; k < q->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = q->req_ids[k]; event->status = JDNS_STATUS_TIMEOUT; _append_event_and_hold_id(s, event); } // report error to parent if(q->cname_parent) { // report event to any requests listening query_t *cq = q->cname_parent; for(k = 0; k < cq->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = cq->req_ids[k]; event->status = JDNS_STATUS_TIMEOUT; _append_event_and_hold_id(s, event); } list_remove(s->queries, cq); } _remove_query_datagrams(s, q); list_remove(s->queries, q); --n; // adjust position continue; } // assign a packet id if we don't have one yet if(q->dns_id == -1) { q->dns_id = get_next_dns_id(s); // couldn't get an id? if(q->dns_id == -1) { _debug_line(s, "unable to reserve packet id"); // report event to any requests listening for(k = 0; k < q->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = q->req_ids[k]; event->status = JDNS_STATUS_ERROR; _append_event_and_hold_id(s, event); } // report error to parent if(q->cname_parent) { // report event to any requests listening query_t *cq = q->cname_parent; for(k = 0; k < cq->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = cq->req_ids[k]; event->status = JDNS_STATUS_ERROR; _append_event_and_hold_id(s, event); } list_remove(s->queries, cq); } _remove_query_datagrams(s, q); list_remove(s->queries, q); --n; // adjust position continue; } } // out of name servers? if(q->servers_tried_count == s->name_servers->count) { // clear the 'tried' list, and start over in retry mode query_clear_servers_tried(q); q->retrying = 1; } // find a nameserver that has not been tried ns = 0; for(k = 0; k < s->name_servers->count; ++k) { name_server_t *i = (name_server_t *)s->name_servers->item[k]; if(!query_server_tried(q, i->id)) { ns = i; break; } } // in theory, it is not possible for 'ns' to be null here // don't send the packet if there is already one in the queue already_sending = 0; for(k = 0; k < s->outgoing->count; ++k) { datagram_t *a = (datagram_t *)s->outgoing->item[k]; if(a->query == q && a->query_send_type == 0) { already_sending = 1; break; } } // send the query, with recursion desired, normal query_send_type if(!already_sending) _queue_packet(s, q, ns, 1, 0); query_add_server_tried(q, ns->id); // if there is one query, then do a trick on the first step /*if(s->queries->count == 1 && q->step == 0 && !q->retrying) { // query all other servers non-recursively // note: if sending fails, there is no retry for(k = 0; k < s->name_servers->count; ++k) { name_server_t *i = (name_server_t *)s->name_servers->item[k]; if(!query_server_tried(q, i->id)) { // last arg sets first-step query_send_type _queue_packet(s, q, i, 0, 1); } } }*/ // out of name servers? if(q->servers_tried_count == s->name_servers->count) { // clear the 'tried' list, and start over in retry mode query_clear_servers_tried(q); q->retrying = 1; } q->time_start = now; q->time_next = q->retrying ? 1500 : 800; ++q->step; } // try to send queued outgoing packets for(n = 0; n < s->outgoing->count; ++n) { datagram_t *a = (datagram_t *)s->outgoing->item[n]; int ret; if(!s->handle_writable) { need_write = 1; break; } _debug_line(s, "SEND %s:%d (size=%d)", a->dest_address->c_str, a->dest_port, a->size); _print_hexdump(s, a->data, a->size); ret = s->cb.udp_write(s, s->cb.app, a->handle, a->dest_address, a->dest_port, a->data, a->size); if(ret == 0) { s->handle_writable = 0; need_write = 1; break; } list_remove(s->outgoing, a); --n; // adjust position } return need_write; } void _cache_add(jdns_session_t *s, const unsigned char *qname, int qtype, int time_start, int ttl, const jdns_rr_t *record) { cache_item_t *i; jdns_string_t *str; if(ttl == 0) return; if(s->cache->count >= JDNS_CACHE_MAX) return; i = cache_item_new(); i->qname = _ustrdup(qname); i->qtype = qtype; i->time_start = time_start; i->ttl = ttl; if(record) i->record = jdns_rr_copy(record); list_insert(s->cache, i, -1); str = _make_printable_cstr((const char *)i->qname); _debug_line(s, "cache add [%s] for %d seconds", str->data, i->ttl); jdns_string_delete(str); } void _cache_remove_all_of_kind(jdns_session_t *s, const unsigned char *qname, int qtype) { int n; for(n = 0; n < s->cache->count; ++n) { cache_item_t *i = (cache_item_t *)s->cache->item[n]; if(jdns_domain_cmp(i->qname, qname) && i->qtype == qtype) { jdns_string_t *str = _make_printable_cstr((const char *)i->qname); _debug_line(s, "cache del [%s]", str->data); jdns_string_delete(str); list_remove(s->cache, i); --n; // adjust position } } } void _cache_remove_all_of_record(jdns_session_t *s, const jdns_rr_t *record) { int n; for(n = 0; n < s->cache->count; ++n) { cache_item_t *i = (cache_item_t *)s->cache->item[n]; if(i->record && _cmp_rr(i->record, record)) { jdns_string_t *str = _make_printable_cstr((const char *)i->qname); _debug_line(s, "cache del [%s]", str->data); jdns_string_delete(str); list_remove(s->cache, i); --n; // adjust position } } } // same as _cache_add, but make sure the exact same record (name AND value) // isn't stored twice, and make sure no more than one cname record per name // is stored. void _cache_add_no_dups(jdns_session_t *s, const unsigned char *qname, int qtype, int time_start, int ttl, const jdns_rr_t *record) { if(qtype == JDNS_RTYPE_CNAME) _cache_remove_all_of_kind(s, qname, qtype); else _cache_remove_all_of_record(s, record); _cache_add(s, qname, qtype, time_start, ttl, record); } int _unicast_do_reads(jdns_session_t *s, int now) { int need_read; int n, k; // let's always ask for reads, just so the user doesn't have to // worry about what should happen to incoming packets otherwise need_read = 1; if(!s->handle_readable) return need_read; while(1) { unsigned char buf[JDNS_UDP_UNI_IN_MAX]; int bufsize = JDNS_UDP_UNI_IN_MAX; int ret; jdns_packet_t *packet; jdns_address_t *addr; int port; query_t *q; name_server_t *ns; addr = jdns_address_new(); ret = s->cb.udp_read(s, s->cb.app, s->handle, addr, &port, buf, &bufsize); // no packet? if(ret == 0) { s->handle_readable = 0; jdns_address_delete(addr); break; } _debug_line(s, "RECV %s:%d (size=%d)", addr->c_str, port, bufsize); _print_hexdump(s, buf, bufsize); if(!jdns_packet_import(&packet, buf, bufsize)) { _debug_line(s, "error parsing packet / too large"); jdns_address_delete(addr); continue; } _print_packet(s, packet); if(s->queries->count == 0) { _debug_line(s, "we have no queries"); jdns_address_delete(addr); jdns_packet_delete(packet); continue; } // who does it belong to? q = 0; ns = 0; for(n = 0; n < s->queries->count; ++n) { query_t *i = (query_t *)s->queries->item[n]; if(i->dns_id == -1) continue; if(i->dns_id == packet->id) { q = i; break; } } if(q) { // what name server did it come from? for(k = 0; k < s->name_servers->count; ++k) { name_server_t *i = (name_server_t *)s->name_servers->item[k]; if(jdns_address_cmp(i->address, addr) && i->port == port) { ns = i; break; } } // none? maybe that's because we're using unicast // over multicast, where responses always come // from an unexpected address if(!ns && s->name_servers->count > 0) { name_server_t *i; jdns_address_t *m4, *m6; i = (name_server_t *)s->name_servers->item[0]; m4 = jdns_address_multicast4_new(); m6 = jdns_address_multicast6_new(); if(jdns_address_cmp(i->address, m4) || jdns_address_cmp(i->address, m6)) ns = i; jdns_address_delete(m4); jdns_address_delete(m6); } // no suitable name server if(!ns) { // setting q = 0 causes the response to be // ignored. earlier versions of jdns would // do this, but now we comment it out because // the behavior is too strict. //q = 0; // instead we'll just print a warning _debug_line(s, "warning: response from unexpected nameserver"); } } jdns_address_delete(addr); // no queries? eat the packet if(!q) { _debug_line(s, "no such query for packet"); jdns_packet_delete(packet); continue; } _process_message(s, packet, now, q, ns); jdns_packet_delete(packet); } return need_read; } void _process_message(jdns_session_t *s, jdns_packet_t *packet, int now, query_t *q, name_server_t *ns) { int n; int authoritative; int truncated; int recursion_desired; int answer_section_ok; jdns_response_t *r; if(packet->opts.opcode != 0) { _debug_line(s, "opcode != 0, discarding"); return; } // we don't test RA (recursion available) // we don't test the extra Z fields authoritative = packet->opts.aa; truncated = packet->opts.tc; recursion_desired = packet->opts.rd; answer_section_ok = 0; if(packet->qdcount == packet->questions->count && packet->ancount == packet->answerRecords->count) answer_section_ok = 1; r = 0; // nxdomain if(packet->opts.rcode == 3) { // treat nxdomain as a generic error, but at the same time flag // the fact that it was received. this ensures that // resolving keeps going, in case the user has multiple dns // servers and one of them reports nxdomain when a later one // would succeed. if all of the servers fail then this flag // can be used at the end to report nxdomain instead of a // generic error. q->nxdomain = 1; } // normal else if(packet->opts.rcode == 0) { int at_least_something; int success; r = _packet2response(packet, q->qname, q->qtype, 0xffff); at_least_something = 0; if(r->answerCount > 0) at_least_something = 1; _print_records(s, r, q->qname); success = 0; if(at_least_something) { success = 1; } else { // note: why does qdns care about recursion_desired here? if(authoritative && recursion_desired) success = 1; } if(!success) { jdns_response_delete(r); r = 0; } } // caching if(r) { int cache_answers; int cache_additional; // clear past items _cache_remove_all_of_kind(s, q->qname, q->qtype); cache_answers = 1; cache_additional = 1; // if truncated, we may not want to cache if(truncated) { cache_additional = 0; if(!answer_section_ok) cache_answers = 0; } if(cache_answers) { for(n = 0; n < r->answerCount; ++n) { jdns_rr_t *record = r->answerRecords[n]; _cache_add_no_dups(s, q->qname, record->type, now, _min(record->ttl, JDNS_TTL_MAX), record); } } if(cache_additional) { for(n = 0; n < r->additionalCount; ++n) { jdns_rr_t *record = r->additionalRecords[n]; _cache_add_no_dups(s, record->owner, record->type, now, _min(record->ttl, JDNS_TTL_MAX), record); } } } // don't pass authority/additional records upwards if(r) jdns_response_remove_extra(r); // this server returned an error? if(!r && ns) { // all failed servers must also be considered tried servers, // so mark as tried if necessary. this can happen if the // tried list is cleared (to perform retrying) and then an // error is received if(!query_server_tried(q, ns->id)) query_add_server_tried(q, ns->id); query_add_server_failed(q, ns->id); } if(_process_response(s, r, 0, now, q)) { _remove_query_datagrams(s, q); list_remove(s->queries, q); } jdns_response_delete(r); } // 'r' can be null, for processing an error // 'now' can be -1, if processing a cached response ('r' always non-null) int _process_response(jdns_session_t *s, jdns_response_t *r, int nxdomain, int now, query_t *q) { int k; int do_error = 0; int do_nxdomain = 0; // error if(!r) { int all_errored; // if not all servers have errored, ignore error all_errored = 1; for(k = 0; k < s->name_servers->count; ++k) { name_server_t *ns = (name_server_t *)s->name_servers->item[k]; if(!query_server_failed(q, ns->id)) { all_errored = 0; break; } } if(!all_errored) return 0; do_error = 1; // if we picked up an nxdomain along the way, act on it now if(q->nxdomain) { do_nxdomain = 1; // cache nxdomain for 1 minute if(q->qtype != JDNS_RTYPE_ANY && now != -1) { _cache_remove_all_of_kind(s, q->qname, q->qtype); _cache_add(s, q->qname, q->qtype, now, 60, 0); } } } else if(nxdomain) { do_error = 1; do_nxdomain = 1; } if(do_error) { // report event to any requests listening for(k = 0; k < q->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = q->req_ids[k]; if(do_nxdomain) event->status = JDNS_STATUS_NXDOMAIN; else event->status = JDNS_STATUS_ERROR; _append_event_and_hold_id(s, event); } // report error to parent if(q->cname_parent) { // report event to any requests listening query_t *cq = q->cname_parent; for(k = 0; k < cq->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = cq->req_ids[k]; event->status = JDNS_STATUS_ERROR; _append_event_and_hold_id(s, event); } list_remove(s->queries, cq); } return 1; } // all we got was a cname that we didn't ask for? if(r->answerCount == 1 && r->answerRecords[0]->type == JDNS_RTYPE_CNAME && q->qtype != JDNS_RTYPE_CNAME) { query_t *new_q; _debug_line(s, "all we got was a cname, following the chain ..."); // max chain count, bail if(q->cname_chain_count >= JDNS_CNAME_MAX) { // report event to any requests listening for(k = 0; k < q->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = q->req_ids[k]; event->status = JDNS_STATUS_ERROR; _append_event_and_hold_id(s, event); } // report error to parent if(q->cname_parent) { // report event to any requests listening query_t *cq = q->cname_parent; for(k = 0; k < cq->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = cq->req_ids[k]; event->status = JDNS_STATUS_ERROR; _append_event_and_hold_id(s, event); } list_remove(s->queries, cq); } return 1; } new_q = _get_query(s, r->answerRecords[0]->data.name, q->qtype, 1); // is the current query a child query? (has a parent) if(q->cname_parent) { // if so, then set new_q as the new child new_q->cname_chain_count = q->cname_chain_count + 1; new_q->cname_parent = q->cname_parent; new_q->cname_parent->cname_child = new_q; // and delete the current query return 1; } else { // otherwise, the current query becomes a parent, with // new_q set as the child new_q->cname_chain_count = q->cname_chain_count + 1; new_q->cname_parent = q; q->cname_child = new_q; q->time_start = -1; q->dns_id = -1; // don't handle responses } } // if this query now has a child, then don't report events or delete if(q->cname_child) return 0; // report event to any requests listening for(k = 0; k < q->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = q->req_ids[k]; event->status = JDNS_STATUS_SUCCESS; event->response = jdns_response_copy(r); _append_event_and_hold_id(s, event); } // report to parent if(q->cname_parent) { // report event to any requests listening query_t *cq = q->cname_parent; for(k = 0; k < cq->req_ids_count; ++k) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = cq->req_ids[k]; event->status = JDNS_STATUS_SUCCESS; event->response = jdns_response_copy(r); _append_event_and_hold_id(s, event); } list_remove(s->queries, cq); } return 1; } //---------------------------------------------------------------------------- // jdns - multicast //---------------------------------------------------------------------------- static jdns_rr_t *_mdnsda2rr(mdnsda a) { jdns_rr_t *rr; if(a->type == JDNS_RTYPE_ANY) return 0; // for AAAA, TXT and HINFO, run the raw rdata through jdns_rr's parser if(a->type == JDNS_RTYPE_AAAA || a->type == JDNS_RTYPE_TXT || a->type == JDNS_RTYPE_HINFO) { jdns_packet_resource_t *pr = jdns_packet_resource_new(); pr->qname = jdns_string_new(); jdns_string_set_cstr(pr->qname, (const char *)a->name); pr->qtype = a->type; pr->qclass = 0x0001; // class is always 1 for us if(a->ttl == 0) pr->ttl = 0; else pr->ttl = a->real_ttl; pr->rdata = jdns_copy_array(a->rdata, a->rdlen); pr->rdlength = a->rdlen; // we don't need a reference for these types rr = jdns_rr_from_resource(pr, 0); } // else, pull the values out of 'a' directly else { rr = jdns_rr_new(); rr->owner = _ustrdup(a->name); rr->qclass = 0x0001; // class is always 1 for us if(a->ttl == 0) rr->ttl = 0; else rr->ttl = a->real_ttl; switch(a->type) { case JDNS_RTYPE_A: { jdns_address_t *addr = jdns_address_new(); jdns_address_set_ipv4(addr, a->ip); jdns_rr_set_A(rr, addr); jdns_address_delete(addr); break; } case JDNS_RTYPE_AAAA: { // covered earlier break; } case JDNS_RTYPE_MX: { // don't care about MX jdns_rr_delete(rr); rr = 0; break; } case JDNS_RTYPE_SRV: { jdns_rr_set_SRV(rr, a->rdname, a->srv.port, a->srv.priority, a->srv.weight); break; } case JDNS_RTYPE_CNAME: { jdns_rr_set_CNAME(rr, a->rdname); break; } case JDNS_RTYPE_PTR: { jdns_rr_set_PTR(rr, a->rdname); break; } case JDNS_RTYPE_TXT: { // covered earlier break; } case JDNS_RTYPE_HINFO: { // covered earlier break; } case JDNS_RTYPE_NS: { // don't care about NS jdns_rr_delete(rr); rr = 0; break; } default: { jdns_rr_set_record(rr, a->type, a->rdata, a->rdlen); break; } } } return rr; } int _multicast_query_ans(mdnsda a, void *arg) { int n; jdns_session_t *s; query_t *q; jdns_response_t *r; jdns_rr_t *rr; jdns_event_t *event; s = (jdns_session_t *)arg; // what query is this for? q = 0; for(n = 0; n < s->queries->count; ++n) { query_t *i = (query_t *)s->queries->item[n]; if((i->qtype == JDNS_RTYPE_ANY || i->qtype == a->type) && jdns_domain_cmp(i->qname, a->name)) { q = i; break; } } // note: this can't happen, but we'll check anyway if(!q) { _debug_line(s, "no such multicast query"); return 0; } rr = _mdnsda2rr(a); if(!rr) return 0; // add/remove as a known if(rr->ttl == 0) { for(n = 0; n < q->mul_known->answerCount; ++n) { jdns_rr_t *k = q->mul_known->answerRecords[n]; if(_cmp_rr(k, rr)) { jdns_response_remove_answer(q->mul_known, n); break; } } } else jdns_response_append_answer(q->mul_known, rr); r = jdns_response_new(); jdns_response_append_answer(r, rr); jdns_rr_delete(rr); // report event to any requests listening for(n = 0; n < q->req_ids_count; ++n) { event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = q->req_ids[n]; event->status = JDNS_STATUS_SUCCESS; event->response = jdns_response_copy(r); _append_event(s, event); } jdns_response_delete(r); return 0; } query_t *_get_multicast_query(jdns_session_t *s, const unsigned char *qname, int qtype) { int n; query_t *q; jdns_string_t *str; // check for existing queries for(n = 0; n < s->queries->count; ++n) { q = (query_t *)s->queries->item[n]; if(jdns_domain_cmp(q->qname, qname) && q->qtype == qtype) { str = _make_printable_cstr((const char *)q->qname); _debug_line(s, "[%d] reusing query for: [%s] [%s]", q->id, _qtype2str(qtype), str->data); jdns_string_delete(str); return q; } } q = query_new(); q->id = get_next_qid(s); q->qname = _ustrdup(qname); q->qtype = qtype; q->step = 0; q->mul_known = jdns_response_new(); list_insert(s->queries, q, -1); str = _make_printable_cstr((const char *)q->qname); _debug_line(s, "[%d] querying: [%s] [%s]", q->id, _qtype2str(qtype), str->data); jdns_string_delete(str); return q; } int _multicast_query(jdns_session_t *s, const unsigned char *name, int qtype) { unsigned char *qname; query_t *q; int req_id; jdns_string_t *str; str = _make_printable_cstr((const char *)name); _debug_line(s, "query input: [%s]", str->data); jdns_string_delete(str); // add a dot to the end if needed qname = _fix_input(name); q = _get_multicast_query(s, qname, qtype); req_id = get_next_req_id(s); query_add_req_id(q, req_id); free(qname); // start the mdnsd_query if necessary if(q->step == 0) { q->step = 1; mdnsd_query(s->mdns, (char *)q->qname, q->qtype, _multicast_query_ans, s); } else { int n; // report the knowns for(n = 0; n < q->mul_known->answerCount; ++n) { const jdns_rr_t *rr; jdns_response_t *r; jdns_event_t *event; rr = q->mul_known->answerRecords[n]; r = jdns_response_new(); jdns_response_append_answer(r, rr); event = jdns_event_new(); event->type = JDNS_EVENT_RESPONSE; event->id = req_id; event->status = JDNS_STATUS_SUCCESS; event->response = r; _append_event(s, event); } } return req_id; } void _multicast_cancel(jdns_session_t *s, int req_id) { int n; for(n = 0; n < s->queries->count; ++n) { query_t *q = (query_t *)s->queries->item[n]; if(query_have_req_id(q, req_id)) { query_remove_req_id(q, req_id); // if no one else is depending on this request, then take action if(q->req_ids_count == 0) { mdnsd_query(s->mdns, (char *)q->qname, q->qtype, NULL, 0); list_remove(s->queries, q); } break; } } } void _multicast_pubresult(int result, char *name, int type, void *arg) { jdns_session_t *s; published_item_t *pub; jdns_event_t *event; int n; s = (jdns_session_t *)arg; // find the associated pub item pub = 0; for(n = 0; n < s->published->count; ++n) { published_item_t *i = (published_item_t *)s->published->item[n]; if(strcmp((char *)i->qname, name) == 0 && i->qtype == type) { pub = i; break; } } // note: this can't happen, but we'll check anyway if(!pub) { _debug_line(s, "no such multicast published item"); return; } if(result == 1) { jdns_string_t *str = _make_printable_cstr(name); _debug_line(s, "published name %s for type %d", str->data, type); jdns_string_delete(str); event = jdns_event_new(); event->type = JDNS_EVENT_PUBLISH; event->id = pub->id; event->status = JDNS_STATUS_SUCCESS; _append_event(s, event); } else { jdns_string_t *str = _make_printable_cstr(name); _debug_line(s, "conflicting name detected %s for type %d", str->data, type); jdns_string_delete(str); event = jdns_event_new(); event->type = JDNS_EVENT_PUBLISH; event->id = pub->id; event->status = JDNS_STATUS_CONFLICT; _append_event_and_hold_id(s, event); // remove the item list_remove(s->published, pub); } } static jdns_string_t *_create_text(const jdns_stringlist_t *texts) { jdns_string_t *out; int n; int total; unsigned char *buf; buf = 0; total = 0; for(n = 0; n < texts->count; ++n) total += texts->item[n]->size + 1; if(total > 0) { int at = 0; buf = (unsigned char *)malloc(total); for(n = 0; n < texts->count; ++n) { unsigned int len = texts->item[n]->size; buf[at++] = len; memcpy(buf + at, texts->item[n]->data, len); at += len; } } out = jdns_string_new(); if(buf) { out->data = buf; out->size = total; } else jdns_string_set_cstr(out, ""); return out; } static void _publish_applyrr_unknown(jdns_session_t *s, mdnsdr r, const jdns_rr_t *rr) { // for unsupported/unknown, just take the rdata // note: for this to work, the app must explicitly set the rdata. // if the record is MX or some other known but unsupported record // type, setting the known fields is not enough mdnsd_set_raw(s->mdns, r, (char *)rr->rdata, rr->rdlength); } static int _publish_applyrr(jdns_session_t *s, mdnsdr r, const jdns_rr_t *rr) { if(!rr->haveKnown) { _publish_applyrr_unknown(s, r, rr); return 1; } // jdns_mdnsd supports: A, AAAA, SRV, CNAME, PTR, TXT, and HINFO switch(rr->type) { case JDNS_RTYPE_A: { unsigned long int ip_net = htonl(rr->data.address->addr.v4); mdnsd_set_raw(s->mdns, r, (char *)&ip_net, 4); break; } case JDNS_RTYPE_AAAA: { mdnsd_set_raw(s->mdns, r, (char *)rr->data.address->addr.v6, 16); break; } case JDNS_RTYPE_SRV: { mdnsd_set_srv(s->mdns, r, rr->data.server->priority, rr->data.server->weight, rr->data.server->port, (char *)rr->data.server->name); break; } case JDNS_RTYPE_CNAME: { mdnsd_set_host(s->mdns, r, (char *)rr->data.name); break; } case JDNS_RTYPE_PTR: { mdnsd_set_host(s->mdns, r, (char *)rr->data.name); break; } case JDNS_RTYPE_TXT: { jdns_string_t *out = _create_text(rr->data.texts); mdnsd_set_raw(s->mdns, r, (char *)out->data, out->size); jdns_string_delete(out); break; } case JDNS_RTYPE_HINFO: { jdns_string_t *out; jdns_stringlist_t *list; list = jdns_stringlist_new(); jdns_stringlist_append(list, rr->data.hinfo.cpu); jdns_stringlist_append(list, rr->data.hinfo.os); out = _create_text(list); jdns_stringlist_delete(list); mdnsd_set_raw(s->mdns, r, (char *)out->data, out->size); jdns_string_delete(out); break; } default: { _publish_applyrr_unknown(s, r, rr); break; } } return 1; } static void report_published(jdns_session_t *s, published_item_t *pub) { jdns_event_t *event; jdns_string_t *str; str = _make_printable_cstr((char *)pub->qname); _debug_line(s, "published name %s for type %d", str->data, pub->qtype); jdns_string_delete(str); event = jdns_event_new(); event->type = JDNS_EVENT_PUBLISH; event->id = pub->id; event->status = JDNS_STATUS_SUCCESS; _append_event(s, event); } int _multicast_publish(jdns_session_t *s, int mode, const jdns_rr_t *rr) { mdnsdr r; published_item_t *pub; int next_id; jdns_event_t *event; int n; r = 0; next_id = get_next_req_id(s); // see if we have an item with this name+type combination already pub = 0; for(n = 0; n < s->published->count; ++n) { published_item_t *i = (published_item_t *)s->published->item[n]; if(i->qtype == rr->type && jdns_domain_cmp(i->qname, rr->owner)) { pub = i; break; } } if(pub) goto error; if(!jdns_rr_verify(rr)) goto error; if(mode == JDNS_PUBLISH_UNIQUE) r = mdnsd_unique(s->mdns, (char *)rr->owner, rr->type, rr->ttl, _multicast_pubresult, s); else r = mdnsd_shared(s->mdns, (char *)rr->owner, rr->type, rr->ttl); if(!_publish_applyrr(s, r, rr)) goto error; pub = published_item_new(); pub->id = next_id; pub->mode = mode; pub->qname = _ustrdup(rr->owner); pub->qtype = rr->type; pub->rec = r; pub->rr = jdns_rr_copy(rr); list_insert(s->published, pub, -1); // mdnsd doesn't report publish events for shared, so do that here if(mode == JDNS_PUBLISH_SHARED) report_published(s, pub); return pub->id; error: _debug_line(s, "attempt to publish record, malformed, unsupported, or duplicate type"); if(r) { // don't publish mdnsd_done(s->mdns, r); } // send an error to the app event = jdns_event_new(); event->type = JDNS_EVENT_PUBLISH; event->id = next_id; event->status = JDNS_STATUS_ERROR; _append_event_and_hold_id(s, event); return next_id; } void _multicast_update_publish(jdns_session_t *s, int id, const jdns_rr_t *rr) { mdnsdr r; published_item_t *pub; int n; pub = 0; for(n = 0; n < s->published->count; ++n) { published_item_t *i = (published_item_t *)s->published->item[n]; if(i->id == id) { pub = i; break; } } if(!pub) return; r = pub->rec; // expire existing record. this is mostly needed for shared records // since unique records already have the cache flush bit and that // should achieve the same result. however, since Apple expires // unique records before updates, so will we. mdnsd_done(s->mdns, r); if(pub->mode == JDNS_PUBLISH_UNIQUE) r = mdnsd_unique(s->mdns, (char *)pub->rr->owner, pub->rr->type, rr->ttl, _multicast_pubresult, s); else r = mdnsd_shared(s->mdns, (char *)pub->rr->owner, pub->rr->type, rr->ttl); pub->rec = r; if(!_publish_applyrr(s, r, rr)) { _debug_line(s, "attempt to update_publish an unsupported type"); return; } } void _multicast_cancel_publish(jdns_session_t *s, int id) { int n; for(n = 0; n < s->published->count; ++n) { published_item_t *i = (published_item_t *)s->published->item[n]; if(i->id == id) { mdnsd_done(s->mdns, i->rec); list_remove(s->published, i); break; } } } void _multicast_flush(jdns_session_t *s) { int n; // to flush, we make like our queries and published items are all new. // we'll do this by destroying/creating the mdnsd object again (so it // is fresh) and then reapply all queries and published items to it. // start over with mdnsd mdnsd_free(s->mdns); s->mdns = mdnsd_new(0x0001, 1000, s->port, _callback_time_now, _callback_rand_int, s); // attempt to publish again for(n = 0; n < s->published->count; ++n) { published_item_t *i; mdnsdr r; i = (published_item_t *)s->published->item[n]; if(i->mode == JDNS_PUBLISH_UNIQUE) r = mdnsd_unique(s->mdns, (char *)i->rr->owner, i->rr->type, i->rr->ttl, _multicast_pubresult, s); else r = mdnsd_shared(s->mdns, (char *)i->rr->owner, i->rr->type, i->rr->ttl); _publish_applyrr(s, r, i->rr); i->rec = r; } // restore the queries for(n = 0; n < s->queries->count; ++n) { query_t *q = (query_t *)s->queries->item[n]; // issue the query mdnsd_query(s->mdns, (char *)q->qname, q->qtype, _multicast_query_ans, s); } } int jdns_step_multicast(jdns_session_t *s, int now) { int need_read, need_write, smallest_time; struct mytimeval *tv; jdns_packet_t *packet; int flags; // not used (void)now; need_read = 0; need_write = 0; if(s->shutdown == 1) mdnsd_shutdown(s->mdns); while(1) { jdns_address_t *addr; unsigned short int port; int ret; unsigned char *buf; int buf_len; if(!mdnsd_out(s->mdns, &packet, &addr, &port)) break; if(!s->handle_writable) { need_write = 1; jdns_address_delete(addr); break; } if(!jdns_packet_export(packet, JDNS_UDP_MUL_OUT_MAX)) { _debug_line(s, "outgoing packet export error, not sending"); jdns_packet_delete(packet); continue; } buf = packet->raw_data; buf_len = packet->raw_size; // multicast if(!addr) { addr = jdns_address_copy(s->maddr); port = s->port; } _debug_line(s, "SEND %s:%d (size=%d)", addr->c_str, port, buf_len); _print_hexdump(s, buf, buf_len); ret = s->cb.udp_write(s, s->cb.app, s->handle, addr, port, buf, buf_len); jdns_address_delete(addr); jdns_packet_delete(packet); // if we can't write the packet, oh well if(ret == 0) { s->handle_writable = 0; need_write = 1; break; } } if(s->shutdown == 1) { jdns_event_t *event = jdns_event_new(); event->type = JDNS_EVENT_SHUTDOWN; _append_event(s, event); s->shutdown = 2; return 0; } // let's always ask for reads, just so the user doesn't have to // worry about what should happen to incoming packets otherwise need_read = 1; if(s->handle_readable) { while(1) { unsigned char buf[JDNS_UDP_MUL_IN_MAX]; int bufsize = JDNS_UDP_MUL_IN_MAX; int ret; jdns_address_t *addr; int port; jdns_response_t *r; addr = jdns_address_new(); ret = s->cb.udp_read(s, s->cb.app, s->handle, addr, &port, buf, &bufsize); // no packet? if(ret == 0) { s->handle_readable = 0; jdns_address_delete(addr); break; } _debug_line(s, "RECV %s:%d (size=%d)", addr->c_str, port, bufsize); _print_hexdump(s, buf, bufsize); if(!jdns_packet_import(&packet, buf, bufsize)) { _debug_line(s, "error parsing packet / too large"); jdns_address_delete(addr); continue; } _print_packet(s, packet); r = _packet2response(packet, 0, 0, 0x7fff); _print_records(s, r, 0); mdnsd_in(s->mdns, packet, r, addr, (unsigned short)port); jdns_address_delete(addr); jdns_packet_delete(packet); jdns_response_delete(r); } } tv = mdnsd_sleep(s->mdns); smallest_time = tv->tv_sec * 1000 + tv->tv_usec / 1000; flags = 0; if(smallest_time != -1) { flags |= JDNS_STEP_TIMER; s->next_timer = smallest_time; // offset it a little bit, so that the user doesn't call // us too early, resulting in a no-op and another timer // of 1 millisecond. s->next_timer += 2; } if(need_read || need_write) flags |= JDNS_STEP_HANDLE; return flags; } zurl-1.0.0/src/jdns/jdns.h000066400000000000000000000363051220152020200153310ustar00rootroot00000000000000/* * Copyright (C) 2005,2006 Justin Karneges * * 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. */ #ifndef JDNS_H #define JDNS_H #ifdef __cplusplus extern "C" { #endif typedef void (*jdns_object_dtor_func)(void *); typedef void *(*jdns_object_cctor_func)(const void *); #define JDNS_OBJECT \ jdns_object_dtor_func dtor; \ jdns_object_cctor_func cctor; #define JDNS_OBJECT_NEW(name) \ (name##_t *)jdns_object_new(sizeof(name##_t), \ (jdns_object_dtor_func)name##_delete, \ (jdns_object_cctor_func)name##_copy); typedef struct jdns_object { JDNS_OBJECT } jdns_object_t; void *jdns_object_new(int size, void (*dtor)(void *), void *(*cctor)(const void *)); void *jdns_object_copy(const void *a); void jdns_object_delete(void *a); void jdns_object_free(void *a); #define JDNS_LIST_DECLARE(name) \ JDNS_OBJECT \ int count; \ name##_t **item; typedef struct jdns_list { JDNS_OBJECT int count; void **item; int valueList; int autoDelete; } jdns_list_t; jdns_list_t *jdns_list_new(); jdns_list_t *jdns_list_copy(const jdns_list_t *a); void jdns_list_delete(jdns_list_t *a); void jdns_list_clear(jdns_list_t *a); void jdns_list_insert(jdns_list_t *a, void *item, int pos); void jdns_list_insert_value(jdns_list_t *a, const void *item, int pos); void jdns_list_remove(jdns_list_t *a, void *item); void jdns_list_remove_at(jdns_list_t *a, int pos); typedef struct jdns_string { JDNS_OBJECT unsigned char *data; int size; } jdns_string_t; jdns_string_t *jdns_string_new(); jdns_string_t *jdns_string_copy(const jdns_string_t *s); void jdns_string_delete(jdns_string_t *s); void jdns_string_set(jdns_string_t *s, const unsigned char *str, int str_len); void jdns_string_set_cstr(jdns_string_t *s, const char *str); // overlays jdns_list typedef struct jdns_stringlist { JDNS_OBJECT int count; jdns_string_t **item; } jdns_stringlist_t; jdns_stringlist_t *jdns_stringlist_new(); jdns_stringlist_t *jdns_stringlist_copy(const jdns_stringlist_t *a); void jdns_stringlist_delete(jdns_stringlist_t *a); void jdns_stringlist_append(jdns_stringlist_t *a, const jdns_string_t *str); typedef struct jdns_address { int isIpv6; union { unsigned long int v4; unsigned char *v6; // 16 bytes } addr; char *c_str; } jdns_address_t; jdns_address_t *jdns_address_new(); jdns_address_t *jdns_address_copy(const jdns_address_t *a); void jdns_address_delete(jdns_address_t *a); void jdns_address_set_ipv4(jdns_address_t *a, unsigned long int ipv4); void jdns_address_set_ipv6(jdns_address_t *a, const unsigned char *ipv6); // return 1 if string was ok, else 0. Note: IPv4 addresses only! int jdns_address_set_cstr(jdns_address_t *a, const char *str); // return 1 if the same, else 0 int jdns_address_cmp(const jdns_address_t *a, const jdns_address_t *b); // convenient predefined addresses/ports #define JDNS_UNICAST_PORT 53 #define JDNS_MULTICAST_PORT 5353 jdns_address_t *jdns_address_multicast4_new(); // 224.0.0.251 jdns_address_t *jdns_address_multicast6_new(); // FF02::FB typedef struct jdns_server { unsigned char *name; int port; // SRV only int priority; int weight; // SRV only } jdns_server_t; jdns_server_t *jdns_server_new(); jdns_server_t *jdns_server_copy(const jdns_server_t *s); void jdns_server_delete(jdns_server_t *s); void jdns_server_set_name(jdns_server_t *s, const unsigned char *name); typedef struct jdns_nameserver { jdns_address_t *address; int port; } jdns_nameserver_t; jdns_nameserver_t *jdns_nameserver_new(); jdns_nameserver_t *jdns_nameserver_copy(const jdns_nameserver_t *a); void jdns_nameserver_delete(jdns_nameserver_t *a); void jdns_nameserver_set(jdns_nameserver_t *a, const jdns_address_t *addr, int port); typedef struct jdns_nameserverlist { int count; jdns_nameserver_t **item; } jdns_nameserverlist_t; jdns_nameserverlist_t *jdns_nameserverlist_new(); jdns_nameserverlist_t *jdns_nameserverlist_copy( const jdns_nameserverlist_t *a); void jdns_nameserverlist_delete(jdns_nameserverlist_t *a); void jdns_nameserverlist_append(jdns_nameserverlist_t *a, const jdns_address_t *addr, int port); typedef struct jdns_dnshost { jdns_string_t *name; jdns_address_t *address; } jdns_dnshost_t; typedef struct jdns_dnshostlist { int count; jdns_dnshost_t **item; } jdns_dnshostlist_t; typedef struct jdns_dnsparams { jdns_nameserverlist_t *nameservers; jdns_stringlist_t *domains; jdns_dnshostlist_t *hosts; } jdns_dnsparams_t; jdns_dnsparams_t *jdns_dnsparams_new(); jdns_dnsparams_t *jdns_dnsparams_copy(jdns_dnsparams_t *a); void jdns_dnsparams_delete(jdns_dnsparams_t *a); void jdns_dnsparams_append_nameserver(jdns_dnsparams_t *a, const jdns_address_t *addr, int port); void jdns_dnsparams_append_domain(jdns_dnsparams_t *a, const jdns_string_t *domain); void jdns_dnsparams_append_host(jdns_dnsparams_t *a, const jdns_string_t *name, const jdns_address_t *address); #define JDNS_RTYPE_A 1 #define JDNS_RTYPE_AAAA 28 #define JDNS_RTYPE_MX 15 #define JDNS_RTYPE_SRV 33 #define JDNS_RTYPE_CNAME 5 #define JDNS_RTYPE_PTR 12 #define JDNS_RTYPE_TXT 16 #define JDNS_RTYPE_HINFO 13 #define JDNS_RTYPE_NS 2 #define JDNS_RTYPE_ANY 255 typedef struct jdns_rr { unsigned char *owner; int ttl; int type; int qclass; int rdlength; unsigned char *rdata; int haveKnown; union { jdns_address_t *address; // for A, AAAA jdns_server_t *server; // for MX, SRV unsigned char *name; // for CNAME, PTR, NS jdns_stringlist_t *texts; // for TXT struct { jdns_string_t *cpu; jdns_string_t *os; } hinfo; // for HINFO } data; } jdns_rr_t; jdns_rr_t *jdns_rr_new(); jdns_rr_t *jdns_rr_copy(const jdns_rr_t *r); void jdns_rr_delete(jdns_rr_t *r); void jdns_rr_set_owner(jdns_rr_t *r, const unsigned char *name); void jdns_rr_set_record(jdns_rr_t *r, int type, const unsigned char *rdata, int rdlength); void jdns_rr_set_A(jdns_rr_t *r, const jdns_address_t *address); void jdns_rr_set_AAAA(jdns_rr_t *r, const jdns_address_t *address); void jdns_rr_set_MX(jdns_rr_t *r, const unsigned char *name, int priority); void jdns_rr_set_SRV(jdns_rr_t *r, const unsigned char *name, int port, int priority, int weight); void jdns_rr_set_CNAME(jdns_rr_t *r, const unsigned char *name); void jdns_rr_set_PTR(jdns_rr_t *r, const unsigned char *name); void jdns_rr_set_TXT(jdns_rr_t *r, const jdns_stringlist_t *texts); void jdns_rr_set_HINFO(jdns_rr_t *r, const jdns_string_t *cpu, const jdns_string_t *os); void jdns_rr_set_NS(jdns_rr_t *r, const unsigned char *name); // note: only works on known types int jdns_rr_verify(const jdns_rr_t *r); typedef struct jdns_response { int answerCount; jdns_rr_t **answerRecords; int authorityCount; jdns_rr_t **authorityRecords; int additionalCount; jdns_rr_t **additionalRecords; } jdns_response_t; jdns_response_t *jdns_response_new(); jdns_response_t *jdns_response_copy(const jdns_response_t *r); void jdns_response_delete(jdns_response_t *r); void jdns_response_append_answer(jdns_response_t *r, const jdns_rr_t *rr); void jdns_response_append_authority(jdns_response_t *r, const jdns_rr_t *rr); void jdns_response_append_additional(jdns_response_t *r, const jdns_rr_t *rr); #define JDNS_PUBLISH_SHARED 0x0001 #define JDNS_PUBLISH_UNIQUE 0x0002 #define JDNS_STEP_TIMER 0x0001 #define JDNS_STEP_HANDLE 0x0002 #define JDNS_EVENT_RESPONSE 0x0001 #define JDNS_EVENT_PUBLISH 0x0002 #define JDNS_EVENT_SHUTDOWN 0x0003 #define JDNS_STATUS_SUCCESS 0x0001 #define JDNS_STATUS_NXDOMAIN 0x0002 #define JDNS_STATUS_ERROR 0x0003 #define JDNS_STATUS_TIMEOUT 0x0004 #define JDNS_STATUS_CONFLICT 0x0005 typedef struct jdns_session jdns_session_t; typedef struct jdns_callbacks { void *app; // user-supplied context // time_now: // s: session // app: user-supplied context // return: milliseconds since session started int (*time_now)(jdns_session_t *s, void *app); // rand_int: // s: session // app: user-supplied context // return: random integer between 0-65535 int (*rand_int)(jdns_session_t *s, void *app); // debug_line: // s: session // app: user-supplied context // str: a line of debug text // return: nothing void (*debug_line)(jdns_session_t *s, void *app, const char *str); // udp_bind: // s: session // app: user-supplied context // addr: ip address of interface to bind to. 0 for all // port: port of interface to bind to. 0 for any // maddr: multicast address. 0 if not using multicast // return: handle (>0) of bound socket, or 0 on error // note: for multicast, the following must be done: // use SO_REUSEPORT to share with other mdns programs // use IP_ADD_MEMBERSHIP to associate addr and maddr // set IP_MULTICAST_TTL to 255 int (*udp_bind)(jdns_session_t *s, void *app, const jdns_address_t *addr, int port, const jdns_address_t *maddr); // udp_unbind: // s: session // app: user-supplied context // handle: handle of socket obtained with udp_bind // return: nothing void (*udp_unbind)(jdns_session_t *s, void *app, int handle); // udp_read: // s: session // app: user-supplied context // handle: handle of socket obtained with udp_bind // addr: store ip address of sender // port: store port of sender // buf: store packet content // bufsize: value contains max size, to be changed to real size // return: 1 if packet read, 0 if none available int (*udp_read)(jdns_session_t *s, void *app, int handle, jdns_address_t *addr, int *port, unsigned char *buf, int *bufsize); // udp_write: // s: session // app: user-supplied context // handle: handle of socket obtained with udp_bind // addr: ip address of recipient // port: port of recipient // buf: packet content // bufsize: size of packet // return: 1 if packet taken for writing, 0 if this is a bad time int (*udp_write)(jdns_session_t *s, void *app, int handle, const jdns_address_t *addr, int port, unsigned char *buf, int bufsize); } jdns_callbacks_t; typedef struct jdns_event { int type; // JDNS_EVENT int id; // query id or publish id // for query, this can be SUCCESS, NXDOMAIN, ERROR, or TIMEOUT // for publish, this can be SUCCESS, ERROR, or CONFLICT int status; // for query jdns_response_t *response; } jdns_event_t; void jdns_event_delete(jdns_event_t *e); // jdns_session_new: // callbacks: the struct of callbacks // return: newly allocated session jdns_session_t *jdns_session_new(jdns_callbacks_t *callbacks); // jdns_session_delete: // s: session to free // return: nothing void jdns_session_delete(jdns_session_t *s); // jdns_init_unicast: // s: session // addr: ip address of interface to bind to. NULL for all // port: port of interface to bind to. 0 for any // return: 1 on success, 0 on failure int jdns_init_unicast(jdns_session_t *s, const jdns_address_t *addr, int port); // jdns_init_multicast: // s: session // addr: ip address of interface to bind to. NULL for all // port: port of interface to bind to. 0 for any // addr: multicast address to associate with. cannot be NULL // return: 1 on success, 0 on failure int jdns_init_multicast(jdns_session_t *s, const jdns_address_t *addr, int port, const jdns_address_t *maddr); // jdns_shutdown: // s: session // return: nothing void jdns_shutdown(jdns_session_t *s); // jdns_set_nameservers: // s: session // nslist: list of nameservers // return nothing void jdns_set_nameservers(jdns_session_t *s, const jdns_nameserverlist_t *nslist); // jdns_probe: // s: session // return: nothing void jdns_probe(jdns_session_t *s); // jdns_query: // s: session // name: the name to look up // rtype: the record type // return: id of this operation int jdns_query(jdns_session_t *s, const unsigned char *name, int rtype); // jdns_cancel_query: // s: session // id: the operation id to cancel // return: nothing void jdns_cancel_query(jdns_session_t *s, int id); // jdns_publish: // s: session // mode: JDNS_PUBLISH shared or unique // rec: the record data // return: id of this operation // note: supported record types: A, AAAA, SRV, CNAME, PTR, TXT, and HINFO. // if the published type is not one of these, raw rdata must be set. int jdns_publish(jdns_session_t *s, int mode, const jdns_rr_t *rec); // jdns_update_publish: // s: session // id: the operation id to update // rec: the record data // return: nothing // note: update only works on successfully published records, and no event // is generated for a successful update. void jdns_update_publish(jdns_session_t *s, int id, const jdns_rr_t *rec); // jdns_cancel_publish: // s: session // id: the operation id to cancel // return: nothing void jdns_cancel_publish(jdns_session_t *s, int id); // jdns_step: // s: session // return: JDNS_STEP flags OR'd together int jdns_step(jdns_session_t *s); // jdns_next_timer: // s: session // return: milliseconds until timeout int jdns_next_timer(jdns_session_t *s); // jdns_set_handle_readable: // s: session // handle: handle that is now readable // return: nothing void jdns_set_handle_readable(jdns_session_t *s, int handle); // jdns_set_handle_writable: // s: session // handle: handle that is now writable // return: nothing void jdns_set_handle_writable(jdns_session_t *s, int handle); // jdns_next_event: // s: session // return: newly allocated event, or zero if none are ready jdns_event_t *jdns_next_event(jdns_session_t *s); // jdns_system_dnsparams: // return: newly allocated dnsparams from the system jdns_dnsparams_t *jdns_system_dnsparams(); // jdns_set_hold_ids_enabled // s: session // enabled: whether to enable id holding. default is 0 (disabled) // return: nothing // normally, when a unicast query completes or any kind of query or publish // operation results in an error, the operation is automatically "canceled". // when id holding is enabled, the operation still stops internally, but the // id value used by that operation is "held" until the application // explicitly calls jdns_cancel_query() or jdns_cancel_publish() to release // it. this allows the application to ensure there is no ambiguity when // determining which operation a particular event belongs to. it is disabled // be default so as to not introduce memory leaks in existing applications, // however new applications really should use it. void jdns_set_hold_ids_enabled(jdns_session_t *s, int enabled); #ifdef __cplusplus } #endif #endif zurl-1.0.0/src/jdns/jdns.pri000066400000000000000000000006321220152020200156660ustar00rootroot00000000000000# qmake project include file QT *= network windows:{ LIBS += -lWs2_32 -lAdvapi32 } unix:{ #QMAKE_CFLAGS += -pedantic } HEADERS += \ $$PWD/jdns_packet.h \ $$PWD/jdns_mdnsd.h \ $$PWD/jdns_p.h \ $$PWD/jdns.h \ $$PWD/qjdns_sock.h \ $$PWD/qjdns.h SOURCES += \ $$PWD/jdns_util.c \ $$PWD/jdns_packet.c \ $$PWD/jdns_mdnsd.c \ $$PWD/jdns_sys.c \ $$PWD/jdns.c \ $$PWD/qjdns_sock.cpp \ $$PWD/qjdns.cpp zurl-1.0.0/src/jdns/jdns.pro000066400000000000000000000001521220152020200156710ustar00rootroot00000000000000CONFIG += console CONFIG -= app_bundle QT -= gui QT += network include(jdns.pri) SOURCES += \ main.cpp zurl-1.0.0/src/jdns/jdns_mdnsd.c000066400000000000000000001013721220152020200165060ustar00rootroot00000000000000/* * Copyright (C) 2005 Jeremie Miller * Copyright (C) 2005,2006 Justin Karneges * * 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. */ #include "jdns_mdnsd.h" #include #include #define QTYPE_A JDNS_RTYPE_A #define QTYPE_AAAA JDNS_RTYPE_AAAA #define QTYPE_MX JDNS_RTYPE_MX #define QTYPE_SRV JDNS_RTYPE_SRV #define QTYPE_CNAME JDNS_RTYPE_CNAME #define QTYPE_PTR JDNS_RTYPE_PTR #define QTYPE_TXT JDNS_RTYPE_TXT #define QTYPE_HINFO JDNS_RTYPE_HINFO #define QTYPE_NS JDNS_RTYPE_NS #define QTYPE_ANY JDNS_RTYPE_ANY // size of query/publish hashes #define SPRIME 108 // size of cache hash #define LPRIME 1009 // brute force garbage cleanup frequency, rarely needed (daily default) #define GC 86400 // maximum number of items to cache. if an attacker on the LAN advertises // a million services, we don't want to crash our program trying to collect // them all. any dns records received beyond this max are ignored. this // means the attacker would succeed in DoS'ing the multicast dns network, // but he wouldn't succeed in running our program out of memory. #define MAX_CACHE 16384 #define bzero(p, size) memset(p, 0, size) /* messy, but it's the best/simplest balance I can find at the moment Some internal data types, and a few hashes: querys, answers, cached, and records (published, unique and shared) Each type has different semantics for processing, both for timeouts, incoming, and outgoing I/O They inter-relate too, like records affect the querys they are relevant to Nice things about MDNS: we only publish once (and then ask asked), and only query once, then just expire records we've got cached */ struct query { char *name; int type; unsigned long int nexttry; int tries; int (*answer)(mdnsda, void *); void *arg; struct query *next, *list; }; struct unicast { int id; char ipv6; unsigned long int to; unsigned char to6[16]; unsigned short int port; mdnsdr r; struct unicast *next; }; struct cached { struct mdnsda_struct rr; struct query *q; struct cached *next; }; struct mdnsdr_struct { struct mdnsda_struct rr; char unique; // # of checks performed to ensure int tries; void (*pubresult)(int, char *, int, void *); void *arg; struct mdnsdr_struct *next, *list; }; struct mdnsd_struct { char shutdown; unsigned long int expireall, checkqlist; struct mytimeval now, sleep, pause, probe, publish; int class, frame; struct cached *cache[LPRIME]; int cache_count; struct mdnsdr_struct *published[SPRIME], *probing, *a_now, *a_pause, *a_publish; struct unicast *uanswers; struct query *queries[SPRIME], *qlist; int (*cb_time_now)(struct mdnsd_struct *dp, void *arg); int (*cb_rand_int)(struct mdnsd_struct *dp, void *arg); void *cb_arg; int port; }; void mygettimeofday(mdnsd d, struct mytimeval *tv) { //struct timeval t; //gettimeofday(&t, 0); //tv->tv_sec = t.tv_sec; //tv->tv_usec = t.tv_usec; int msec = d->cb_time_now(d, d->cb_arg); tv->tv_sec = msec / 1000; tv->tv_usec = (msec % 1000) * 1000; } void query_free(struct query *q) { jdns_free(q->name); jdns_free(q); } void mdnsda_content_free(struct mdnsda_struct *rr) { if(rr->name) jdns_free(rr->name); if(rr->rdata) jdns_free(rr->rdata); if(rr->rdname) jdns_free(rr->rdname); } int _namehash(const char *s) { const unsigned char *name = (const unsigned char *)s; unsigned long h = 0, g; while (*name) { /* do some fancy bitwanking on the string */ h = (h << 4) + (unsigned long)(*name++); if ((g = (h & 0xF0000000UL))!=0) h ^= (g >> 24); h &= ~g; } return (int)h; } // case-insensitive hash int _namehash_nocase(const char *s) { int n, len; char *low = jdns_strdup(s); len = strlen(low); for(n = 0; n < len; ++n) low[n] = tolower(low[n]); n = _namehash(low); jdns_free(low); return n; } // basic linked list and hash primitives struct query *_q_next(mdnsd d, struct query *q, char *host, int type) { if(q == 0) q = d->queries[_namehash_nocase(host) % SPRIME]; else q = q->next; for(;q != 0; q = q->next) if(q->type == type && jdns_domain_cmp((unsigned char *)q->name, (unsigned char *)host)) return q; return 0; } struct cached *_c_next(mdnsd d, struct cached *c, char *host, int type) { if(c == 0) c = d->cache[_namehash_nocase(host) % LPRIME]; else c = c->next; for(;c != 0; c = c->next) if((type == c->rr.type || type == 255) && jdns_domain_cmp(c->rr.name, (unsigned char *)host)) return c; return 0; } mdnsdr _r_next(mdnsd d, mdnsdr r, char *host, int type) { if(r == 0) r = d->published[_namehash_nocase(host) % SPRIME]; else r = r->next; for(;r != 0; r = r->next) if(type == r->rr.type && jdns_domain_cmp(r->rr.name, (unsigned char *)host)) return r; return 0; } /* int _rr_len(mdnsda rr) { int len = 12; // name is always compressed (dup of earlier), plus normal stuff if(rr->rdata) len += rr->rdlen; if(rr->rdname) len += strlen((char *)rr->rdname); // worst case if(rr->ip) len += 4; if(rr->type == QTYPE_PTR) len += 6; // srv record stuff return len; } */ /* int _a_match(struct resource *r, mdnsda a) { // compares new rdata with known a, painfully if(strcmp((char *)r->name,(char *)a->name) || r->type != a->type) return 0; if(r->type == QTYPE_SRV && !strcmp((char *)r->known.srv.name,(char *)a->rdname) && a->srv.port == r->known.srv.port && a->srv.weight == r->known.srv.weight && a->srv.priority == r->known.srv.priority) return 1; if((r->type == QTYPE_PTR || r->type == QTYPE_NS || r->type == QTYPE_CNAME) && !strcmp((char *)a->rdname,(char *)r->known.ns.name)) return 1; if(r->rdlength == a->rdlen && !memcmp(r->rdata,a->rdata,r->rdlength)) return 1; return 0; } */ int _a_match(const jdns_rr_t *r, mdnsda a) { if(r->type != a->type || !jdns_domain_cmp(r->owner, a->name)) return 0; if(r->type == JDNS_RTYPE_SRV) { if(jdns_domain_cmp(r->data.server->name, a->rdname) && r->data.server->port == a->srv.port && r->data.server->priority == a->srv.priority && r->data.server->weight == a->srv.weight ) return 1; } else if(r->type == JDNS_RTYPE_PTR || r->type == JDNS_RTYPE_NS || r->type == JDNS_RTYPE_CNAME) { if(jdns_domain_cmp(r->data.name, a->rdname)) return 1; } else if(r->rdlength == a->rdlen && !memcmp(r->rdata, a->rdata, r->rdlength)) return 1; return 0; } // compare time values easily int _tvdiff(struct mytimeval old, struct mytimeval new) { int udiff = 0; if(old.tv_sec != new.tv_sec) udiff = (new.tv_sec - old.tv_sec) * 1000000; return (new.tv_usec - old.tv_usec) + udiff; } // make sure not already on the list, then insert void _r_push(mdnsdr *list, mdnsdr r) { mdnsdr cur; for(cur = *list; cur != 0; cur = cur->list) if(cur == r) return; r->list = *list; *list = r; } // set this r to probing, set next probe time void _r_probe(mdnsd d, mdnsdr r) { (void)d; (void)r; } // force any r out right away, if valid void _r_publish(mdnsd d, mdnsdr r) { if(r->unique && r->unique < 5) return; // probing already r->tries = 0; d->publish.tv_sec = d->now.tv_sec; d->publish.tv_usec = d->now.tv_usec; _r_push(&d->a_publish,r); } // send r out asap void _r_send(mdnsd d, mdnsdr r) { // removing record if(r->rr.ttl == 0) { if(d->a_publish == r) d->a_publish = r->list; _r_push(&d->a_now, r); return; } if(r->tries < 4) { // being published, make sure that happens soon d->publish.tv_sec = d->now.tv_sec; d->publish.tv_usec = d->now.tv_usec; return; } if(r->unique) { // known unique ones can be sent asap _r_push(&d->a_now,r); return; } // set d->pause.tv_usec to random 20-120 msec d->pause.tv_sec = d->now.tv_sec; //d->pause.tv_usec = d->now.tv_usec + ((d->now.tv_usec % 100) + 20) * 1000; d->pause.tv_usec = d->now.tv_usec; d->pause.tv_usec += ((d->cb_rand_int(d, d->cb_arg) % 100) + 20) * 1000; _r_push(&d->a_pause,r); } // create generic unicast response struct void _u_push(mdnsd d, mdnsdr r, int id, const jdns_address_t *addr, unsigned short int port) { struct unicast *u; u = (struct unicast *)jdns_alloc(sizeof(struct unicast)); bzero(u,sizeof(struct unicast)); u->r = r; u->id = id; if(addr->isIpv6) { u->ipv6 = 1; memcpy(u->to6, addr->addr.v6, 16); } else { u->ipv6 = 0; u->to = addr->addr.v4; } u->port = port; u->next = d->uanswers; d->uanswers = u; } void _q_reset(mdnsd d, struct query *q) { struct cached *cur = 0; q->nexttry = 0; q->tries = 0; while((cur = _c_next(d,cur,q->name,q->type))) if(q->nexttry == 0 || cur->rr.ttl - 7 < q->nexttry) q->nexttry = cur->rr.ttl - 7; if(q->nexttry != 0 && q->nexttry < d->checkqlist) d->checkqlist = q->nexttry; } void _q_done(mdnsd d, struct query *q) { // no more query, update all it's cached entries, remove from lists struct cached *c = 0; struct query *cur; int i = _namehash_nocase(q->name) % SPRIME; while((c = _c_next(d,c,q->name,q->type))) c->q = 0; if(d->qlist == q) d->qlist = q->list; else { for(cur=d->qlist;cur->list != q;cur = cur->list); cur->list = q->list; } if(d->queries[i] == q) d->queries[i] = q->next; else { for(cur=d->queries[i];cur->next != q;cur = cur->next); cur->next = q->next; } query_free(q); } void _r_done(mdnsd d, mdnsdr r) { // buh-bye, remove from hash and free mdnsdr cur = 0; int i = _namehash_nocase((char *)r->rr.name) % SPRIME; if(d->a_now == r) d->a_now = r->list; if(d->a_pause == r) d->a_pause = r->list; if(d->a_publish == r) d->a_publish = r->list; if(d->published[i] == r) d->published[i] = r->next; else { for(cur=d->published[i];cur && cur->next != r;cur = cur->next); if(cur) cur->next = r->next; } mdnsda_content_free(&r->rr); jdns_free(r); } void _q_answer(mdnsd d, struct cached *c) { // call the answer function with this cached entry if(c->rr.ttl <= d->now.tv_sec) c->rr.ttl = 0; if(c->q->answer(&c->rr,c->q->arg) == -1) _q_done(d, c->q); } void _conflict(mdnsd d, mdnsdr r) { r->pubresult(0, (char *)r->rr.name,r->rr.type,r->arg); mdnsd_done(d,r); } void _published(mdnsd d, mdnsdr r) { (void)d; r->pubresult(1, (char *)r->rr.name,r->rr.type,r->arg); } void _c_expire(mdnsd d, struct cached **list) { // expire any old entries in this list struct cached *next, *cur = *list, *last = 0; while(cur != 0) { next = cur->next; if(d->now.tv_sec >= cur->rr.ttl) { if(last) last->next = next; if(*list == cur) *list = next; // update list pointer if the first one expired --(d->cache_count); if(cur->q) _q_answer(d,cur); mdnsda_content_free(&cur->rr); jdns_free(cur); }else{ last = cur; } cur = next; } } // brute force expire any old cached records void _gc(mdnsd d) { int i; for(i=0;icache[i]) _c_expire(d,&d->cache[i]); d->expireall = d->now.tv_sec + GC; } struct cached *_find_exact(mdnsd d, const jdns_rr_t *r) { struct cached *c = 0; while(1) { c = _c_next(d, c, (char *)r->owner, r->type); if(!c) break; if(_a_match(r, &c->rr)) return c; } return 0; } void _cache(mdnsd d, const jdns_rr_t *r) { struct cached *c; int i = _namehash_nocase((char *)r->owner) % LPRIME; struct cached *same_value; // do we already have it? //printf("cache: checking for entry: [%s] [%d]\n", r->owner, r->type); same_value = _find_exact(d, r); if(same_value) { //printf("already have entry of same value\n"); } if(r->qclass == 32768 + d->class) { // cache flush // simulate removal of all records for this question, // except if the value hasn't changed c = 0; while((c = _c_next(d,c,(char *)r->owner,r->type))) { if(c != same_value) c->rr.ttl = 0; } _c_expire(d,&d->cache[i]); // we may have expired same_value here, so check for it again same_value = _find_exact(d, r); } if(r->ttl == 0) { // process deletes if(same_value) same_value->rr.ttl = 0; _c_expire(d,&d->cache[i]); return; } if(same_value) { //printf("updating ttl only\n"); // only update ttl (this code directly copied from below) same_value->rr.ttl = d->now.tv_sec + (r->ttl / 2) + 8; same_value->rr.real_ttl = r->ttl; return; } //printf("cache: inserting entry: [%s] [%d]\n", r->owner, r->type); if(d->cache_count >= MAX_CACHE) return; c = (struct cached *)jdns_alloc(sizeof(struct cached)); bzero(c,sizeof(struct cached)); c->rr.name = (unsigned char *)jdns_strdup((char *)r->owner); c->rr.type = r->type; c->rr.ttl = d->now.tv_sec + (r->ttl / 2) + 8; // XXX hack for now, BAD SPEC, start retrying just after half-waypoint, then expire c->rr.real_ttl = r->ttl; c->rr.rdlen = r->rdlength; c->rr.rdata = jdns_copy_array(r->rdata, r->rdlength); switch(r->type) { case QTYPE_A: c->rr.ip = r->data.address->addr.v4; break; case QTYPE_NS: case QTYPE_CNAME: case QTYPE_PTR: c->rr.rdname = (unsigned char *)jdns_strdup((const char *)r->data.name); break; case QTYPE_SRV: c->rr.rdname = (unsigned char *)jdns_strdup((const char *)r->data.server->name); c->rr.srv.port = r->data.server->port; c->rr.srv.weight = r->data.server->weight; c->rr.srv.priority = r->data.server->priority; break; } c->next = d->cache[i]; d->cache[i] = c; if((c->q = _q_next(d, 0, (char *)r->owner, r->type))) _q_answer(d,c); if(c->q && c->q->nexttry == 0) { //printf("cache insert, but nexttry == 0\n"); _q_reset(d,c->q); if(d->checkqlist == 0) d->checkqlist = c->q->nexttry; //printf("after reset: q->nexttry=%d d->checkqlist=%d\n", c->q->nexttry, d->checkqlist); } } /* void _a_copy(struct message *m, mdnsda a) { // copy the data bits only if(a->rdata) { message_rdata_raw(m, a->rdata, a->rdlen); return; } if(a->ip) message_rdata_long(m, a->ip); if(a->type == QTYPE_SRV) message_rdata_srv(m, a->srv.priority, a->srv.weight, a->srv.port, a->rdname); else if(a->rdname) message_rdata_name(m, a->rdname); } */ void _a_copyq(jdns_list_t *dest, unsigned char *name, unsigned short type, unsigned short class) { jdns_packet_question_t *q = jdns_packet_question_new(); q->qname = jdns_string_new(); jdns_string_set_cstr(q->qname, (char *)name); q->qtype = type; q->qclass = class; jdns_list_insert(dest, q, -1); jdns_packet_question_delete(q); } void _a_copy(jdns_list_t *dest, unsigned char *name, unsigned short type, unsigned short class, unsigned long int ttl, mdnsda a) { jdns_packet_resource_t *r = jdns_packet_resource_new(); r->qname = jdns_string_new(); jdns_string_set_cstr(r->qname, (char *)name); r->qtype = type; r->qclass = class; r->ttl = ttl; if(a->rdata) jdns_packet_resource_add_bytes(r, a->rdata, a->rdlen); else if(a->ip) { unsigned long int ip; ip = htonl(a->ip); jdns_packet_resource_add_bytes(r, (unsigned char *)&ip, 4); } else if(a->type == QTYPE_SRV) { unsigned short priority, weight, port; jdns_string_t *name; priority = htons(a->srv.priority); weight = htons(a->srv.weight); port = htons(a->srv.port); name = jdns_string_new(); jdns_string_set_cstr(name, (const char *)a->rdname); jdns_packet_resource_add_bytes(r, (unsigned char *)&priority, 2); jdns_packet_resource_add_bytes(r, (unsigned char *)&weight, 2); jdns_packet_resource_add_bytes(r, (unsigned char *)&port, 2); jdns_packet_resource_add_name(r, name); jdns_string_delete(name); } else if(a->rdname) { jdns_string_t *name; name = jdns_string_new(); jdns_string_set_cstr(name, (const char *)a->rdname); jdns_packet_resource_add_name(r, name); jdns_string_delete(name); } jdns_list_insert(dest, r, -1); jdns_packet_resource_delete(r); } /* int _r_out(mdnsd d, struct message *m, mdnsdr *list) { // copy a published record into an outgoing message mdnsdr r; //, next; int ret = 0; while((r = *list) != 0 && message_packet_len(m) + _rr_len(&r->rr) < d->frame) { *list = r->list; ret++; if(r->unique) message_an(m, r->rr.name, r->rr.type, (unsigned short)(d->class + 32768), r->rr.ttl); else message_an(m, r->rr.name, r->rr.type, (unsigned short)d->class, r->rr.ttl); _a_copy(m, &r->rr); if(r->rr.ttl == 0) _r_done(d,r); } return ret; } */ int _r_out(mdnsd d, jdns_packet_t *m, mdnsdr *list) { // copy a published record into an outgoing message mdnsdr r; //, next; unsigned short class; int ret = 0; while((r = *list) != 0) { *list = r->list; ret++; class = r->unique ? d->class | 0x8000 : d->class; _a_copy(m->answerRecords, r->rr.name, r->rr.type, class, r->rr.ttl, &r->rr); if(r->rr.ttl == 0) _r_done(d,r); } return ret; } mdnsd mdnsd_new(int class, int frame, int port, int (*time_now)(mdnsd d, void *arg), int (*rand_int)(mdnsd d, void *arg), void *arg) { //int i; mdnsd d; d = (mdnsd)jdns_alloc(sizeof(struct mdnsd_struct)); bzero(d,sizeof(struct mdnsd_struct)); d->cb_time_now = time_now; d->cb_rand_int = rand_int; d->cb_arg = arg; mygettimeofday(d, &d->now); d->expireall = d->now.tv_sec + GC; d->class = class; d->frame = frame; d->cache_count = 0; d->port = port; return d; } void mdnsd_shutdown(mdnsd d) { // shutting down, zero out ttl and push out all records int i; mdnsdr cur,next; d->a_now = 0; for(i=0;ipublished[i]; cur != 0;) { next = cur->next; cur->rr.ttl = 0; cur->list = d->a_now; d->a_now = cur; cur = next; } d->shutdown = 1; } void mdnsd_flush(mdnsd d) { // set all querys to 0 tries // free whole cache // set all mdnsdr to probing // reset all answer lists (void)d; } void mdnsd_free(mdnsd d) { int i; // loop through all hashes, free everything // free answers if any for(i = 0; i < LPRIME; ++i) { while(d->cache[i]) { struct cached *cur = d->cache[i]; d->cache[i] = cur->next; mdnsda_content_free(&cur->rr); jdns_free(cur); } } for(i = 0; i < SPRIME; ++i) { while(d->published[i]) { struct mdnsdr_struct *cur = d->published[i]; d->published[i] = cur->next; mdnsda_content_free(&cur->rr); jdns_free(cur); } } while(d->uanswers) { struct unicast *u = d->uanswers; d->uanswers = u->next; jdns_free(u); } for(i = 0; i < SPRIME; ++i) { while(d->queries[i]) { struct query *cur = d->queries[i]; d->queries[i] = cur->next; query_free(cur); } } jdns_free(d); } void mdnsd_in(mdnsd d, const jdns_packet_t *m, const jdns_response_t *resp, const jdns_address_t *addr, unsigned short int port) { int i, j; mdnsdr r = 0; if(d->shutdown) return; mygettimeofday(d, &d->now); if(m->opts.qr == 0) { for(i=0;iquestions->count;i++) { // process each query jdns_packet_question_t *pq = (jdns_packet_question_t *)m->questions->item[i]; if(pq->qclass != d->class || (r = _r_next(d,0,(char *)pq->qname->data,pq->qtype)) == 0) continue; // send the matching unicast reply if(port != d->port) _u_push(d,r,m->id,addr,port); for(;r != 0; r = _r_next(d,r,(char *)pq->qname->data,pq->qtype)) { // check all of our potential answers if(r->unique && r->unique < 5) { // probing state, check for conflicts for(j=0;jauthorityCount;j++) { // check all to-be answers against our own jdns_rr_t *ns = resp->authorityRecords[j]; if(pq->qtype != ns->type || !jdns_domain_cmp(pq->qname->data, ns->owner)) continue; if(!_a_match(ns,&r->rr)) { _conflict(d,r); // answer isn't ours, conflict! // r is invalid after conflict, start all over r = 0; break; } } continue; } for(j=0;janswerCount;j++) { // check the known answers for this question jdns_rr_t *an = resp->answerRecords[j]; if(pq->qtype != an->type || !jdns_domain_cmp(pq->qname->data, an->owner)) continue; if(_a_match(an,&r->rr)) break; // they already have this answer } if(j == resp->answerCount) _r_send(d,r); } } return; } for(i=0;ianswerCount;i++) { // process each answer, check for a conflict, and cache jdns_rr_t *an = resp->answerRecords[i]; if((r = _r_next(d,0,(char *)an->owner,an->type)) != 0 && r->unique && _a_match(an,&r->rr) == 0) _conflict(d,r); _cache(d,an); } // cache additional records for(i=0;iadditionalCount;i++) { jdns_rr_t *an = resp->additionalRecords[i]; _cache(d,an); } } int mdnsd_out(mdnsd d, jdns_packet_t **_m, jdns_address_t **addr, unsigned short int *port) { mdnsdr r; int ret = 0; jdns_packet_t *m; mygettimeofday(d, &d->now); //bzero(m,sizeof(struct message)); m = jdns_packet_new(); // defaults, multicast *port = 0; //htons(5353); *addr = 0; // *ip = 0; //inet_addr("224.0.0.251"); m->opts.qr = 1; m->opts.aa = 1; if(d->uanswers) { // send out individual unicast answers struct unicast *u = d->uanswers; d->uanswers = u->next; *port = u->port; // *ip = u->to; *addr = jdns_address_new(); if(u->ipv6) jdns_address_set_ipv6(*addr, u->to6); else jdns_address_set_ipv4(*addr, u->to); m->id = u->id; _a_copyq(m->questions, u->r->rr.name, u->r->rr.type, (unsigned short)d->class); _a_copy(m->answerRecords, u->r->rr.name, u->r->rr.type, (unsigned short)d->class, u->r->rr.ttl, &u->r->rr); jdns_free(u); ret = 1; goto end; } //printf("OUT: probing %X now %X pause %X publish %X\n",d->probing,d->a_now,d->a_pause,d->a_publish); // accumulate any immediate responses if(d->a_now) { ret += _r_out(d, m, &d->a_now); } if(d->a_publish && _tvdiff(d->now,d->publish) <= 0) { // check to see if it's time to send the publish retries (and unlink if done) mdnsdr next, cur = d->a_publish, last = 0; unsigned short class; while(cur /*&& message_packet_len(m) + _rr_len(&cur->rr) < d->frame*/ ) { next = cur->list; ret++; cur->tries++; class = cur->unique ? d->class | 0x8000 : d->class; _a_copy(m->answerRecords, cur->rr.name, cur->rr.type, class, cur->rr.ttl, &cur->rr); if(cur->rr.ttl != 0 && cur->tries < 4) { last = cur; cur = next; continue; } if(d->a_publish == cur) d->a_publish = next; if(last) last->list = next; if(cur->rr.ttl == 0) _r_done(d,cur); cur = next; } if(d->a_publish) { d->publish.tv_sec = d->now.tv_sec + 2; d->publish.tv_usec = d->now.tv_usec; } } // if we're in shutdown, we're done if(d->shutdown) goto end; // check if a_pause is ready if(d->a_pause && _tvdiff(d->now, d->pause) <= 0) ret += _r_out(d, m, &d->a_pause); // now process questions if(ret) goto end; m->opts.qr = 0; m->opts.aa = 0; if(d->probing && _tvdiff(d->now,d->probe) <= 0) { mdnsdr last = 0; for(r = d->probing; r != 0;) { // scan probe list to ask questions and process published if(r->unique == 4) { // done probing, publish mdnsdr next = r->list; if(d->probing == r) d->probing = r->list; else last->list = r->list; r->list = 0; r->unique = 5; _r_publish(d,r); _published(d,r); r = next; continue; } //message_qd(m, r->rr.name, r->rr.type, (unsigned short)d->class); _a_copyq(m->questions, r->rr.name, r->rr.type, (unsigned short)d->class); last = r; r = r->list; } for(r = d->probing; r != 0; last = r, r = r->list) { // scan probe list again to append our to-be answers r->unique++; _a_copy(m->authorityRecords, r->rr.name, r->rr.type, (unsigned short)d->class, r->rr.ttl, &r->rr); ret++; } if(ret) { // process probes again in the future d->probe.tv_sec = d->now.tv_sec; d->probe.tv_usec = d->now.tv_usec + 250000; goto end; } } if(d->checkqlist && d->now.tv_sec >= d->checkqlist) { // process qlist for retries or expirations struct query *q; struct cached *c; unsigned long int nextbest = 0; // ask questions first, track nextbest time for(q = d->qlist; q != 0; q = q->list) if(q->nexttry > 0 && q->nexttry <= d->now.tv_sec && q->tries < 3) _a_copyq(m->questions, (unsigned char *)q->name, (unsigned short)q->type, (unsigned short)d->class); else if(q->nexttry > 0 && (nextbest == 0 || q->nexttry < nextbest)) nextbest = q->nexttry; // include known answers, update questions for(q = d->qlist; q != 0; q = q->list) { if(q->nexttry == 0 || q->nexttry > d->now.tv_sec) continue; if(q->tries == 3) { // done retrying, expire and reset _c_expire(d,&d->cache[_namehash_nocase(q->name) % LPRIME]); _q_reset(d,q); continue; } ret++; q->nexttry = d->now.tv_sec + ++q->tries; if(nextbest == 0 || q->nexttry < nextbest) nextbest = q->nexttry; // if room, add all known good entries c = 0; while((c = _c_next(d,c,q->name,q->type)) != 0 && c->rr.ttl > d->now.tv_sec + 8 /* && message_packet_len(m) + _rr_len(&c->rr) < d->frame */) { _a_copy(m->answerRecords, (unsigned char *)q->name, (unsigned short)q->type, (unsigned short)d->class, (unsigned long int)(c->rr.ttl - d->now.tv_sec), &c->rr); } } d->checkqlist = nextbest; } if(d->now.tv_sec > d->expireall) _gc(d); end: if(ret) *_m = m; else jdns_packet_delete(m); return ret; } struct mytimeval *mdnsd_sleep(mdnsd d) { int sec, usec; //mdnsdr r; d->sleep.tv_sec = d->sleep.tv_usec = 0; #define RET while(d->sleep.tv_usec > 1000000) {d->sleep.tv_sec++;d->sleep.tv_usec -= 1000000;} return &d->sleep; // first check for any immediate items to handle if(d->uanswers || d->a_now) return &d->sleep; mygettimeofday(d, &d->now); if(d->a_pause) { // then check for paused answers if((usec = _tvdiff(d->now,d->pause)) > 0) d->sleep.tv_usec = usec; RET; } if(d->probing) { // now check for probe retries if((usec = _tvdiff(d->now,d->probe)) > 0) d->sleep.tv_usec = usec; RET; } if(d->a_publish) { // now check for publish retries if((usec = _tvdiff(d->now,d->publish)) > 0) d->sleep.tv_usec = usec; RET; } if(d->checkqlist) { // also check for queries with known answer expiration/retry if((sec = d->checkqlist - d->now.tv_sec) > 0) d->sleep.tv_sec = sec; RET; } // last resort, next gc expiration if((sec = d->expireall - d->now.tv_sec) > 0) d->sleep.tv_sec = sec; RET; } void mdnsd_query(mdnsd d, char *host, int type, int (*answer)(mdnsda a, void *arg), void *arg) { struct query *q; struct cached *cur = 0; int i = _namehash_nocase(host) % SPRIME; if(!(q = _q_next(d,0,host,type))) { if(!answer) return; q = (struct query *)jdns_alloc(sizeof(struct query)); bzero(q,sizeof(struct query)); q->name = jdns_strdup(host); q->type = type; q->next = d->queries[i]; q->list = d->qlist; d->qlist = d->queries[i] = q; q->answer = answer; q->arg = arg; while((cur = _c_next(d,cur,q->name,q->type))) { cur->q = q; // any cached entries should be associated _q_answer(d,cur); // and reported! } _q_reset(d,q); q->nexttry = d->checkqlist = d->now.tv_sec; // new questin, immediately send out return; } if(!answer) { // no answer means we don't care anymore _q_done(d,q); return; } q->answer = answer; q->arg = arg; } mdnsda mdnsd_list(mdnsd d, char *host, int type, mdnsda last) { return (mdnsda)_c_next(d,(struct cached *)last,host,type); } mdnsdr mdnsd_shared(mdnsd d, char *host, int type, long int ttl) { int i = _namehash_nocase(host) % SPRIME; mdnsdr r; r = (mdnsdr)jdns_alloc(sizeof(struct mdnsdr_struct)); bzero(r,sizeof(struct mdnsdr_struct)); r->rr.name = (unsigned char *)jdns_strdup(host); r->rr.type = type; r->rr.ttl = ttl; r->next = d->published[i]; d->published[i] = r; return r; } mdnsdr mdnsd_unique(mdnsd d, char *host, int type, long int ttl, void (*pubresult)(int result, char *host, int type, void *arg), void *arg) { mdnsdr r; r = mdnsd_shared(d,host,type,ttl); r->pubresult = pubresult; r->arg = arg; r->unique = 1; _r_push(&d->probing,r); d->probe.tv_sec = d->now.tv_sec; d->probe.tv_usec = d->now.tv_usec; return r; } void mdnsd_done(mdnsd d, mdnsdr r) { mdnsdr cur; if(r->unique && r->unique < 5) { // probing yet, zap from that list first! if(d->probing == r) d->probing = r->list; else { for(cur=d->probing;cur->list != r;cur = cur->list); cur->list = r->list; } _r_done(d,r); return; } r->rr.ttl = 0; _r_send(d,r); } void mdnsd_set_raw(mdnsd d, mdnsdr r, char *data, int len) { if(r->rr.rdata) jdns_free(r->rr.rdata); r->rr.rdata = jdns_copy_array((unsigned char*)data, len); r->rr.rdlen = len; _r_publish(d,r); } void mdnsd_set_host(mdnsd d, mdnsdr r, char *name) { jdns_free(r->rr.rdname); r->rr.rdname = (unsigned char *)jdns_strdup(name); _r_publish(d,r); } void mdnsd_set_ip(mdnsd d, mdnsdr r, unsigned long int ip) { r->rr.ip = ip; _r_publish(d,r); } void mdnsd_set_srv(mdnsd d, mdnsdr r, int priority, int weight, int port, char *name) { r->rr.srv.priority = priority; r->rr.srv.weight = weight; r->rr.srv.port = port; mdnsd_set_host(d,r,name); } zurl-1.0.0/src/jdns/jdns_mdnsd.h000066400000000000000000000107311220152020200165110ustar00rootroot00000000000000/* * Copyright (C) 2005 Jeremie Miller * Copyright (C) 2005,2006 Justin Karneges * * 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. */ #ifndef JDNS_MDNSD_H #define JDNS_MDNSD_H #include "jdns_p.h" struct mytimeval { unsigned long int tv_sec; /* seconds */ unsigned long int tv_usec; /* microseconds */ }; typedef struct mdnsd_struct *mdnsd; // main daemon data typedef struct mdnsdr_struct *mdnsdr; // record entry // answer data typedef struct mdnsda_struct { unsigned char *name; unsigned short int type; unsigned long int ttl; unsigned long int real_ttl; unsigned short int rdlen; unsigned char *rdata; unsigned long int ip; // A unsigned char *rdname; // NS/CNAME/PTR/SRV struct { unsigned short int priority, weight, port; } srv; // SRV } *mdnsda; /////////// // Global functions // // create a new mdns daemon for the given class of names (usually 1) and maximum frame size mdnsd mdnsd_new(int class, int frame, int port, int (*time_now)(mdnsd d, void *arg), int (*rand_int)(mdnsd d, void *arg), void *arg); // // gracefully shutdown the daemon, use mdnsd_out() to get the last packets void mdnsd_shutdown(mdnsd d); // // flush all cached records (network/interface changed) void mdnsd_flush(mdnsd d); // // free given mdnsd (should have used mdnsd_shutdown() first!) void mdnsd_free(mdnsd d); // /////////// /////////// // I/O functions // // incoming message from host (to be cached/processed) void mdnsd_in(mdnsd d, const jdns_packet_t *m, const jdns_response_t *resp, const jdns_address_t *addr, unsigned short int port); // // outgoing messge to be delivered to host, returns >0 if one was returned and m/ip/port set int mdnsd_out(mdnsd d, jdns_packet_t **m, jdns_address_t **addr, unsigned short int *port); // // returns the max wait-time until mdnsd_out() needs to be called again struct mytimeval *mdnsd_sleep(mdnsd d); // //////////// /////////// // Q/A functions // // register a new query // answer(record, arg) is called whenever one is found/changes/expires (immediate or anytime after, mdnsda valid until ->ttl==0) // either answer returns -1, or another mdnsd_query with a NULL answer will remove/unregister this query void mdnsd_query(mdnsd d, char *host, int type, int (*answer)(mdnsda a, void *arg), void *arg); // // returns the first (if last == NULL) or next answer after last from the cache // mdnsda only valid until an I/O function is called mdnsda mdnsd_list(mdnsd d, char *host, int type, mdnsda last); // /////////// /////////// // Publishing functions // // create a new unique record (try mdnsda_list first to make sure it's not used) // conflict(arg) called at any point when one is detected and unable to recover // after the first data is set_*(), any future changes effectively expire the old one and attempt to create a new unique record mdnsdr mdnsd_unique(mdnsd d, char *host, int type, long int ttl, void (*pubresult)(int result, char *host, int type, void *arg), void *arg); // // create a new shared record mdnsdr mdnsd_shared(mdnsd d, char *host, int type, long int ttl); // // de-list the given record void mdnsd_done(mdnsd d, mdnsdr r); // // these all set/update the data for the given record, nothing is published until they are called void mdnsd_set_raw(mdnsd d, mdnsdr r, char *data, int len); void mdnsd_set_host(mdnsd d, mdnsdr r, char *name); void mdnsd_set_ip(mdnsd d, mdnsdr r, unsigned long int ip); void mdnsd_set_srv(mdnsd d, mdnsdr r, int priority, int weight, int port, char *name); // /////////// #endif zurl-1.0.0/src/jdns/jdns_p.h000066400000000000000000000065611220152020200156510ustar00rootroot00000000000000/* * Copyright (C) 2005-2008 Justin Karneges * * 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. */ #ifndef JDNS_P_H #define JDNS_P_H #include #include #include #include #include #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) # define JDNS_OS_WIN #else # define JDNS_OS_UNIX #endif #if defined(__FreeBSD__) || defined(__DragonFly__) # define JDNS_OS_FREEBSD #elif defined(__NetBSD__) # define JDNS_OS_NETBSD #elif defined(sun) || defined(__sun) # define JDNS_OS_SOLARIS #elif defined(__APPLE__) && (defined(__GNUC__) || defined(__xlC__) || defined(__xlc__)) # define JDNS_OS_MAC #endif #ifdef JDNS_OS_WIN # include #endif #ifdef JDNS_OS_UNIX # include # include #endif #include "jdns.h" #include "jdns_packet.h" // jdns_util.c void *jdns_alloc(int size); void *jdns_realloc(void *p, int size); void jdns_free(void *p); char *jdns_strdup(const char *s); unsigned char *jdns_copy_array(const unsigned char *src, int size); int jdns_domain_cmp(const unsigned char *a, const unsigned char *b); int jdns_sprintf_s(char *str, int n, const char *format, ...); int jdns_vsprintf_s(char *str, int n, const char *format, va_list ap); FILE *jdns_fopen(const char *path, const char *mode); jdns_string_t *jdns_getenv(const char *name); char *jdns_strcpy(char *dst, const char *src); int jdns_string_indexOf(const jdns_string_t *s, unsigned char c, int pos); jdns_stringlist_t *jdns_string_split(const jdns_string_t *s, unsigned char sep); jdns_dnshost_t *jdns_dnshost_new(); jdns_dnshost_t *jdns_dnshost_copy(const jdns_dnshost_t *a); void jdns_dnshost_delete(jdns_dnshost_t *a); jdns_dnshostlist_t *jdns_dnshostlist_new(); jdns_dnshostlist_t *jdns_dnshostlist_copy(const jdns_dnshostlist_t *a); void jdns_dnshostlist_delete(jdns_dnshostlist_t *a); void jdns_dnshostlist_append(jdns_dnshostlist_t *a, const jdns_dnshost_t *host); jdns_rr_t *jdns_rr_from_resource(const jdns_packet_resource_t *pr, const jdns_packet_t *ref); void jdns_response_remove_extra(jdns_response_t *r); void jdns_response_remove_answer(jdns_response_t *r, int pos); #define alloc_type(type) (type *)jdns_alloc(sizeof(type)) #define _ustrdup(str) (unsigned char *)jdns_strdup((const char *)str) #define _ustrlen(str) strlen((const char *)str) #define _ustrcmp(a, b) strcmp((const char *)a, (const char *)b) #endif zurl-1.0.0/src/jdns/jdns_packet.c000066400000000000000000000554271220152020200166610ustar00rootroot00000000000000/* * Copyright (C) 2006 Justin Karneges * * 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. */ #include "jdns_packet.h" #include "jdns_p.h" // maximum length of a sublabel #define MAX_SUBLABEL_LENGTH 63 // maximum length of a label, including final terminating zero (root sublabel) // according to RFC 2181, the maximum length is 255, not counting the root // sublabel. so, with the root sublabel, that means a max length of 256. #define MAX_LABEL_LENGTH 256 // jer's endian functions static unsigned short int net2short(const unsigned char **bufp) { unsigned short int i; i = **bufp; i <<= 8; i |= *(*bufp + 1); *bufp += 2; return i; } static unsigned long int net2long(const unsigned char **bufp) { unsigned long int l; l = **bufp; l <<= 8; l |= *(*bufp + 1); l <<= 8; l |= *(*bufp + 2); l <<= 8; l |= *(*bufp + 3); *bufp += 4; return l; } static void short2net(unsigned short int i, unsigned char **bufp) { *(*bufp + 1) = (unsigned char)i; i >>= 8; **bufp = (unsigned char)i; *bufp += 2; } static void long2net(unsigned long int l, unsigned char **bufp) { *(*bufp + 3) = (unsigned char)l; l >>= 8; *(*bufp + 2) = (unsigned char)l; l >>= 8; *(*bufp + 1) = (unsigned char)l; l >>= 8; **bufp = (unsigned char)l; *bufp += 4; } // label stuff typedef struct jdns_packet_label { JDNS_OBJECT int offset; jdns_string_t *value; } jdns_packet_label_t; static void jdns_packet_label_delete(jdns_packet_label_t *a); static jdns_packet_label_t *jdns_packet_label_copy(const jdns_packet_label_t *a); static jdns_packet_label_t *jdns_packet_label_new() { jdns_packet_label_t *a = JDNS_OBJECT_NEW(jdns_packet_label); a->offset = 0; a->value = 0; return a; } jdns_packet_label_t *jdns_packet_label_copy(const jdns_packet_label_t *a) { jdns_packet_label_t *c = jdns_packet_label_new(); c->offset = a->offset; if(a->value) c->value = jdns_string_copy(a->value); return c; } void jdns_packet_label_delete(jdns_packet_label_t *a) { if(!a) return; jdns_string_delete(a->value); jdns_object_free(a); } // gets an offset for decompression. does range and hop count checking also static int getoffset(const unsigned char *str, int refsize, int *hopsleft) { unsigned short int x; if(*hopsleft <= 0) return -1; --(*hopsleft); x = str[0] & 0x3f; x <<= 8; x |= str[1]; // stay in bounds if(x >= refsize) return -1; return x; } static int readlabel(const unsigned char *in, int insize, const unsigned char *ref, int refsize, int *_at, jdns_string_t **name) { int at; // string format is one character smaller than dns format. e.g.: // dns: [7] affinix [3] com [0] = 13 bytes // string: "affinix.com." = 12 bytes // only exception is '.' itself, but that won't influence the max. unsigned char out[MAX_LABEL_LENGTH - 1]; int out_size; const unsigned char *label, *last; int hopped_yet; int hopsleft; int label_size; at = *_at; // stay in range if(at < 0 || at >= insize) return 0; out_size = 0; label = in + at; hopped_yet = 0; last = in + insize; while(1) { // need a byte if(label + 1 > last) goto error; // we make this a while loop instead of an 'if', in case // there's a pointer to a pointer. as a precaution, // we will hop no more than 8 times hopsleft = 8; while(*label & 0xc0) { int offset; // need the next byte, too if(label + 2 > last) goto error; offset = getoffset(label, refsize, &hopsleft); if(offset == -1) goto error; label = ref + offset; if(!hopped_yet) { at += 2; hopped_yet = 1; last = ref + refsize; } // need a byte if(label + 1 > last) goto error; } label_size = *label & 0x3f; // null label? then we're done if(label_size == 0) { if(!hopped_yet) ++at; break; } // enough source bytes? (length byte + length) if(label + label_size + 1 > last) goto error; // enough dest bytes? (length + dot) if(out_size + label_size + 1 > MAX_LABEL_LENGTH - 1) goto error; memcpy(out + out_size, label + 1, label_size); out_size += label_size; out[out_size] = '.'; ++out_size; if(!hopped_yet) at += label_size + 1; label += label_size + 1; } *_at = at; *name = jdns_string_new(); jdns_string_set(*name, out, out_size); return 1; error: return 0; } // this function compares labels in label format: // [length] [value ...] [length] [value ...] [0] static int matchlabel(const unsigned char *a, int asize, const unsigned char *b, int bsize, const unsigned char *ref, int refsize, int ahopsleft, int bhopsleft) { int n, alen, blen, offset; // same pointer? if(a == b) return 1; if(asize < 1 || bsize < 1) return 0; // always ensure we get called without a pointer if(*a & 0xc0) { if(asize < 2) return 0; offset = getoffset(a, refsize, &ahopsleft); if(offset == -1) return 0; return matchlabel(ref + offset, refsize - offset, b, bsize, ref, refsize, ahopsleft, bhopsleft); } if(*b & 0xc0) { if(bsize < 2) return 0; offset = getoffset(b, refsize, &bhopsleft); if(offset == -1) return 0; return matchlabel(a, asize, ref + offset, refsize - offset, ref, refsize, ahopsleft, bhopsleft); } alen = *a & 0x3f; blen = *b & 0x3f; // must be same length if(alen != blen) return 0; // done? if(alen == 0) return 1; // length byte + length + first byte of next label if(asize < alen + 2) return 0; if(bsize < blen + 2) return 0; // compare the value for(n = 1; n < alen + 1; ++n) { if(a[n] != b[n]) return 0; } // try next labels n = alen + 1; return matchlabel(a + n, asize - n, b + n, bsize - n, ref, refsize, ahopsleft, bhopsleft); } int jdns_packet_name_isvalid(const unsigned char *name, int size) { int n, at, len; // at least one byte, no larger than MAX_LABEL_LENGTH - 1 (one byte is // gained when converting to a label) if(size < 1 || size > (MAX_LABEL_LENGTH - 1)) return 0; // last byte must be a dot if(name[size - 1] != '.') return 0; // first byte can't be a dot if there are characters after if(size > 1 && name[0] == '.') return 0; // each sublabel must be between 1 and MAX_SUBLABEL_LENGTH in length at = 0; while(1) { // search for dot or end for(n = at; n < size; ++n) { if(name[n] == '.') break; } // length of last one is always zero if(n >= size) break; len = n - at; if(len < 1 || len > MAX_SUBLABEL_LENGTH) return 0; at = n + 1; // skip over the dot } return 1; } // this function assumes label is pointing to a MAX_LABEL_LENGTH byte buffer static int name_to_label(const jdns_string_t *name, unsigned char *label) { int n, i, at, len; if(!jdns_packet_name_isvalid(name->data, name->size)) return -1; if(name->size == 1) { label[0] = 0; return 1; } at = 0; i = 0; while(1) { // search for dot or end for(n = at; n < name->size; ++n) { if(name->data[n] == '.') break; } len = n - at; if(i + (len + 1) > MAX_LABEL_LENGTH) // length byte + length return 0; label[i++] = len; memcpy(label + i, name->data + at, len); i += len; if(n >= name->size) // end? break; at = n + 1; // skip over the dot } return i; } // lookup list is made of jdns_packet_labels static int writelabel(const jdns_string_t *name, int at, int left, unsigned char **bufp, jdns_list_t *lookup) { unsigned char label[MAX_LABEL_LENGTH]; int n, i, len; unsigned char *l; unsigned char *ref; int refsize; len = name_to_label(name, label); if(len == -1) return 0; ref = *bufp - at; refsize = at + left; for(n = 0; label[n]; n += label[n] + 1) { for(i = 0; i < lookup->count; ++i) { jdns_packet_label_t *pl = (jdns_packet_label_t *)lookup->item[i]; if(matchlabel(label + n, len - n, pl->value->data, pl->value->size, ref, refsize, 8, 8)) { // set up a pointer right here, overwriting // the length byte and the first content // byte of this section within 'label'. // this is safe, because the length value // will always be greater than zero, // ensuring we have two bytes available to // use. l = label + n; short2net((unsigned short int)pl->offset, &l); label[n] |= 0xc0; len = n + 2; // cut things short break; } } if(label[n] & 0xc0) // double loop, so break again break; } if(left < len) return 0; // copy into buffer, point there now memcpy(*bufp, label, len); l = *bufp; *bufp += len; // for each new label, store its location for future compression for(n = 0; l[n]; n += l[n] + 1) { jdns_string_t *str; jdns_packet_label_t *pl; if(l[n] & 0xc0) break; pl = jdns_packet_label_new(); str = jdns_string_new(); jdns_string_set(str, l + n, len - n); pl->offset = l + n - ref; pl->value = str; jdns_list_insert(lookup, pl, -1); } return 1; } //---------------------------------------------------------------------------- // jdns_packet_write //---------------------------------------------------------------------------- #define JDNS_PACKET_WRITE_RAW 0 #define JDNS_PACKET_WRITE_NAME 1 struct jdns_packet_write { JDNS_OBJECT int type; jdns_string_t *value; }; void jdns_packet_write_delete(jdns_packet_write_t *a); jdns_packet_write_t *jdns_packet_write_copy(const jdns_packet_write_t *a); jdns_packet_write_t *jdns_packet_write_new() { jdns_packet_write_t *a = JDNS_OBJECT_NEW(jdns_packet_write); a->type = 0; a->value = 0; return a; } jdns_packet_write_t *jdns_packet_write_copy(const jdns_packet_write_t *a) { jdns_packet_write_t *c = jdns_packet_write_new(); c->type = a->type; if(a->value) c->value = jdns_string_copy(a->value); return c; } void jdns_packet_write_delete(jdns_packet_write_t *a) { if(!a) return; jdns_string_delete(a->value); jdns_object_free(a); } //---------------------------------------------------------------------------- // jdns_packet_question //---------------------------------------------------------------------------- jdns_packet_question_t *jdns_packet_question_new() { jdns_packet_question_t *a = JDNS_OBJECT_NEW(jdns_packet_question); a->qname = 0; a->qtype = 0; a->qclass = 0; return a; } jdns_packet_question_t *jdns_packet_question_copy(const jdns_packet_question_t *a) { jdns_packet_question_t *c = jdns_packet_question_new(); if(a->qname) c->qname = jdns_string_copy(a->qname); c->qtype = a->qtype; c->qclass = a->qclass; return c; } void jdns_packet_question_delete(jdns_packet_question_t *a) { if(!a) return; jdns_string_delete(a->qname); jdns_object_free(a); } //---------------------------------------------------------------------------- // jdns_packet_resource //---------------------------------------------------------------------------- jdns_packet_resource_t *jdns_packet_resource_new() { jdns_packet_resource_t *a = JDNS_OBJECT_NEW(jdns_packet_resource); a->qname = 0; a->qtype = 0; a->qclass = 0; a->ttl = 0; a->rdlength = 0; a->rdata = 0; a->writelog = jdns_list_new(); a->writelog->valueList = 1; return a; } jdns_packet_resource_t *jdns_packet_resource_copy(const jdns_packet_resource_t *a) { jdns_packet_resource_t *c = jdns_packet_resource_new(); if(a->qname) c->qname = jdns_string_copy(a->qname); c->qtype = a->qtype; c->qclass = a->qclass; c->ttl = a->ttl; c->rdlength = a->rdlength; c->rdata = jdns_copy_array(a->rdata, a->rdlength); jdns_list_delete(c->writelog); c->writelog = jdns_list_copy(a->writelog); return c; } void jdns_packet_resource_delete(jdns_packet_resource_t *a) { if(!a) return; jdns_string_delete(a->qname); if(a->rdata) jdns_free(a->rdata); jdns_list_delete(a->writelog); jdns_object_free(a); } void jdns_packet_resource_add_bytes(jdns_packet_resource_t *a, const unsigned char *data, int size) { jdns_packet_write_t *write = jdns_packet_write_new(); write->type = JDNS_PACKET_WRITE_RAW; write->value = jdns_string_new(); jdns_string_set(write->value, data, size); jdns_list_insert_value(a->writelog, write, -1); jdns_packet_write_delete(write); } void jdns_packet_resource_add_name(jdns_packet_resource_t *a, const jdns_string_t *name) { jdns_packet_write_t *write = jdns_packet_write_new(); write->type = JDNS_PACKET_WRITE_NAME; write->value = jdns_string_copy(name); jdns_list_insert_value(a->writelog, write, -1); jdns_packet_write_delete(write); } int jdns_packet_resource_read_name(const jdns_packet_resource_t *a, const jdns_packet_t *p, int *at, jdns_string_t **name) { return readlabel(a->rdata, a->rdlength, p->raw_data, p->raw_size, at, name); } //---------------------------------------------------------------------------- // jdns_packet //---------------------------------------------------------------------------- // note: both process_qsection and process_rrsection modify the 'dest' list, // even if later items cause an error. this turns out to be convenient // for handling truncated dns packets static int process_qsection(jdns_list_t *dest, int count, const unsigned char *data, int size, const unsigned char **bufp) { int n; int offset, at; jdns_string_t *name = 0; const unsigned char *buf; buf = *bufp; for(n = 0; n < count; ++n) { jdns_packet_question_t *q; offset = buf - data; at = 0; if(!readlabel(data + offset, size - offset, data, size, &at, &name)) goto error; offset += at; // need 4 more bytes if(size - offset < 4) goto error; buf = data + offset; q = jdns_packet_question_new(); q->qname = name; name = 0; q->qtype = net2short(&buf); q->qclass = net2short(&buf); jdns_list_insert_value(dest, q, -1); jdns_packet_question_delete(q); } *bufp = buf; return 1; error: jdns_string_delete(name); return 0; } static int process_rrsection(jdns_list_t *dest, int count, const unsigned char *data, int size, const unsigned char **bufp) { int n; int offset, at; jdns_string_t *name = 0; const unsigned char *buf; buf = *bufp; for(n = 0; n < count; ++n) { jdns_packet_resource_t *r; offset = buf - data; at = 0; if(!readlabel(data + offset, size - offset, data, size, &at, &name)) goto error; offset += at; // need 10 more bytes if(offset + 10 > size) goto error; buf = data + offset; r = jdns_packet_resource_new(); r->qname = name; name = 0; r->qtype = net2short(&buf); r->qclass = net2short(&buf); r->ttl = net2long(&buf); // per RFC 2181, ttl is supposed to be a 31 bit number. if // the top bit of the 32 bit field is 1, then entire ttl is // to be considered 0. if(r->ttl & 0x80000000) r->ttl = 0; r->rdlength = net2short(&buf); offset = buf - data; // make sure we have enough for the rdata if(size - offset < r->rdlength) { jdns_packet_resource_delete(r); goto error; } r->rdata = jdns_copy_array(buf, r->rdlength); buf += r->rdlength; jdns_list_insert_value(dest, r, -1); jdns_packet_resource_delete(r); } *bufp = buf; return 1; error: jdns_string_delete(name); return 0; } static int append_qsection(const jdns_list_t *src, int at, int left, unsigned char **bufp, jdns_list_t *lookup) { unsigned char *buf, *start, *last; int n; buf = *bufp; start = buf - at; last = buf + left; for(n = 0; n < src->count; ++n) { jdns_packet_question_t *q = (jdns_packet_question_t *)src->item[n]; if(!writelabel(q->qname, buf - start, last - buf, &buf, lookup)) goto error; if(buf + 4 > last) goto error; short2net(q->qtype, &buf); short2net(q->qclass, &buf); } *bufp = buf; return 1; error: return 0; } static int append_rrsection(const jdns_list_t *src, int at, int left, unsigned char **bufp, jdns_list_t *lookup) { unsigned char *buf, *start, *last, *rdlengthp; int n, i; buf = *bufp; start = buf - at; last = buf + left; for(n = 0; n < src->count; ++n) { jdns_packet_resource_t *r = (jdns_packet_resource_t *)src->item[n]; if(!writelabel(r->qname, buf - start, last - buf, &buf, lookup)) goto error; if(buf + 10 > last) goto error; short2net(r->qtype, &buf); short2net(r->qclass, &buf); long2net(r->ttl, &buf); // skip over rdlength rdlengthp = buf; buf += 2; // play write log for(i = 0; i < r->writelog->count; ++i) { jdns_packet_write_t *write = (jdns_packet_write_t *)r->writelog->item[i]; if(write->type == JDNS_PACKET_WRITE_RAW) { if(buf + write->value->size > last) goto error; memcpy(buf, write->value->data, write->value->size); buf += write->value->size; } else // JDNS_PACKET_WRITE_NAME { if(!writelabel(write->value, buf - start, last - buf, &buf, lookup)) goto error; } } i = buf - rdlengthp; // should be rdata size + 2 short2net((unsigned short int)(i - 2), &rdlengthp); } *bufp = buf; return 1; error: return 0; } jdns_packet_t *jdns_packet_new() { jdns_packet_t *a = JDNS_OBJECT_NEW(jdns_packet); a->id = 0; a->opts.qr = 0; a->opts.opcode = 0; a->opts.aa = 0; a->opts.tc = 0; a->opts.rd = 0; a->opts.ra = 0; a->opts.z = 0; a->opts.rcode = 0; a->questions = jdns_list_new(); a->answerRecords = jdns_list_new(); a->authorityRecords = jdns_list_new(); a->additionalRecords = jdns_list_new(); a->questions->valueList = 1; a->answerRecords->valueList = 1; a->authorityRecords->valueList = 1; a->additionalRecords->valueList = 1; a->fully_parsed = 0; a->raw_size = 0; a->raw_data = 0; return a; } jdns_packet_t *jdns_packet_copy(const jdns_packet_t *a) { jdns_packet_t *c = jdns_packet_new(); c->id = a->id; c->opts.qr = a->opts.qr; c->opts.opcode = a->opts.opcode; c->opts.aa = a->opts.aa; c->opts.tc = a->opts.tc; c->opts.rd = a->opts.rd; c->opts.ra = a->opts.ra; c->opts.z = a->opts.z; c->opts.rcode = a->opts.rcode; jdns_list_delete(c->questions); jdns_list_delete(c->answerRecords); jdns_list_delete(c->authorityRecords); jdns_list_delete(c->additionalRecords); c->questions = jdns_list_copy(a->questions); c->answerRecords = jdns_list_copy(a->answerRecords); c->authorityRecords = jdns_list_copy(a->authorityRecords); c->additionalRecords = jdns_list_copy(a->additionalRecords); c->fully_parsed = a->fully_parsed; c->raw_size = a->raw_size; c->raw_data = jdns_copy_array(a->raw_data, a->raw_size); return c; } void jdns_packet_delete(jdns_packet_t *a) { if(!a) return; jdns_list_delete(a->questions); jdns_list_delete(a->answerRecords); jdns_list_delete(a->authorityRecords); jdns_list_delete(a->additionalRecords); if(a->raw_data) jdns_free(a->raw_data); jdns_object_free(a); } int jdns_packet_import(jdns_packet_t **a, const unsigned char *data, int size) { jdns_packet_t *tmp = 0; const unsigned char *buf; // need at least some data if(!data || size == 0) return 0; // header (id + options + item counts) is 12 bytes if(size < 12) goto error; tmp = jdns_packet_new(); buf = data; // id tmp->id = net2short(&buf); // options if(buf[0] & 0x80) // qr is bit 7 tmp->opts.qr = 1; tmp->opts.opcode = (buf[0] & 0x78) >> 3; // opcode is bits 6,5,4,3 if(buf[0] & 0x04) // aa is bit 2 tmp->opts.aa = 1; if(buf[0] & 0x02) // tc is bit 1 tmp->opts.tc = 1; if(buf[0] & 0x01) // rd is bit 0 tmp->opts.rd = 1; if(buf[1] & 0x80) // ra is bit 7 (second byte) tmp->opts.ra = 1; tmp->opts.z = (buf[1] & 0x70) >> 4; // z is bits 6,5,4 tmp->opts.rcode = buf[1] & 0x0f; // rcode is bits 3,2,1,0 buf += 2; // item counts tmp->qdcount = net2short(&buf); tmp->ancount = net2short(&buf); tmp->nscount = net2short(&buf); tmp->arcount = net2short(&buf); // if these fail, we don't count them as errors, since the packet // might have been truncated if(!process_qsection(tmp->questions, tmp->qdcount, data, size, &buf)) goto skip; if(!process_rrsection(tmp->answerRecords, tmp->ancount, data, size, &buf)) goto skip; if(!process_rrsection(tmp->authorityRecords, tmp->nscount, data, size, &buf)) goto skip; if(!process_rrsection(tmp->additionalRecords, tmp->arcount, data, size, &buf)) goto skip; tmp->fully_parsed = 1; skip: // keep the raw data for reference during rdata parsing tmp->raw_size = size; tmp->raw_data = jdns_copy_array(data, size); *a = tmp; return 1; error: jdns_packet_delete(tmp); return 0; } int jdns_packet_export(jdns_packet_t *a, int maxsize) { unsigned char *block = 0; unsigned char *buf, *last; unsigned char c; int size; jdns_list_t *lookup = 0; // to hold jdns_packet_label_t // clear out any existing raw data before we begin if(a->raw_data) { jdns_free(a->raw_data); a->raw_data = 0; a->raw_size = 0; } // preallocate size = maxsize; block = (unsigned char *)jdns_alloc(size); memset(block, 0, size); buf = block; last = block + size; if(size < 12) goto error; short2net(a->id, &buf); if(a->opts.qr) buf[0] |= 0x80; c = (unsigned char)a->opts.opcode; buf[0] |= c << 3; if(a->opts.aa) buf[0] |= 0x04; if(a->opts.tc) buf[0] |= 0x02; if(a->opts.rd) buf[0] |= 0x01; if(a->opts.ra) buf[1] |= 0x80; c = (unsigned char)a->opts.z; buf[1] |= c << 4; c = (unsigned char)a->opts.rcode; buf[1] |= c; buf += 2; short2net((unsigned short int)a->questions->count, &buf); short2net((unsigned short int)a->answerRecords->count, &buf); short2net((unsigned short int)a->authorityRecords->count, &buf); short2net((unsigned short int)a->additionalRecords->count, &buf); // append sections lookup = jdns_list_new(); lookup->autoDelete = 1; if(!append_qsection(a->questions, buf - block, last - buf, &buf, lookup)) goto error; if(!append_rrsection(a->answerRecords, buf - block, last - buf, &buf, lookup)) goto error; if(!append_rrsection(a->authorityRecords, buf - block, last - buf, &buf, lookup)) goto error; if(!append_rrsection(a->additionalRecords, buf - block, last - buf, &buf, lookup)) goto error; // done with all sections jdns_list_delete(lookup); // condense size = buf - block; block = (unsigned char *)jdns_realloc(block, size); // finalize a->qdcount = a->questions->count; a->ancount = a->answerRecords->count; a->nscount = a->authorityRecords->count; a->arcount = a->additionalRecords->count; a->raw_data = block; a->raw_size = size; return 1; error: jdns_list_delete(lookup); if(block) jdns_free(block); return 0; } zurl-1.0.0/src/jdns/jdns_packet.h000066400000000000000000000101101220152020200166420ustar00rootroot00000000000000/* * Copyright (C) 2006 Justin Karneges * * 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. */ #ifndef JDNS_PACKET_H #define JDNS_PACKET_H #include "jdns.h" // -- howto -- // // writing packets: // 1) call jdns_packet_new() // 2) populate the jdns_packet_t structure, using the functions // as necessary // 3) call jdns_packet_export() to populate the raw data of the packet // // reading packets: // 1) call jdns_packet_new() // 2) call jdns_packet_import() with the raw data // 3) the jdns_packet_t structure is now populated // // IMPORTANT: all names must be valid. that is, ending in a dot character int jdns_packet_name_isvalid(const unsigned char *name, int size); // 0 if not valid typedef struct jdns_packet_question { JDNS_OBJECT jdns_string_t *qname; unsigned short int qtype, qclass; } jdns_packet_question_t; jdns_packet_question_t *jdns_packet_question_new(); jdns_packet_question_t *jdns_packet_question_copy(const jdns_packet_question_t *a); void jdns_packet_question_delete(jdns_packet_question_t *a); typedef struct jdns_packet_write jdns_packet_write_t; typedef struct jdns_packet jdns_packet_t; typedef struct jdns_packet_resource { JDNS_OBJECT jdns_string_t *qname; unsigned short int qtype, qclass; unsigned long int ttl; // 31-bit number, top bit always 0 unsigned short int rdlength; unsigned char *rdata; // private jdns_list_t *writelog; // jdns_packet_write_t } jdns_packet_resource_t; jdns_packet_resource_t *jdns_packet_resource_new(); jdns_packet_resource_t *jdns_packet_resource_copy(const jdns_packet_resource_t *a); void jdns_packet_resource_delete(jdns_packet_resource_t *a); void jdns_packet_resource_add_bytes(jdns_packet_resource_t *a, const unsigned char *data, int size); void jdns_packet_resource_add_name(jdns_packet_resource_t *a, const jdns_string_t *name); int jdns_packet_resource_read_name(const jdns_packet_resource_t *a, const jdns_packet_t *p, int *at, jdns_string_t **name); struct jdns_packet { JDNS_OBJECT unsigned short int id; struct { unsigned short qr, opcode, aa, tc, rd, ra, z, rcode; } opts; // item counts as specified by the packet. do not use these // for iteration over the item lists, since they can be wrong // if the packet is truncated. int qdcount, ancount, nscount, arcount; // value lists jdns_list_t *questions; // jdns_packet_question_t jdns_list_t *answerRecords; // jdns_packet_resource_t jdns_list_t *authorityRecords; // jdns_packet_resource_t jdns_list_t *additionalRecords; // jdns_packet_resource_t // since dns packets are allowed to be truncated, it is possible // for a packet to not get fully parsed yet still be considered // successfully parsed. this flag means the packet was fully // parsed also. int fully_parsed; int raw_size; unsigned char *raw_data; }; jdns_packet_t *jdns_packet_new(); jdns_packet_t *jdns_packet_copy(const jdns_packet_t *a); void jdns_packet_delete(jdns_packet_t *a); int jdns_packet_import(jdns_packet_t **a, const unsigned char *data, int size); // 0 on fail int jdns_packet_export(jdns_packet_t *a, int maxsize); // 0 on fail #endif zurl-1.0.0/src/jdns/jdns_sys.c000066400000000000000000000477351220152020200162330ustar00rootroot00000000000000/* * Copyright (C) 2005-2008 Justin Karneges * * 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. */ /* this code probes the system for dns settings. blah. q3dns strategies ---------------- windows: domain name, name server, "search list" found in windows registry here: HKEY_LOCAL_MACHINE System\CurrentControlSet\Services\Tcpip\Parameters <-- win nt+ System\CurrentControlSet\Services\VxD\MSTCP <-- win 98 for domain, try DhcpDomain else Domain for name servers, try DhcpNameServer, else NameServer for search list, try SearchList iphlpapi.dll : GetNetworkParams(PFIXED_INFO, PULONG); info->DomainName info->DnsServerList (if not null, use it, and loop through ->Next until null) no search list first try getnetworkparams. if that fails, try the nt regkey then the 98 regkey. it seems that search list can only come from the registry, so maybe we need to grab that entry even if getnetworkparams works. in the case of the registry, the nameserver and searchlist entries are delimited by spaces on win nt and commas on win 98. probably a good idea to simplify white space first (chop away space at start and end, reduce all sections of spaces to one char). also, lowercase the search list. qt doesn't read the hosts file on windows. this might be a good idea, but probably not worth it. unix: read /etc/resolv.conf manually: for each line, split at spaces if the first item is "nameserver", then there should be an IP address following it. note: may contain mixed ipv4 and ipv6 addresses if the first item is "search", all other items are added to the domain list if the first item is "domain", then the next item should be added to the domain list. do case-insensitive matching for the item types for search/domain, the items are in the 8-bit system locale info can also be fetched using system calls. we use the res_* stuff here. first we should detect for a "modern res api". this is available from glibc 2.3 and onward. use the following scheme to check for it: #if defined(__GLIBC__) && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 3))) // modern res api #endif on mac we should look up res_init in the system library. see: qt_mac_resolve_sys(RTLD_NEXT, "res_init"); for a hint. otherwise we can just use res_init() straight. under a modern res api, we do: struct __res_state res; res_ninit(&res); otherwise, we simply call res_init(). for the modern api, we use the "res" struct that we made. otherwise, we use the global "_res" struct. read the res struct to obtain the name servers, search list, and domain. lowercase the search list and domain. qt tries the file, and if that fails it tries the syscalls. we may want to do the syscalls first, or even just do both all the time. read /etc/hosts manually: for each line if there is a '#' character in the line, remove it and everything to the right simplify white space convert to lowercase split the line at spaces first item is the ip address all remaining items are hostnames note: these hosts could also be used for reverse-dns too note2: Windows has a hosts file as well (like C:\WINDOWS\hosts) */ #include "jdns_p.h" #ifdef JDNS_OS_WIN # include #endif #ifdef JDNS_OS_UNIX # include # include # include # include #endif #define string_indexOf jdns_string_indexOf #define string_split jdns_string_split static int char_isspace(unsigned char c) { if(c == ' ' || c == '\t' || c == '\n' || c == '\r') return 1; return 0; } static unsigned char *string_getnextword(unsigned char *in, int size, int pos, int *newpos) { int n; int at; int len; unsigned char *out; at = pos; // skip any space at the start while(at < size && char_isspace(in[at])) ++at; // all space? no word then if(at >= size) return 0; // skip until a space or end n = at; while(n < size && !char_isspace(in[n])) ++n; len = n - at; // allocate length + zero byte out = (unsigned char *)jdns_alloc(len + 1); if(!out) return 0; memcpy(out, in + at, len); out[len] = 0; *newpos = at + len; return out; } static jdns_string_t *string_simplify(const jdns_string_t *in) { int n; int pos; int total; unsigned char *out; int outlen; jdns_string_t *outstr; jdns_stringlist_t *wordlist; // gather words and total of lengths pos = 0; total = 0; wordlist = jdns_stringlist_new(); while(1) { jdns_string_t *word; unsigned char *str = string_getnextword(in->data, in->size, pos, &pos); if(!str) break; word = jdns_string_new(); jdns_string_set_cstr(word, (char *)str); jdns_free(str); jdns_stringlist_append(wordlist, word); total += word->size; jdns_string_delete(word); } if(total == 0) { jdns_stringlist_delete(wordlist); outstr = jdns_string_new(); jdns_string_set_cstr(outstr, ""); return outstr; } // we need to allocate space for total lengths and wordcount-1 spaces outlen = total + (wordlist->count - 1); out = (unsigned char *)jdns_alloc(outlen); // lay out the words pos = 0; for(n = 0; n < wordlist->count; ++n) { unsigned char *data = wordlist->item[n]->data; int size = wordlist->item[n]->size; memcpy(out + pos, data, size); pos += size; // if this is not the last word, append a space if(n + 1 < wordlist->count) out[pos++] = ' '; } jdns_stringlist_delete(wordlist); outstr = jdns_string_new(); jdns_string_set(outstr, out, outlen); jdns_free(out); return outstr; } static jdns_string_t *string_tolower(const jdns_string_t *in) { int n; jdns_string_t *out = jdns_string_copy(in); for(n = 0; n < out->size; ++n) out->data[n] = tolower(out->data[n]); return out; } static jdns_string_t *file_nextline(FILE *f) { int at, size; unsigned char *buf; jdns_string_t *str; size = 1023; buf = (unsigned char *)jdns_alloc(size); at = 0; while(1) { unsigned char c = fgetc(f); if(feof(f)) { if(at > 0) { // if we read at least one char, take it as a // line break; } else { jdns_free(buf); return 0; } } if(c == '\n') break; if(c == '\r') continue; if(at < 1023) buf[at++] = c; } str = jdns_string_new(); jdns_string_set(str, buf, at); jdns_free(buf); return str; } static jdns_dnshostlist_t *read_hosts_file(const char *path) { jdns_dnshostlist_t *out; FILE *f; jdns_string_t *line, *simp; jdns_stringlist_t *parts; jdns_address_t *addr; int n; out = jdns_dnshostlist_new(); f = jdns_fopen(path, "r"); if(!f) return out; while(1) { line = file_nextline(f); if(!line) break; // truncate at comment n = string_indexOf(line, '#', 0); if(n != -1) { line->size = n; line->data[n] = 0; } simp = string_simplify(line); jdns_string_delete(line); parts = string_split(simp, ' '); jdns_string_delete(simp); if(parts->count < 2) { jdns_stringlist_delete(parts); continue; } addr = jdns_address_new(); if(!jdns_address_set_cstr(addr, (const char *)parts->item[0]->data)) { jdns_address_delete(addr); jdns_stringlist_delete(parts); continue; } for(n = 1; n < parts->count; ++n) { jdns_dnshost_t *h = jdns_dnshost_new(); h->name = jdns_string_copy(parts->item[n]); h->address = jdns_address_copy(addr); jdns_dnshostlist_append(out, h); jdns_dnshost_delete(h); } jdns_address_delete(addr); jdns_stringlist_delete(parts); } fclose(f); return out; } static void apply_hosts_file(jdns_dnsparams_t *a, const char *path) { int n; jdns_dnshostlist_t *list; list = read_hosts_file(path); for(n = 0; n < list->count; ++n) jdns_dnshostlist_append(a->hosts, list->item[n]); jdns_dnshostlist_delete(list); } static int dnsparams_have_domain(const jdns_dnsparams_t *a, const jdns_string_t *domain) { int n; for(n = 0; n < a->domains->count; ++n) { jdns_string_t *str = a->domains->item[n]; if(strcmp((const char *)str->data, (const char *)domain->data) == 0) return 1; } return 0; } #ifdef JDNS_OS_WIN // from Microsoft IPTypes.h #ifndef IP_TYPES_INCLUDED #define MAX_HOSTNAME_LEN 128 #define MAX_DOMAIN_NAME_LEN 128 #define MAX_SCOPE_ID_LEN 256 typedef struct { char String[4 * 4]; } IP_ADDRESS_STRING, *PIP_ADDRESS_STRING, IP_MASK_STRING, *PIP_MASK_STRING; typedef struct _IP_ADDR_STRING { struct _IP_ADDR_STRING* Next; IP_ADDRESS_STRING IpAddress; IP_MASK_STRING IpMask; DWORD Context; } IP_ADDR_STRING, *PIP_ADDR_STRING; typedef struct { char HostName[MAX_HOSTNAME_LEN + 4] ; char DomainName[MAX_DOMAIN_NAME_LEN + 4]; PIP_ADDR_STRING CurrentDnsServer; IP_ADDR_STRING DnsServerList; UINT NodeType; char ScopeId[MAX_SCOPE_ID_LEN + 4]; UINT EnableRouting; UINT EnableProxy; UINT EnableDns; } FIXED_INFO, *PFIXED_INFO; #endif typedef DWORD (WINAPI *GetNetworkParamsFunc)(PFIXED_INFO, PULONG); static jdns_string_t *reg_readString(HKEY hk, const char *subkey) { char *buf; DWORD bufsize; int ret; jdns_string_t *str = 0; bufsize = 1024; buf = (char *)jdns_alloc((int)bufsize); if(!buf) return 0; ret = RegQueryValueExA(hk, subkey, 0, 0, (LPBYTE)buf, &bufsize); if(ret == ERROR_MORE_DATA) { buf = (char *)jdns_realloc(buf, bufsize); if(!buf) { jdns_free(buf); return 0; } ret = RegQueryValueExA(hk, subkey, 0, 0, (LPBYTE)buf, &bufsize); } if(ret == ERROR_SUCCESS) { str = jdns_string_new(); jdns_string_set_cstr(str, (char *)buf); } jdns_free(buf); return str; } static jdns_dnsparams_t *dnsparams_get_winreg() { int n; jdns_dnsparams_t *params; HKEY key; int ret; char sep; jdns_string_t *str_domain, *str_nameserver, *str_searchlist; jdns_stringlist_t *list_nameserver, *list_searchlist; sep = ' '; ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &key); if(ret != ERROR_SUCCESS) { sep = ','; ret = RegOpenKeyExA(HKEY_LOCAL_MACHINE, "System\\CurrentControlSet\\Services\\VxD\\MSTCP", 0, KEY_READ, &key); if(ret != ERROR_SUCCESS) return 0; } str_domain = reg_readString(key, "DhcpDomain"); if(!str_domain) str_domain = reg_readString(key, "Domain"); str_nameserver = reg_readString(key, "DhcpNameServer"); if(!str_nameserver) str_nameserver = reg_readString(key, "NameServer"); str_searchlist = reg_readString(key, "SearchList"); RegCloseKey(key); list_nameserver = 0; if(str_nameserver) { list_nameserver = string_split(str_nameserver, sep); jdns_string_delete(str_nameserver); } list_searchlist = 0; if(str_searchlist) { // lowercase the string jdns_string_t *p = string_tolower(str_searchlist); jdns_string_delete(str_searchlist); str_searchlist = p; list_searchlist = string_split(str_searchlist, sep); jdns_string_delete(str_searchlist); } params = jdns_dnsparams_new(); if(list_nameserver) { // qt seems to do a strange thing here by running each name // server address through the q3dns setLabel function, and // then pulls the result as a list of addresses. i have // no idea why they do this, or how one IP address would // turn into anything else, let alone several addresses. // so, uh, we're not going to do that. for(n = 0; n < list_nameserver->count; ++n) { jdns_address_t *addr = jdns_address_new(); if(jdns_address_set_cstr(addr, (char *)list_nameserver->item[n]->data)) jdns_dnsparams_append_nameserver(params, addr, JDNS_UNICAST_PORT); jdns_address_delete(addr); } jdns_stringlist_delete(list_nameserver); } if(str_domain) { if(str_domain->size > 0) jdns_dnsparams_append_domain(params, str_domain); jdns_string_delete(str_domain); } if(list_searchlist) { for(n = 0; n < list_searchlist->count; ++n) { if(list_searchlist->item[n]->size > 0) jdns_dnsparams_append_domain(params, list_searchlist->item[n]); } jdns_stringlist_delete(list_searchlist); } return params; } static jdns_dnsparams_t *dnsparams_get_winsys() { jdns_dnsparams_t *params; GetNetworkParamsFunc myGetNetworkParams; DWORD ret; HINSTANCE lib; jdns_address_t *addr; jdns_string_t *str; IP_ADDR_STRING *ipstr; lib = LoadLibraryA("iphlpapi"); if(!lib) return 0; params = 0; myGetNetworkParams = (GetNetworkParamsFunc)GetProcAddress(lib, "GetNetworkParams"); if(myGetNetworkParams) { ULONG bufsize = 0; ret = myGetNetworkParams(0, &bufsize); if(ret == ERROR_BUFFER_OVERFLOW) { FIXED_INFO *info = (FIXED_INFO *)jdns_alloc((int)bufsize); ret = myGetNetworkParams(info, &bufsize); if(ret == ERROR_SUCCESS) { params = jdns_dnsparams_new(); ipstr = &info->DnsServerList; while(ipstr) { addr = jdns_address_new(); if(jdns_address_set_cstr(addr, (char *)ipstr->IpAddress.String)) jdns_dnsparams_append_nameserver(params, addr, JDNS_UNICAST_PORT); jdns_address_delete(addr); ipstr = ipstr->Next; } str = jdns_string_new(); jdns_string_set_cstr(str, info->DomainName); if(str->size > 0) jdns_dnsparams_append_domain(params, str); jdns_string_delete(str); } jdns_free(info); } } FreeLibrary(lib); return params; } static void apply_hosts_var_filepath(jdns_dnsparams_t *a, const char *envvar, const char *path) { jdns_string_t *e; char *str; int elen, plen; e = jdns_getenv(envvar); if(!e) return; elen = strlen((char *)e->data); plen = strlen(path); str = (char *)jdns_alloc(elen + plen + 1); memcpy(str, e->data, elen); jdns_string_delete(e); jdns_strcpy(str + elen, path); apply_hosts_file(a, str); jdns_free(str); } static void apply_win_hosts_file(jdns_dnsparams_t *a) { // windows 64-bit apply_hosts_var_filepath(a, "SystemRoot", "\\SysWOW64\\drivers\\etc\\hosts"); // winnt+ apply_hosts_var_filepath(a, "SystemRoot", "\\system32\\drivers\\etc\\hosts"); // win9x apply_hosts_var_filepath(a, "WINDIR", "\\hosts"); } static jdns_dnsparams_t *dnsparams_get_win() { int n; jdns_dnsparams_t *sys_params, *reg_params; reg_params = dnsparams_get_winreg(); sys_params = dnsparams_get_winsys(); // no sys params? take the reg params then if(!sys_params) { apply_win_hosts_file(reg_params); return reg_params; } // sys params don't have a search list, so merge the domains from // the registry if possible if(reg_params) { for(n = 0; n < reg_params->domains->count; ++n) { jdns_string_t *reg_str = reg_params->domains->item[n]; // don't add dups if(!dnsparams_have_domain(sys_params, reg_str)) jdns_dnsparams_append_domain(sys_params, reg_str); } jdns_dnsparams_delete(reg_params); } apply_win_hosts_file(sys_params); return sys_params; } #endif #ifdef JDNS_OS_UNIX static jdns_dnsparams_t *dnsparams_get_unixfiles() { FILE *f; int n; jdns_dnsparams_t *params; jdns_string_t *line, *simp; jdns_stringlist_t *parts; params = jdns_dnsparams_new(); f = jdns_fopen("/etc/resolv.conf", "r"); if(!f) return params; while(1) { line = file_nextline(f); if(!line) break; // truncate at comment n = string_indexOf(line, '#', 0); if(n != -1) { line->size = n; line->data[n] = 0; } simp = string_simplify(line); jdns_string_delete(line); parts = string_split(simp, ' '); jdns_string_delete(simp); if(parts->count < 2) { jdns_stringlist_delete(parts); continue; } simp = string_tolower(parts->item[0]); if(strcmp((char *)simp->data, "nameserver") == 0) { jdns_address_t *addr = jdns_address_new(); jdns_address_set_cstr(addr, (const char *)parts->item[1]->data); jdns_dnsparams_append_nameserver(params, addr, JDNS_UNICAST_PORT); jdns_address_delete(addr); } else if(strcmp((char *)simp->data, "search") == 0) { for(n = 1; n < parts->count; ++n) { jdns_dnsparams_append_domain(params, parts->item[n]); } } else if(strcmp((char *)simp->data, "domain") == 0) { jdns_dnsparams_append_domain(params, parts->item[1]); } jdns_string_delete(simp); jdns_stringlist_delete(parts); } fclose(f); return params; } #if defined(__GLIBC__) && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 3))) # define JDNS_MODERN_RES_API #endif #ifndef JDNS_MODERN_RES_API typedef int (*res_init_func)(); static int my_res_init() { #ifdef JDNS_OS_MAC res_init_func mac_res_init; // look up res_init in the system library (qt does this, not sure why) mac_res_init = (res_init_func)dlsym(RTLD_NEXT, "res_init"); if(!mac_res_init) return -1; return mac_res_init(); #else return res_init(); #endif } #endif // on some platforms, __res_state_ext exists as a struct but it is not // a define, so the #ifdef doesn't work. as a workaround, we'll explicitly // specify the platforms that have __res_state_ext //#ifdef __res_state_ext #if defined(JDNS_OS_MAC) || defined(JDNS_OS_FREEBSD) || \ defined(JDNS_OS_NETBSD) || defined (JDNS_OS_SOLARIS) # define USE_EXTEXT #endif static jdns_dnsparams_t *dnsparams_get_unixsys() { int n; jdns_dnsparams_t *params; #ifdef JDNS_MODERN_RES_API struct __res_state res; memset(&res, 0, sizeof(struct __res_state)); n = res_ninit(&res); #define RESVAR res #else n = my_res_init(); #define RESVAR _res #endif params = jdns_dnsparams_new(); // error initializing? if(n == -1) return params; // nameservers - ipv6 for(n = 0; n < MAXNS && n < RESVAR._u._ext.nscount; ++n) { jdns_address_t *addr; struct sockaddr_in6 *sa6; #ifdef USE_EXTEXT // seems _ext.ext can be null in some cases... if(RESVAR._u._ext.ext == NULL) break; sa6 = ((struct sockaddr_in6 *)RESVAR._u._ext.ext) + n; #else sa6 = RESVAR._u._ext.nsaddrs[n]; #endif if(sa6 == NULL) continue; addr = jdns_address_new(); jdns_address_set_ipv6(addr, sa6->sin6_addr.s6_addr); jdns_dnsparams_append_nameserver(params, addr, JDNS_UNICAST_PORT); jdns_address_delete(addr); } // nameservers - ipv4 for(n = 0; n < MAXNS && n < RESVAR.nscount; ++n) { jdns_address_t *addr = jdns_address_new(); jdns_address_set_ipv4(addr, ntohl(RESVAR.nsaddr_list[n].sin_addr.s_addr)); jdns_dnsparams_append_nameserver(params, addr, JDNS_UNICAST_PORT); jdns_address_delete(addr); } // domain name if(strlen(RESVAR.defdname) > 0) { jdns_string_t *str; jdns_string_t *p; str = jdns_string_new(); jdns_string_set_cstr(str, RESVAR.defdname); p = string_tolower(str); jdns_string_delete(str); str = p; jdns_dnsparams_append_domain(params, str); jdns_string_delete(str); } // search list #ifdef MAXDFLSRCH for(n = 0; n < MAXDFLSRCH && RESVAR.dnsrch[n]; ++n) { if(strlen(RESVAR.dnsrch[n]) > 0) { jdns_string_t *str; jdns_string_t *p; str = jdns_string_new(); jdns_string_set_cstr(str, RESVAR.dnsrch[n]); p = string_tolower(str); jdns_string_delete(str); str = p; // don't add dups if(!dnsparams_have_domain(params, str)) jdns_dnsparams_append_domain(params, str); jdns_string_delete(str); } } #endif return params; } static jdns_dnsparams_t *dnsparams_get_unix() { jdns_dnsparams_t *params; // prefer system calls over files params = dnsparams_get_unixsys(); if(params->nameservers->count == 0) { jdns_dnsparams_delete(params); params = dnsparams_get_unixfiles(); } apply_hosts_file(params, "/etc/hosts"); return params; } #endif jdns_dnsparams_t *jdns_system_dnsparams() { #ifdef JDNS_OS_WIN return dnsparams_get_win(); #else return dnsparams_get_unix(); #endif } zurl-1.0.0/src/jdns/jdns_util.c000066400000000000000000001024471220152020200163620ustar00rootroot00000000000000/* * Copyright (C) 2005-2008 Justin Karneges * * 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. */ #include "jdns_p.h" #include "jdns_packet.h" //---------------------------------------------------------------------------- // misc //---------------------------------------------------------------------------- void *jdns_alloc(int size) { return malloc(size); } void *jdns_realloc(void *p, int size) { return realloc(p, size); } void jdns_free(void *p) { free(p); } char *jdns_strdup(const char *s) { char *p; int len; len = strlen(s) + 1; // the zero p = (char *)jdns_alloc(len); memcpy(p, s, len); return p; } unsigned char *jdns_copy_array(const unsigned char *src, int size) { unsigned char *out; if(size <= 0) return 0; out = (unsigned char *)jdns_alloc(size); memcpy(out, src, size); return out; } int jdns_domain_cmp(const unsigned char *a, const unsigned char *b) { int n; int len_a; // case-insensitive compare len_a = _ustrlen(a); if(len_a != (int)_ustrlen(b)) return 0; for(n = 0; n < len_a; ++n) { if(tolower(a[n]) != tolower(b[n])) return 0; } return 1; } int jdns_sprintf_s(char *str, int n, const char *format, ...) { int ret; va_list ap; va_start(ap, format); ret = jdns_vsprintf_s(str, n, format, ap); va_end(ap); return ret; } int jdns_vsprintf_s(char *str, int n, const char *format, va_list ap) { #if defined(_MSC_VER) && _MSC_VER >= 1400 return vsprintf_s(str, n, format, ap); #else (void)n; return vsprintf(str, format, ap); #endif } FILE *jdns_fopen(const char *path, const char *mode) { #if defined(_MSC_VER) && _MSC_VER >= 1400 FILE *fp; if(fopen_s(&fp, path, mode) != 0) return 0; return fp; #else return fopen(path, mode); #endif } jdns_string_t *jdns_getenv(const char *name) { #if defined(_MSC_VER) && _MSC_VER >= 1400 jdns_string_t *out; char *dest; size_t size; int sizei; errno_t ret; ret = getenv_s(&size, 0, 0, name); if(ret != 0 || size == 0) return 0; sizei = (int)size; dest = (char *)jdns_alloc(sizei); ret = getenv_s(&size, dest, size, name); if(ret != 0) { free(dest); return 0; } out = jdns_string_new(); out->size = sizei - 1; out->data = dest; // must be zero-terminated, which it is return out; #else jdns_string_t *out; char *val; val = getenv(name); if(!val) return 0; out = jdns_string_new(); jdns_string_set_cstr(out, val); return out; #endif } char *jdns_strcpy(char *dst, const char *src) { #if defined(_MSC_VER) && _MSC_VER >= 1400 int len; // deliberately unsafe len = strlen(src); if(strcpy_s(dst, len + 1, src) != 0) return 0; return dst; #else return strcpy(dst, src); #endif } //---------------------------------------------------------------------------- // jdns_object //---------------------------------------------------------------------------- void *jdns_object_new(int size, void (*dtor)(void *), void *(*cctor)(const void *)) { jdns_object_t *a = (jdns_object_t *)jdns_alloc(size); memset(a, 0, size); a->dtor = dtor; a->cctor = cctor; return a; } void *jdns_object_copy(const void *a) { return ((const jdns_object_t *)a)->cctor(a); } void jdns_object_delete(void *a) { ((jdns_object_t *)a)->dtor(a); } void jdns_object_free(void *a) { jdns_free(a); } //---------------------------------------------------------------------------- // jdns_list //---------------------------------------------------------------------------- jdns_list_t *jdns_list_new() { jdns_list_t *a = JDNS_OBJECT_NEW(jdns_list); a->count = 0; a->item = 0; a->valueList = 0; a->autoDelete = 0; return a; } jdns_list_t *jdns_list_copy(const jdns_list_t *a) { jdns_list_t *c = jdns_list_new(); // note: copying a list with autoDelete should not ever be done. // heck, let's not even allow it. return an empty list. if(a->autoDelete) return c; c->valueList = a->valueList; // copy the items if(a->item) { int n; c->count = a->count; c->item = (void **)jdns_alloc(sizeof(void *) * c->count); if(a->valueList) { // deep copy for(n = 0; n < c->count; ++n) c->item[n] = jdns_object_copy(a->item[n]); } else { // just the pointer for(n = 0; n < c->count; ++n) c->item[n] = a->item[n]; } } return c; } void jdns_list_delete(jdns_list_t *a) { if(!a) return; jdns_list_clear(a); jdns_object_free(a); } void jdns_list_clear(jdns_list_t *a) { if(a->item) { // delete the items if necessary if(a->valueList || a->autoDelete) { int n; for(n = 0; n < a->count; ++n) jdns_object_delete(a->item[n]); } jdns_free(a->item); a->item = 0; a->count = 0; } } void jdns_list_insert(jdns_list_t *a, void *item, int pos) { // make memory if(!a->item) a->item = (void **)jdns_alloc(sizeof(void *)); else a->item = (void **)jdns_realloc(a->item, sizeof(void *) * (a->count + 1)); // prepare position if(pos != -1) memmove(a->item + pos + 1, a->item + pos, (a->count - pos) * sizeof(void *)); else pos = a->count; // insert it if(a->valueList) a->item[pos] = jdns_object_copy(item); else a->item[pos] = item; ++a->count; } void jdns_list_insert_value(jdns_list_t *a, const void *item, int pos) { jdns_list_insert(a, (void *)item, pos); } void jdns_list_remove(jdns_list_t *a, void *item) { int n; int pos = -1; for(n = 0; n < a->count; ++n) { if(a->item[n] == item) { pos = n; break; } } if(pos == -1) return; jdns_list_remove_at(a, pos); } void jdns_list_remove_at(jdns_list_t *a, int pos) { if(pos < 0 || pos >= a->count) return; // delete the item if necessary if(a->valueList || a->autoDelete) jdns_object_delete(a->item[pos]); // free the position if(a->count > 1) { memmove(a->item + pos, a->item + pos + 1, (a->count - pos - 1) * sizeof(void *)); --a->count; } else { jdns_free(a->item); a->item = 0; a->count = 0; } } //---------------------------------------------------------------------------- // jdns_string //---------------------------------------------------------------------------- jdns_string_t *jdns_string_new() { jdns_string_t *s = JDNS_OBJECT_NEW(jdns_string); s->data = 0; s->size = 0; return s; } jdns_string_t *jdns_string_copy(const jdns_string_t *s) { jdns_string_t *c = jdns_string_new(); if(s->data) jdns_string_set(c, s->data, s->size); return c; } void jdns_string_delete(jdns_string_t *s) { if(!s) return; if(s->data) jdns_free(s->data); jdns_object_free(s); } void jdns_string_set(jdns_string_t *s, const unsigned char *str, int str_len) { if(s->data) jdns_free(s->data); s->data = (unsigned char *)jdns_alloc(str_len + 1); memcpy(s->data, str, str_len); s->data[str_len] = 0; s->size = str_len; } void jdns_string_set_cstr(jdns_string_t *s, const char *str) { jdns_string_set(s, (const unsigned char *)str, strlen(str)); } int jdns_string_indexOf(const jdns_string_t *s, unsigned char c, int pos) { int n; for(n = pos; n < s->size; ++n) { if(s->data[n] == c) return n; } return -1; } jdns_stringlist_t *jdns_string_split(const jdns_string_t *s, unsigned char sep) { int at, n, len; jdns_string_t *str; jdns_stringlist_t *out; at = 0; out = jdns_stringlist_new(); while(at < s->size) { n = jdns_string_indexOf(s, sep, at); if(n == -1) n = s->size; len = n - at; // FIXME: should we allow empty items? //if(len == 0) // break; str = jdns_string_new(); jdns_string_set(str, s->data + at, len); jdns_stringlist_append(out, str); jdns_string_delete(str); at = n + 1; // skip over separator } return out; } //---------------------------------------------------------------------------- // jdns_stringlist //---------------------------------------------------------------------------- jdns_stringlist_t *jdns_stringlist_new() { jdns_list_t *a = jdns_list_new(); a->valueList = 1; return (jdns_stringlist_t *)a; } jdns_stringlist_t *jdns_stringlist_copy(const jdns_stringlist_t *a) { return (jdns_stringlist_t *)jdns_list_copy((const jdns_list_t *)a); } void jdns_stringlist_delete(jdns_stringlist_t *a) { jdns_list_delete((jdns_list_t *)a); // note: no need to call jdns_object_free() here } void jdns_stringlist_append(jdns_stringlist_t *a, const jdns_string_t *str) { jdns_list_insert_value((jdns_list_t *)a, str, -1); } //---------------------------------------------------------------------------- // jdns_address //---------------------------------------------------------------------------- jdns_address_t *jdns_address_new() { jdns_address_t *a = alloc_type(jdns_address_t); a->isIpv6 = 0; a->addr.v4 = 0; a->c_str = jdns_strdup(""); return a; } jdns_address_t *jdns_address_copy(const jdns_address_t *a) { jdns_address_t *c = jdns_address_new(); if(a->isIpv6) jdns_address_set_ipv6(c, a->addr.v6); else jdns_address_set_ipv4(c, a->addr.v4); return c; } void jdns_address_delete(jdns_address_t *a) { if(!a) return; if(a->isIpv6) jdns_free(a->addr.v6); jdns_free(a->c_str); jdns_free(a); } void jdns_address_set_ipv4(jdns_address_t *a, unsigned long int ipv4) { if(a->isIpv6) jdns_free(a->addr.v6); jdns_free(a->c_str); a->isIpv6 = 0; a->addr.v4 = ipv4; a->c_str = (char *)jdns_alloc(16); // max size (3 * 4 + 3 + 1) jdns_sprintf_s(a->c_str, 16, "%d.%d.%d.%d", (unsigned char)((ipv4 >> 24) & 0xff), (unsigned char)((ipv4 >> 16) & 0xff), (unsigned char)((ipv4 >> 8) & 0xff), (unsigned char)((ipv4) & 0xff)); } void jdns_address_set_ipv6(jdns_address_t *a, const unsigned char *ipv6) { int n; unsigned char *p; unsigned short word[8]; if(a->isIpv6) jdns_free(a->addr.v6); jdns_free(a->c_str); a->isIpv6 = 1; a->addr.v6 = (unsigned char *)jdns_alloc(16); memcpy(a->addr.v6, ipv6, 16); p = (unsigned char *)a->addr.v6; a->c_str = (char *)jdns_alloc(40); // max size (8 * 4 + 7 + 1) // each word in a 16-byte ipv6 address is network byte order for(n = 0; n < 8; ++n) word[n] = ((unsigned short)(p[n * 2]) << 8) + (unsigned short)(p[n * 2 + 1]); jdns_sprintf_s(a->c_str, 40, "%04X:%04X:%04X:%04X:%04X:%04X:%04X:%04X", word[0], word[1], word[2], word[3], word[4], word[5], word[6], word[7]); } int jdns_address_set_cstr(jdns_address_t *a, const char *str) { int slen = strlen(str); // ipv6 if(strchr(str, ':')) { jdns_string_t *in; jdns_stringlist_t *list; unsigned char ipv6[16]; int n, at, count, fill; in = jdns_string_new(); jdns_string_set_cstr(in, str); list = jdns_string_split(in, ':'); jdns_string_delete(in); // a confusing outputting-backwards parser adapted from qt count = list->count; if(count < 3 || count > 8) goto error; at = 16; fill = 9 - count; for(n = count - 1; n >= 0; --n) { if(at <= 0) goto error; if(list->item[n]->size == 0) { if(n == count - 1) { if(list->item[n - 1]->size != 0) goto error; ipv6[--at] = 0; ipv6[--at] = 0; } else if(n == 0) { if(list->item[n + 1]->size != 0) goto error; ipv6[--at] = 0; ipv6[--at] = 0; } else { int i; for(i = 0; i < fill; ++i) { if(at <= 0) goto error; ipv6[--at] = 0; ipv6[--at] = 0; } } } else { if(jdns_string_indexOf(list->item[n], '.', 0) == -1) { int x; x = strtol((const char *)list->item[n]->data, NULL, 16); if(x < 0 || x > 0xffff) goto error; ipv6[--at] = x & 0xff; ipv6[--at] = (x >> 8) & 0xff; } else { jdns_address_t *v4; if(n != count - 1) goto error; v4 = jdns_address_new(); if(!jdns_address_set_cstr(v4, (char *)list->item[n]->data)) { jdns_address_delete(v4); goto error; } ipv6[--at] = (unsigned char)(v4->addr.v4 & 0xff); ipv6[--at] = (unsigned char)((v4->addr.v4 >> 8) & 0xff); ipv6[--at] = (unsigned char)((v4->addr.v4 >> 16) & 0xff); ipv6[--at] = (unsigned char)((v4->addr.v4 >> 24) & 0xff); jdns_address_delete(v4); --fill; } } } jdns_stringlist_delete(list); jdns_address_set_ipv6(a, ipv6); return 1; error: jdns_stringlist_delete(list); return 0; } else if(strchr(str, '.')) { unsigned char b[4]; int x; unsigned long int ipv4; int at; char *part; int len; const char *p, *p2; p = str; at = 0; while(1) { p2 = strchr(p, '.'); if(!p2) p2 = str + slen; len = p2 - p; // convert the section into a byte part = (char *)jdns_alloc(len + 1); memcpy(part, p, len); part[len] = 0; x = strtol(part, NULL, 10); jdns_free(part); if(x < 0 || x > 0xff) break; b[at++] = (unsigned char)x; // done? if(p2 >= str + slen) break; // skip over the separator p = p2 + 1; } if(at != 4) return 0; ipv4 = 0; ipv4 += b[0]; ipv4 <<= 8; ipv4 += b[1]; ipv4 <<= 8; ipv4 += b[2]; ipv4 <<= 8; ipv4 += b[3]; jdns_address_set_ipv4(a, ipv4); return 1; } else return 0; } int jdns_address_cmp(const jdns_address_t *a, const jdns_address_t *b) { // same protocol? if(a->isIpv6 != b->isIpv6) return 0; if(a->isIpv6) { int n; for(n = 0; n < 16; ++n) { if(a->addr.v6[n] != b->addr.v6[n]) break; } if(n == 16) return 1; } else { if(a->addr.v4 == b->addr.v4) return 1; } return 0; } // FF02::FB unsigned char jdns_multicast_addr6_value_v6[] = { 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfb }; jdns_address_t *jdns_address_multicast4_new() { jdns_address_t *a = jdns_address_new(); jdns_address_set_ipv4(a, 0xe00000fb); return a; } jdns_address_t *jdns_address_multicast6_new() { jdns_address_t *a = jdns_address_new(); jdns_address_set_ipv6(a, jdns_multicast_addr6_value_v6); return a; } //---------------------------------------------------------------------------- // jdns_server //---------------------------------------------------------------------------- jdns_server_t *jdns_server_new() { jdns_server_t *s = alloc_type(jdns_server_t); s->name = 0; s->port = 0; s->priority = 0; s->weight = 0; return s; } jdns_server_t *jdns_server_copy(const jdns_server_t *s) { jdns_server_t *c = jdns_server_new(); if(s->name) c->name = _ustrdup(s->name); c->port = s->port; c->priority = s->priority; c->weight = s->weight; return c; } void jdns_server_delete(jdns_server_t *s) { if(!s) return; if(s->name) jdns_free(s->name); jdns_object_free(s); } void jdns_server_set_name(jdns_server_t *s, const unsigned char *name) { if(s->name) jdns_free(s->name); s->name = _ustrdup(name); } //---------------------------------------------------------------------------- // jdns_nameserver //---------------------------------------------------------------------------- jdns_nameserver_t *jdns_nameserver_new() { jdns_nameserver_t *a = alloc_type(jdns_nameserver_t); a->address = 0; a->port = -1; return a; } jdns_nameserver_t *jdns_nameserver_copy(const jdns_nameserver_t *a) { jdns_nameserver_t *c = jdns_nameserver_new(); if(a->address) c->address = jdns_address_copy(a->address); c->port = a->port; return c; } void jdns_nameserver_delete(jdns_nameserver_t *a) { if(!a) return; jdns_address_delete(a->address); jdns_free(a); } void jdns_nameserver_set(jdns_nameserver_t *a, const jdns_address_t *addr, int port) { if(a->address) jdns_address_delete(a->address); a->address = jdns_address_copy(addr); a->port = port; } //---------------------------------------------------------------------------- // jdns_nameserverlist //---------------------------------------------------------------------------- jdns_nameserverlist_t *jdns_nameserverlist_new() { jdns_nameserverlist_t *a = alloc_type(jdns_nameserverlist_t); a->count = 0; a->item = 0; return a; } jdns_nameserverlist_t *jdns_nameserverlist_copy(const jdns_nameserverlist_t *a) { int n; jdns_nameserverlist_t *c = jdns_nameserverlist_new(); if(a->item) { c->item = (jdns_nameserver_t **)jdns_alloc(sizeof(jdns_nameserver_t *) * a->count); c->count = a->count; for(n = 0; n < c->count; ++n) c->item[n] = jdns_nameserver_copy(a->item[n]); } return c; } void jdns_nameserverlist_delete(jdns_nameserverlist_t *a) { int n; if(!a) return; if(a->item) { for(n = 0; n < a->count; ++n) jdns_nameserver_delete(a->item[n]); jdns_free(a->item); } jdns_free(a); } void jdns_nameserverlist_append(jdns_nameserverlist_t *a, const jdns_address_t *addr, int port) { if(!a->item) a->item = (jdns_nameserver_t **)jdns_alloc(sizeof(jdns_nameserver_t *)); else a->item = (jdns_nameserver_t **)jdns_realloc(a->item, sizeof(jdns_nameserver_t *) * (a->count + 1)); a->item[a->count] = jdns_nameserver_new(); jdns_nameserver_set(a->item[a->count], addr, port); ++a->count; } //---------------------------------------------------------------------------- // jdns_dnshost //---------------------------------------------------------------------------- jdns_dnshost_t *jdns_dnshost_new() { jdns_dnshost_t *a = alloc_type(jdns_dnshost_t); a->name = 0; a->address = 0; return a; } jdns_dnshost_t *jdns_dnshost_copy(const jdns_dnshost_t *a) { jdns_dnshost_t *c = jdns_dnshost_new(); if(a->name) c->name = jdns_string_copy(a->name); if(a->address) c->address = jdns_address_copy(a->address); return c; } void jdns_dnshost_delete(jdns_dnshost_t *a) { if(!a) return; jdns_string_delete(a->name); jdns_address_delete(a->address); jdns_free(a); } //---------------------------------------------------------------------------- // jdns_dnshostlist //---------------------------------------------------------------------------- jdns_dnshostlist_t *jdns_dnshostlist_new() { jdns_dnshostlist_t *a = alloc_type(jdns_dnshostlist_t); a->count = 0; a->item = 0; return a; } jdns_dnshostlist_t *jdns_dnshostlist_copy(const jdns_dnshostlist_t *a) { int n; jdns_dnshostlist_t *c = jdns_dnshostlist_new(); if(a->item) { c->item = (jdns_dnshost_t **)jdns_alloc(sizeof(jdns_dnshost_t *) * a->count); c->count = a->count; for(n = 0; n < c->count; ++n) c->item[n] = jdns_dnshost_copy(a->item[n]); } return c; } void jdns_dnshostlist_delete(jdns_dnshostlist_t *a) { int n; if(!a) return; if(a->item) { for(n = 0; n < a->count; ++n) jdns_dnshost_delete(a->item[n]); jdns_free(a->item); } jdns_free(a); } void jdns_dnshostlist_append(jdns_dnshostlist_t *a, const jdns_dnshost_t *host) { if(!a->item) a->item = (jdns_dnshost_t **)jdns_alloc(sizeof(jdns_dnshost_t *)); else a->item = (jdns_dnshost_t **)jdns_realloc(a->item, sizeof(jdns_dnshost_t *) * (a->count + 1)); a->item[a->count] = jdns_dnshost_copy(host); ++a->count; } //---------------------------------------------------------------------------- // jdns_dnsparams //---------------------------------------------------------------------------- jdns_dnsparams_t *jdns_dnsparams_new() { jdns_dnsparams_t *a = alloc_type(jdns_dnsparams_t); a->nameservers = jdns_nameserverlist_new(); a->domains = jdns_stringlist_new(); a->hosts = jdns_dnshostlist_new(); return a; } jdns_dnsparams_t *jdns_dnsparams_copy(jdns_dnsparams_t *a) { jdns_dnsparams_t *c = jdns_dnsparams_new(); c->nameservers = jdns_nameserverlist_copy(a->nameservers); c->domains = jdns_stringlist_copy(a->domains); c->hosts = jdns_dnshostlist_copy(a->hosts); return c; } void jdns_dnsparams_delete(jdns_dnsparams_t *a) { if(!a) return; jdns_nameserverlist_delete(a->nameservers); jdns_stringlist_delete(a->domains); jdns_dnshostlist_delete(a->hosts); jdns_free(a); } void jdns_dnsparams_append_nameserver(jdns_dnsparams_t *a, const jdns_address_t *addr, int port) { jdns_nameserverlist_append(a->nameservers, addr, port); } void jdns_dnsparams_append_domain(jdns_dnsparams_t *a, const jdns_string_t *domain) { jdns_stringlist_append(a->domains, domain); } void jdns_dnsparams_append_host(jdns_dnsparams_t *a, const jdns_string_t *name, const jdns_address_t *address) { jdns_dnshost_t *h = jdns_dnshost_new(); h->name = jdns_string_copy(name); h->address = jdns_address_copy(address); jdns_dnshostlist_append(a->hosts, h); jdns_dnshost_delete(h); } //---------------------------------------------------------------------------- // jdns_rr //---------------------------------------------------------------------------- void _jdns_rr_data_reset(jdns_rr_t *r) { if(r->rdata) { jdns_free(r->rdata); r->rdata = 0; } r->rdlength = 0; if(r->haveKnown) { switch(r->type) { case JDNS_RTYPE_A: case JDNS_RTYPE_AAAA: jdns_address_delete(r->data.address); break; case JDNS_RTYPE_MX: case JDNS_RTYPE_SRV: jdns_server_delete(r->data.server); break; case JDNS_RTYPE_CNAME: case JDNS_RTYPE_PTR: case JDNS_RTYPE_NS: jdns_free(r->data.name); break; case JDNS_RTYPE_TXT: jdns_stringlist_delete(r->data.texts); break; case JDNS_RTYPE_HINFO: jdns_string_delete(r->data.hinfo.cpu); jdns_string_delete(r->data.hinfo.os); break; default: break; }; r->haveKnown = 0; } r->type = -1; } void _jdns_rr_data_copy(const jdns_rr_t *r, jdns_rr_t *c) { c->type = r->type; c->qclass = r->qclass; c->rdlength = r->rdlength; c->rdata = jdns_copy_array(r->rdata, r->rdlength); if(r->haveKnown) { switch(r->type) { case JDNS_RTYPE_A: case JDNS_RTYPE_AAAA: c->data.address = jdns_address_copy(r->data.address); break; case JDNS_RTYPE_MX: case JDNS_RTYPE_SRV: c->data.server = jdns_server_copy(r->data.server); break; case JDNS_RTYPE_CNAME: case JDNS_RTYPE_PTR: case JDNS_RTYPE_NS: c->data.name = _ustrdup(r->data.name); break; case JDNS_RTYPE_TXT: c->data.texts = jdns_stringlist_copy(r->data.texts); break; case JDNS_RTYPE_HINFO: c->data.hinfo.cpu = jdns_string_copy(r->data.hinfo.cpu); c->data.hinfo.os = jdns_string_copy(r->data.hinfo.os); break; default: break; }; c->haveKnown = 1; } } jdns_rr_t *jdns_rr_new() { jdns_rr_t *r = alloc_type(jdns_rr_t); r->owner = 0; r->ttl = 0; r->type = -1; r->qclass = 0; r->rdata = 0; r->rdlength = 0; r->haveKnown = 0; return r; } jdns_rr_t *jdns_rr_copy(const jdns_rr_t *r) { jdns_rr_t *c = jdns_rr_new(); if(r->owner) c->owner = _ustrdup(r->owner); c->ttl = r->ttl; _jdns_rr_data_copy(r, c); return c; } void jdns_rr_delete(jdns_rr_t *r) { if(!r) return; if(r->owner) jdns_free(r->owner); _jdns_rr_data_reset(r); jdns_free(r); } void jdns_rr_set_owner(jdns_rr_t *r, const unsigned char *name) { if(r->owner) jdns_free(r->owner); r->owner = _ustrdup(name); } void jdns_rr_set_record(jdns_rr_t *r, int type, const unsigned char *rdata, int rdlength) { _jdns_rr_data_reset(r); r->type = type; r->rdlength = rdlength; r->rdata = jdns_copy_array(rdata, rdlength); } void jdns_rr_set_A(jdns_rr_t *r, const jdns_address_t *address) { _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_A; r->haveKnown = 1; r->data.address = jdns_address_copy(address); } void jdns_rr_set_AAAA(jdns_rr_t *r, const jdns_address_t *address) { _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_AAAA; r->haveKnown = 1; r->data.address = jdns_address_copy(address); } void jdns_rr_set_MX(jdns_rr_t *r, const unsigned char *name, int priority) { jdns_server_t *s = jdns_server_new(); jdns_server_set_name(s, name); s->priority = priority; _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_MX; r->haveKnown = 1; r->data.server = s; } void jdns_rr_set_SRV(jdns_rr_t *r, const unsigned char *name, int port, int priority, int weight) { jdns_server_t *s = jdns_server_new(); jdns_server_set_name(s, name); s->port = port; s->priority = priority; s->weight = weight; _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_SRV; r->haveKnown = 1; r->data.server = s; } void jdns_rr_set_CNAME(jdns_rr_t *r, const unsigned char *name) { _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_CNAME; r->haveKnown = 1; r->data.name = _ustrdup(name); } void jdns_rr_set_PTR(jdns_rr_t *r, const unsigned char *name) { _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_PTR; r->haveKnown = 1; r->data.name = _ustrdup(name); } void jdns_rr_set_TXT(jdns_rr_t *r, const jdns_stringlist_t *texts) { _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_TXT; r->haveKnown = 1; r->data.texts = jdns_stringlist_copy(texts); } void jdns_rr_set_HINFO(jdns_rr_t *r, const jdns_string_t *cpu, const jdns_string_t *os) { _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_HINFO; r->haveKnown = 1; r->data.hinfo.cpu = jdns_string_copy(cpu); r->data.hinfo.os = jdns_string_copy(os); } void jdns_rr_set_NS(jdns_rr_t *r, const unsigned char *name) { _jdns_rr_data_reset(r); r->type = JDNS_RTYPE_NS; r->haveKnown = 1; r->data.name = _ustrdup(name); } int jdns_rr_verify(const jdns_rr_t *r) { if(r->type == -1) return 0; if(!jdns_packet_name_isvalid(r->owner, _ustrlen(r->owner))) return 0; switch(r->type) { case JDNS_RTYPE_MX: case JDNS_RTYPE_SRV: { // consider it valid if we don't have a known to check if(!r->haveKnown) return 1; if(!jdns_packet_name_isvalid(r->data.server->name, _ustrlen(r->data.server->name))) return 0; break; } case JDNS_RTYPE_CNAME: case JDNS_RTYPE_PTR: case JDNS_RTYPE_NS: { if(!r->haveKnown) return 1; if(!jdns_packet_name_isvalid(r->data.name, _ustrlen(r->data.name))) return 0; break; } case JDNS_RTYPE_TXT: { int n; if(!r->haveKnown) return 1; for(n = 0; n < r->data.texts->count; ++n) { if(r->data.texts->item[n]->size > 255) return 0; } break; } case JDNS_RTYPE_HINFO: { if(!r->haveKnown) return 1; if(r->data.hinfo.cpu->size > 255) return 0; if(r->data.hinfo.os->size > 255) return 0; break; } } return 1; } static jdns_string_t *read_name_at_end(const jdns_packet_resource_t *pr, const jdns_packet_t *ref, int _at) { jdns_string_t *name; int at; at = _at; if(!jdns_packet_resource_read_name(pr, ref, &at, &name)) return 0; if(at != pr->rdlength) { jdns_string_delete(name); return 0; } return name; } static jdns_string_t *read_text_string(const jdns_packet_resource_t *pr, int *_at) { jdns_string_t *out; int at, len; at = *_at; if(at + 1 > pr->rdlength) return 0; len = pr->rdata[at++]; if(at + len > pr->rdlength) return 0; out = jdns_string_new(); jdns_string_set(out, pr->rdata + at, len); at += len; *_at = at; return out; } // if the type is known, then it must be parsed properly // if the type is unknown, then that's ok // rdata is always copied, known or not jdns_rr_t *jdns_rr_from_resource(const jdns_packet_resource_t *pr, const jdns_packet_t *ref) { jdns_rr_t *rr = 0; if(pr->qtype == JDNS_RTYPE_ANY) return 0; switch(pr->qtype) { case JDNS_RTYPE_A: { jdns_address_t *addr; unsigned long int ip; if(pr->rdlength != 4) break; memcpy(&ip, pr->rdata, 4); ip = ntohl(ip); addr = jdns_address_new(); jdns_address_set_ipv4(addr, ip); rr = jdns_rr_new(); jdns_rr_set_A(rr, addr); jdns_address_delete(addr); break; } case JDNS_RTYPE_AAAA: { jdns_address_t *addr; if(pr->rdlength != 16) break; addr = jdns_address_new(); jdns_address_set_ipv6(addr, pr->rdata); rr = jdns_rr_new(); jdns_rr_set_AAAA(rr, addr); jdns_address_delete(addr); break; } case JDNS_RTYPE_MX: { unsigned short priority; jdns_string_t *name; if(pr->rdlength < 2) break; memcpy(&priority, pr->rdata, 2); priority = ntohs(priority); name = read_name_at_end(pr, ref, 2); if(!name) break; rr = jdns_rr_new(); jdns_rr_set_MX(rr, name->data, priority); jdns_string_delete(name); break; } case JDNS_RTYPE_SRV: { unsigned short priority, weight, port; jdns_string_t *name; if(pr->rdlength < 6) break; memcpy(&priority, pr->rdata, 2); priority = ntohs(priority); memcpy(&weight, pr->rdata + 2, 2); weight = ntohs(weight); memcpy(&port, pr->rdata + 4, 2); port = ntohs(port); name = read_name_at_end(pr, ref, 6); if(!name) break; rr = jdns_rr_new(); jdns_rr_set_SRV(rr, name->data, port, priority, weight); jdns_string_delete(name); break; } case JDNS_RTYPE_CNAME: { jdns_string_t *name; name = read_name_at_end(pr, ref, 0); if(!name) break; rr = jdns_rr_new(); jdns_rr_set_CNAME(rr, name->data); jdns_string_delete(name); break; } case JDNS_RTYPE_PTR: { jdns_string_t *name; name = read_name_at_end(pr, ref, 0); if(!name) break; rr = jdns_rr_new(); jdns_rr_set_PTR(rr, name->data); jdns_string_delete(name); break; } case JDNS_RTYPE_TXT: { jdns_stringlist_t *texts; jdns_string_t *str; int at, error; texts = jdns_stringlist_new(); at = 0; error = 0; while(at < pr->rdlength) { str = read_text_string(pr, &at); if(!str) { error = 1; break; } jdns_stringlist_append(texts, str); jdns_string_delete(str); } if(error) { jdns_stringlist_delete(texts); break; } rr = jdns_rr_new(); jdns_rr_set_TXT(rr, texts); jdns_stringlist_delete(texts); break; } case JDNS_RTYPE_HINFO: { jdns_string_t *cpu, *os; int at; at = 0; cpu = read_text_string(pr, &at); if(!cpu) break; os = read_text_string(pr, &at); if(!os) { jdns_string_delete(cpu); break; } if(at != pr->rdlength) { jdns_string_delete(cpu); jdns_string_delete(os); break; } rr = jdns_rr_new(); jdns_rr_set_HINFO(rr, cpu, os); jdns_string_delete(cpu); jdns_string_delete(os); break; } case JDNS_RTYPE_NS: { jdns_string_t *name; name = read_name_at_end(pr, ref, 0); if(!name) break; rr = jdns_rr_new(); jdns_rr_set_NS(rr, name->data); jdns_string_delete(name); break; } default: { rr = jdns_rr_new(); rr->type = pr->qtype; break; } } if(rr) { rr->qclass = pr->qclass; rr->owner = _ustrdup(pr->qname->data); rr->ttl = (int)pr->ttl; // pr->ttl is 31-bits, cast is safe rr->rdlength = pr->rdlength; rr->rdata = jdns_copy_array(pr->rdata, pr->rdlength); } return rr; } //---------------------------------------------------------------------------- // jdns_response //---------------------------------------------------------------------------- #define ARRAY_DELETE(array, count, dtor) \ { \ if(count > 0) \ { \ int n; \ for(n = 0; n < count; ++n) \ dtor(array[n]); \ } \ jdns_free(array); \ array = 0; \ count = 0; \ } #define ARRAY_COPY(type, array_src, count_src, array_dest, count_dest, cctor) \ { \ if(count_src > 0) \ { \ int n; \ count_dest = count_src; \ array_dest = (type **)jdns_alloc(sizeof(type *) * count_dest); \ for(n = 0; n < count_dest; ++n) \ array_dest[n] = cctor(array_src[n]); \ } \ } #define ARRAY_APPEND(type, array, count, item) \ { \ if(!array) \ array = (type **)jdns_alloc(sizeof(type *)); \ else \ array = (type **)jdns_realloc(array, sizeof(type *) * (count + 1)); \ array[count] = item; \ ++count; \ } jdns_response_t *jdns_response_new() { jdns_response_t *r = alloc_type(jdns_response_t); r->answerCount = 0; r->answerRecords = 0; r->authorityCount = 0; r->authorityRecords = 0; r->additionalCount = 0; r->additionalRecords = 0; return r; } jdns_response_t *jdns_response_copy(const jdns_response_t *r) { jdns_response_t *c = jdns_response_new(); ARRAY_COPY(jdns_rr_t, r->answerRecords, r->answerCount, c->answerRecords, c->answerCount, jdns_rr_copy); ARRAY_COPY(jdns_rr_t, r->authorityRecords, r->authorityCount, c->authorityRecords, c->authorityCount, jdns_rr_copy); ARRAY_COPY(jdns_rr_t, r->additionalRecords, r->additionalCount, c->additionalRecords, c->additionalCount, jdns_rr_copy); return c; } void jdns_response_delete(jdns_response_t *r) { if(!r) return; ARRAY_DELETE(r->answerRecords, r->answerCount, jdns_rr_delete); ARRAY_DELETE(r->authorityRecords, r->authorityCount, jdns_rr_delete); ARRAY_DELETE(r->additionalRecords, r->additionalCount, jdns_rr_delete); jdns_free(r); } void jdns_response_append_answer(jdns_response_t *r, const jdns_rr_t *rr) { ARRAY_APPEND(jdns_rr_t, r->answerRecords, r->answerCount, jdns_rr_copy(rr)); } void jdns_response_append_authority(jdns_response_t *r, const jdns_rr_t *rr) { ARRAY_APPEND(jdns_rr_t, r->authorityRecords, r->authorityCount, jdns_rr_copy(rr)); } void jdns_response_append_additional(jdns_response_t *r, const jdns_rr_t *rr) { ARRAY_APPEND(jdns_rr_t, r->additionalRecords, r->additionalCount, jdns_rr_copy(rr)); } void jdns_response_remove_extra(jdns_response_t *r) { ARRAY_DELETE(r->authorityRecords, r->authorityCount, jdns_rr_delete); ARRAY_DELETE(r->additionalRecords, r->additionalCount, jdns_rr_delete); } void jdns_response_remove_answer(jdns_response_t *r, int pos) { jdns_rr_t *rr = r->answerRecords[pos]; jdns_rr_delete(rr); // free the position if(r->answerCount > 1) { memmove(r->answerRecords + pos, r->answerRecords + pos + 1, (r->answerCount - pos - 1) * sizeof(void *)); --r->answerCount; } else { jdns_free(r->answerRecords); r->answerRecords = 0; r->answerCount = 0; } } zurl-1.0.0/src/jdns/main.cpp000066400000000000000000000326161220152020200156530ustar00rootroot00000000000000/* * Copyright (C) 2005 Justin Karneges * * 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. */ #include #include #include "qjdns.h" QString dataToString(const QByteArray &buf) { QString out; for(int n = 0; n < buf.size(); ++n) { unsigned char c = (unsigned char)buf[n]; if(c == '\\') out += "\\\\"; else if(c >= 0x20 && c < 0x7f) out += c; else out += QString().sprintf("\\x%02x", (unsigned int)c); } return out; } void print_record(const QJDns::Record &r) { switch(r.type) { case QJDns::A: printf(" A: [%s] (ttl=%d)\n", qPrintable(r.address.toString()), r.ttl); break; case QJDns::Aaaa: printf(" AAAA: [%s] (ttl=%d)\n", qPrintable(r.address.toString()), r.ttl); break; case QJDns::Mx: printf(" MX: [%s] priority=%d (ttl=%d)\n", r.name.data(), r.priority, r.ttl); break; case QJDns::Srv: printf(" SRV: [%s] port=%d priority=%d weight=%d (ttl=%d)\n", r.name.data(), r.port, r.priority, r.weight, r.ttl); break; case QJDns::Cname: printf(" CNAME: [%s] (ttl=%d)\n", r.name.data(), r.ttl); break; case QJDns::Ptr: printf(" PTR: [%s] (ttl=%d)\n", r.name.data(), r.ttl); break; case QJDns::Txt: { printf(" TXT: count=%d (ttl=%d)\n", r.texts.count(), r.ttl); for(int n = 0; n < r.texts.count(); ++n) printf(" len=%d [%s]\n", r.texts[n].size(), qPrintable(dataToString(r.texts[n]))); break; } case QJDns::Hinfo: printf(" HINFO: [%s] [%s] (ttl=%d)\n", r.cpu.data(), r.os.data(), r.ttl); break; case QJDns::Ns: printf(" NS: [%s] (ttl=%d)\n", r.name.data(), r.ttl); break; default: printf(" (Unknown): type=%d, size=%d (ttl=%d)\n", r.type, r.rdata.size(), r.ttl); break; } } class App : public QObject { Q_OBJECT public: bool opt_debug, opt_ipv6, opt_quit; int quit_time; QString mode, type, name, ipaddr; QStringList nslist; QList pubitems; QJDns jdns; int req_id; App() { connect(&jdns, SIGNAL(resultsReady(int, const QJDns::Response &)), SLOT(jdns_resultsReady(int, const QJDns::Response &))); connect(&jdns, SIGNAL(published(int)), SLOT(jdns_published(int))); connect(&jdns, SIGNAL(error(int, QJDns::Error)), SLOT(jdns_error(int, QJDns::Error))); connect(&jdns, SIGNAL(shutdownFinished()), SLOT(jdns_shutdownFinished())); connect(&jdns, SIGNAL(debugLinesReady()), SLOT(jdns_debugLinesReady())); } ~App() { } public slots: void start() { if(mode == "uni") { if(!jdns.init(QJDns::Unicast, opt_ipv6 ? QHostAddress::AnyIPv6 : QHostAddress::Any)) { jdns_debugLinesReady(); printf("unable to bind\n"); emit quit(); return; } QList addrs; for(int n = 0; n < nslist.count(); ++n) { QJDns::NameServer host; QString str = nslist[n]; if(str == "mul") { if(opt_ipv6) host.address = QHostAddress("FF02::FB"); else host.address = QHostAddress("224.0.0.251"); host.port = 5353; } else { int at = str.indexOf(';'); if(at != -1) { host.address = QHostAddress(str.mid(0, at)); host.port = str.mid(at + 1).toInt(); } else { host.address = QHostAddress(str); } } if(host.address.isNull() || host.port <= 0) { printf("bad nameserver: [%s]\n", qPrintable(nslist[n])); emit quit(); return; } addrs += host; } if(addrs.isEmpty()) addrs = QJDns::systemInfo().nameServers; if(addrs.isEmpty()) { printf("no nameservers were detected or specified\n"); emit quit(); return; } jdns.setNameServers(addrs); } else { if(!jdns.init(QJDns::Multicast, opt_ipv6 ? QHostAddress::AnyIPv6 : QHostAddress::Any)) { jdns_debugLinesReady(); printf("unable to bind\n"); emit quit(); return; } } if(mode == "uni" || mode == "mul") { int x = QJDns::A; if(type == "ptr") x = QJDns::Ptr; else if(type == "srv") x = QJDns::Srv; else if(type == "a") x = QJDns::A; else if(type == "aaaa") x = QJDns::Aaaa; else if(type == "mx") x = QJDns::Mx; else if(type == "txt") x = QJDns::Txt; else if(type == "hinfo") x = QJDns::Hinfo; else if(type == "cname") x = QJDns::Cname; else if(type == "any") x = QJDns::Any; else { bool ok; int y = type.toInt(&ok); if(ok) x = y; } req_id = jdns.queryStart(name.toLatin1(), x); printf("[%d] Querying for [%s] type=%d ...\n", req_id, qPrintable(name), x); } else // publish { for(int n = 0; n < pubitems.count(); ++n) { const QJDns::Record &rr = pubitems[n]; QJDns::PublishMode m = QJDns::Unique; if(rr.type == QJDns::Ptr) m = QJDns::Shared; int id = jdns.publishStart(m, rr); printf("[%d] Publishing [%s] type=%d ...\n", id, rr.owner.data(), rr.type); } } if(opt_quit) QTimer::singleShot(quit_time * 1000, this, SLOT(doShutdown())); } signals: void quit(); private slots: void jdns_resultsReady(int id, const QJDns::Response &results) { printf("[%d] Results\n", id); for(int n = 0; n < results.answerRecords.count(); ++n) print_record(results.answerRecords[n]); if(mode == "uni") jdns.shutdown(); } void jdns_published(int id) { printf("[%d] Published\n", id); } void jdns_error(int id, QJDns::Error e) { QString str; if(e == QJDns::ErrorGeneric) str = "Generic"; else if(e == QJDns::ErrorNXDomain) str = "NXDomain"; else if(e == QJDns::ErrorTimeout) str = "Timeout"; else if(e == QJDns::ErrorConflict) str = "Conflict"; printf("[%d] Error: %s\n", id, qPrintable(str)); jdns.shutdown(); } void jdns_shutdownFinished() { emit quit(); } void jdns_debugLinesReady() { QStringList lines = jdns.debugLines(); if(opt_debug) { for(int n = 0; n < lines.count(); ++n) printf("jdns: %s\n", qPrintable(lines[n])); } } void doShutdown() { jdns.shutdown(); } }; #include "main.moc" void usage() { printf("usage: jdns (options) uni [type] [name] (nameserver(;port)|mul ...)\n"); printf(" jdns (options) mul [type] [name]\n"); printf(" jdns (options) pub [items ...]\n"); printf(" jdns sys\n"); printf("\n"); printf("options:\n"); printf(" -d show debug output\n"); printf(" -6 use ipv6\n"); printf(" -q x quit x seconds after starting\n"); printf("\n"); printf("uni/mul types: a aaaa ptr srv mx txt hinfo cname any\n"); printf("pub items: ptr:name,answer srv:name,answer,port a:name,ipaddr\n"); printf(" txt:name,str0,...,strn aaaa:name,ipaddr\n"); printf("\n"); printf("examples:\n"); printf(" jdns uni a jabber.org 192.168.0.1\n"); printf(" jdns uni srv _xmpp-client._tcp.jabber.org 192.168.0.1;53\n"); printf(" jdns uni 10 user@host._presence._tcp.local mul\n"); printf(" jdns mul a foobar.local\n"); printf(" jdns mul ptr _services._dns-sd._udp.local\n"); printf(" jdns pub a:mybox.local.,192.168.0.55\n"); printf("\n"); } int main(int argc, char **argv) { QCoreApplication app(argc, argv); if(argc < 2) { usage(); return 1; } // get args QStringList args; for(int n = 1; n < argc; ++n) args += QString(argv[n]); bool opt_debug = false; bool opt_ipv6 = false; bool opt_quit = false; int quit_time = 0; QString mode, type, name, ipaddr; QStringList nslist; QList pubitems; // options for(int n = 0; n < args.count(); ++n) { if(args[n].left(1) == "-") { if(args[n] == "-d") opt_debug = true; else if(args[n] == "-6") opt_ipv6 = true; else if(args[n] == "-q") { if(n + 1 >= args.count()) { printf("need to specify number of seconds\n"); usage(); return 1; } int x = args[n + 1].toInt(); if(x < 1) x = 30; opt_quit = true; quit_time = x; args.removeAt(n + 1); } else { printf("bad option\n"); usage(); return 1; } args.removeAt(n); --n; // adjust position } } mode = args[0]; if(mode == "uni" || mode == "mul") { if(args.count() < 3) { printf("not enough args\n"); usage(); return 1; } type = args[1]; name = args[2]; if(mode == "uni") { for(int n = 3; n < args.count(); ++n) nslist += QString(args[n]); } } else if(mode == "pub") { if(args.count() < 2) { printf("not enough args\n"); usage(); return 1; } for(int n = 1; n < args.count(); ++n) { QString arg = args[n]; int at = arg.indexOf(':'); if(at == -1) { printf("missing colon\n"); usage(); return 1; } QString type = arg.mid(0, at).toLower(); QString val = arg.mid(at + 1); if(type == "a") { QStringList list = val.split(','); if(list.count() != 2) { printf("bad format for A type\n"); usage(); return 1; } QHostAddress host(list[1]); if(host.isNull() || host.protocol() != QAbstractSocket::IPv4Protocol) { printf("bad format for A type IP address\n"); usage(); return 1; } QJDns::Record rec; rec.owner = list[0].toLatin1(); rec.type = QJDns::A; rec.ttl = 120; rec.haveKnown = true; rec.address = host; pubitems += rec; } else if(type == "aaaa") { QStringList list = val.split(','); if(list.count() != 2) { printf("bad format for AAAA type\n"); usage(); return 1; } QHostAddress host(list[1]); if(host.isNull() || host.protocol() != QAbstractSocket::IPv6Protocol) { printf("bad format for AAAA type IP address\n"); usage(); return 1; } QJDns::Record rec; rec.owner = list[0].toLatin1(); rec.type = QJDns::Aaaa; rec.ttl = 120; rec.haveKnown = true; rec.address = host; pubitems += rec; } else if(type == "srv") { QStringList list = val.split(','); if(list.count() != 3) { printf("bad format for SRV type\n"); usage(); return 1; } QJDns::Record rec; rec.owner = list[0].toLatin1(); rec.type = QJDns::Srv; rec.ttl = 120; rec.haveKnown = true; rec.name = list[1].toLatin1(); rec.priority = 0; rec.weight = 0; rec.port = list[2].toInt(); pubitems += rec; } else if(type == "ptr") { QStringList list = val.split(','); if(list.count() != 2) { printf("bad format for PTR type\n"); usage(); return 1; } QJDns::Record rec; rec.owner = list[0].toLatin1(); rec.type = QJDns::Ptr; rec.ttl = 120; rec.haveKnown = true; rec.name = list[1].toLatin1(); pubitems += rec; } else if(type == "txt") { QStringList list = val.split(','); QList texts; for(int n = 1; n < list.count(); ++n) texts += list[n].toLatin1(); QJDns::Record rec; rec.owner = list[0].toLatin1(); rec.type = QJDns::Txt; rec.ttl = 120; rec.haveKnown = true; rec.texts = texts; pubitems += rec; } else { printf("bad record type [%s]\n", qPrintable(type)); usage(); return 1; } } } else if(mode == "sys") { QJDns::SystemInfo info = QJDns::systemInfo(); printf("DNS System Information\n"); printf(" Name Servers:\n"); if(!info.nameServers.isEmpty()) { for(int n = 0; n < info.nameServers.count(); ++n) printf(" %s\n", qPrintable(info.nameServers[n].address.toString())); } else printf(" (None)\n"); printf(" Domains:\n"); if(!info.domains.isEmpty()) { for(int n = 0; n < info.domains.count(); ++n) printf(" [%s]\n", info.domains[n].data()); } else printf(" (None)\n"); printf(" Hosts:\n"); if(!info.hosts.isEmpty()) { for(int n = 0; n < info.hosts.count(); ++n) { const QJDns::DnsHost &h = info.hosts[n]; printf(" [%s] -> %s\n", h.name.data(), qPrintable(h.address.toString())); } } else printf(" (None)\n"); QHostAddress addr; printf("Primary IPv4 Multicast Address: "); addr = QJDns::detectPrimaryMulticast(QHostAddress::Any); if(!addr.isNull()) printf("%s\n", qPrintable(addr.toString())); else printf("(None)\n"); printf("Primary IPv6 Multicast Address: "); addr = QJDns::detectPrimaryMulticast(QHostAddress::AnyIPv6); if(!addr.isNull()) printf("%s\n", qPrintable(addr.toString())); else printf("(None)\n"); return 0; } else { usage(); return 1; } App a; a.opt_debug = opt_debug; a.opt_ipv6 = opt_ipv6; a.opt_quit = opt_quit; a.quit_time = quit_time; a.mode = mode; a.type = type.toLower(); a.name = name; a.ipaddr = ipaddr; a.nslist = nslist; a.pubitems = pubitems; QObject::connect(&a, SIGNAL(quit()), &app, SLOT(quit())); QTimer::singleShot(0, &a, SLOT(start())); app.exec(); return 0; } zurl-1.0.0/src/jdns/qjdns.cpp000066400000000000000000000546421220152020200160510ustar00rootroot00000000000000/* * Copyright (C) 2005-2008 Justin Karneges * * 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. */ #include "qjdns.h" #include #include "qjdns_sock.h" #include "jdns.h" // for fprintf #include namespace { // safeobj stuff, from qca void releaseAndDeleteLater(QObject *owner, QObject *obj) { obj->disconnect(owner); obj->setParent(0); obj->deleteLater(); } class SafeTimer : public QObject { Q_OBJECT public: SafeTimer(QObject *parent = 0) : QObject(parent) { t = new QTimer(this); connect(t, SIGNAL(timeout()), SIGNAL(timeout())); } ~SafeTimer() { releaseAndDeleteLater(this, t); } int interval() const { return t->interval(); } bool isActive() const { return t->isActive(); } bool isSingleShot() const { return t->isSingleShot(); } void setInterval(int msec) { t->setInterval(msec); } void setSingleShot(bool singleShot) { t->setSingleShot(singleShot); } int timerId() const { return t->timerId(); } public slots: void start(int msec) { t->start(msec); } void start() { t->start(); } void stop() { t->stop(); } signals: void timeout(); private: QTimer *t; }; } static jdns_string_t *qt2str(const QByteArray &in) { jdns_string_t *out = jdns_string_new(); jdns_string_set(out, (const unsigned char *)in.data(), in.size()); return out; } static QByteArray str2qt(const jdns_string_t *in) { return QByteArray((const char *)in->data, in->size); } static void qt2addr_set(jdns_address_t *addr, const QHostAddress &host) { if(host.protocol() == QAbstractSocket::IPv6Protocol) jdns_address_set_ipv6(addr, host.toIPv6Address().c); else jdns_address_set_ipv4(addr, host.toIPv4Address()); } static jdns_address_t *qt2addr(const QHostAddress &host) { jdns_address_t *addr = jdns_address_new(); qt2addr_set(addr, host); return addr; } static QHostAddress addr2qt(const jdns_address_t *addr) { if(addr->isIpv6) return QHostAddress(addr->addr.v6); else return QHostAddress(addr->addr.v4); } static QJDns::Record import_record(const jdns_rr_t *in) { QJDns::Record out; out.owner = QByteArray((const char *)in->owner); out.ttl = in->ttl; out.type = in->type; out.rdata = QByteArray((const char *)in->rdata, in->rdlength); // known if(in->haveKnown) { int type = in->type; if(type == QJDns::A || type == QJDns::Aaaa) { out.haveKnown = true; out.address = addr2qt(in->data.address); } else if(type == QJDns::Mx) { out.haveKnown = true; out.name = QByteArray((const char *)in->data.server->name); out.priority = in->data.server->priority; } else if(type == QJDns::Srv) { out.haveKnown = true; out.name = QByteArray((const char *)in->data.server->name); out.priority = in->data.server->priority; out.weight = in->data.server->weight; out.port = in->data.server->port; } else if(type == QJDns::Cname || type == QJDns::Ptr || type == QJDns::Ns) { out.haveKnown = true; out.name = QByteArray((const char *)in->data.name); } else if(type == QJDns::Txt) { out.haveKnown = true; out.texts.clear(); for(int n = 0; n < in->data.texts->count; ++n) out.texts += str2qt(in->data.texts->item[n]); } else if(type == QJDns::Hinfo) { out.haveKnown = true; out.cpu = str2qt(in->data.hinfo.cpu); out.os = str2qt(in->data.hinfo.os); } } return out; } static jdns_rr_t *export_record(const QJDns::Record &in) { jdns_rr_t *out = jdns_rr_new(); jdns_rr_set_owner(out, (const unsigned char *)in.owner.data()); out->ttl = in.ttl; // if we have known, use that if(in.haveKnown) { int type = in.type; if(type == QJDns::A) { jdns_address_t *addr = qt2addr(in.address); jdns_rr_set_A(out, addr); jdns_address_delete(addr); } else if(type == QJDns::Aaaa) { jdns_address_t *addr = qt2addr(in.address); jdns_rr_set_AAAA(out, addr); jdns_address_delete(addr); } else if(type == QJDns::Mx) { jdns_rr_set_MX(out, (const unsigned char *)in.name.data(), in.priority); } else if(type == QJDns::Srv) { jdns_rr_set_SRV(out, (const unsigned char *)in.name.data(), in.port, in.priority, in.weight); } else if(type == QJDns::Cname) { jdns_rr_set_CNAME(out, (const unsigned char *)in.name.data()); } else if(type == QJDns::Ptr) { jdns_rr_set_PTR(out, (const unsigned char *)in.name.data()); } else if(type == QJDns::Txt) { jdns_stringlist_t *list = jdns_stringlist_new(); for(int n = 0; n < in.texts.count(); ++n) { jdns_string_t *str = qt2str(in.texts[n]); jdns_stringlist_append(list, str); jdns_string_delete(str); } jdns_rr_set_TXT(out, list); jdns_stringlist_delete(list); } else if(type == QJDns::Hinfo) { jdns_string_t *cpu = qt2str(in.cpu); jdns_string_t *os = qt2str(in.os); jdns_rr_set_HINFO(out, cpu, os); jdns_string_delete(cpu); jdns_string_delete(os); } else if(type == QJDns::Ns) { jdns_rr_set_NS(out, (const unsigned char *)in.name.data()); } } else jdns_rr_set_record(out, in.type, (const unsigned char *)in.rdata.data(), in.rdata.size()); return out; } //---------------------------------------------------------------------------- // QJDns::NameServer //---------------------------------------------------------------------------- QJDns::NameServer::NameServer() { port = JDNS_UNICAST_PORT; } //---------------------------------------------------------------------------- // QJDns::Record //---------------------------------------------------------------------------- QJDns::Record::Record() { ttl = 0; type = -1; haveKnown = false; } bool QJDns::Record::verify() const { jdns_rr_t *rr = export_record(*this); int ok = jdns_rr_verify(rr); jdns_rr_delete(rr); return (ok ? true : false); } //---------------------------------------------------------------------------- // QJDns //---------------------------------------------------------------------------- static int my_srand_done = 0; static void my_srand() { if(my_srand_done) return; // lame attempt at randomizing without srand int count = ::time(NULL) % 128; for(int n = 0; n < count; ++n) rand(); my_srand_done = 1; } class QJDns::Private : public QObject { Q_OBJECT public: class LateError { public: int source_type; // 0 for query, 1 for publish int id; Error error; }; class LateResponse { public: int id; QJDns::Response response; bool do_cancel; }; QJDns *q; QJDns::Mode mode; jdns_session_t *sess; bool shutting_down; SafeTimer stepTrigger, debugTrigger; SafeTimer stepTimeout; QTime clock; QStringList debug_strings; bool new_debug_strings; int next_handle; bool need_handle; QHash socketForHandle; QHash handleForSocket; int pending; bool pending_wait; bool complete_shutdown; // pointers that will point to things we are currently signalling // about. when a query or publish is cancelled, we can use these // pointers to extract anything we shouldn't signal. QList *pErrors; QList *pPublished; QList *pResponses; Private(QJDns *_q) : QObject(_q), q(_q), stepTrigger(this), debugTrigger(this), stepTimeout(this), pErrors(0), pPublished(0), pResponses(0) { sess = 0; shutting_down = false; new_debug_strings = false; pending = 0; connect(&stepTrigger, SIGNAL(timeout()), SLOT(doNextStepSlot())); stepTrigger.setSingleShot(true); connect(&debugTrigger, SIGNAL(timeout()), SLOT(doDebug())); debugTrigger.setSingleShot(true); connect(&stepTimeout, SIGNAL(timeout()), SLOT(st_timeout())); stepTimeout.setSingleShot(true); my_srand(); clock.start(); } ~Private() { cleanup(); } void cleanup() { if(sess) { jdns_session_delete(sess); sess = 0; } shutting_down = false; pending = 0; // it is safe to delete the QUdpSocket objects here without // deleteLater, since this code path never occurs when // a signal from those objects is on the stack qDeleteAll(socketForHandle); socketForHandle.clear(); handleForSocket.clear(); stepTrigger.stop(); stepTimeout.stop(); need_handle = 0; } bool init(QJDns::Mode _mode, const QHostAddress &address) { mode = _mode; jdns_callbacks_t callbacks; callbacks.app = this; callbacks.time_now = cb_time_now; callbacks.rand_int = cb_rand_int; callbacks.debug_line = cb_debug_line; callbacks.udp_bind = cb_udp_bind; callbacks.udp_unbind = cb_udp_unbind; callbacks.udp_read = cb_udp_read; callbacks.udp_write = cb_udp_write; sess = jdns_session_new(&callbacks); jdns_set_hold_ids_enabled(sess, 1); next_handle = 1; need_handle = false; int ret; jdns_address_t *baddr = qt2addr(address); if(mode == Unicast) { ret = jdns_init_unicast(sess, baddr, 0); } else { jdns_address_t *maddr; if(address.protocol() == QAbstractSocket::IPv6Protocol) maddr = jdns_address_multicast6_new(); else maddr = jdns_address_multicast4_new(); ret = jdns_init_multicast(sess, baddr, JDNS_MULTICAST_PORT, maddr); jdns_address_delete(maddr); } jdns_address_delete(baddr); if(!ret) { jdns_session_delete(sess); sess = 0; return false; } return true; } void setNameServers(const QList &nslist) { jdns_nameserverlist_t *addrs = jdns_nameserverlist_new(); for(int n = 0; n < nslist.count(); ++n) { jdns_address_t *addr = qt2addr(nslist[n].address); jdns_nameserverlist_append(addrs, addr, nslist[n].port); jdns_address_delete(addr); } jdns_set_nameservers(sess, addrs); jdns_nameserverlist_delete(addrs); } void process() { if(!stepTrigger.isActive()) { stepTimeout.stop(); stepTrigger.start(); } } void processDebug() { new_debug_strings = true; if(!debugTrigger.isActive()) debugTrigger.start(); } void doNextStep() { if(shutting_down && complete_shutdown) { cleanup(); emit q->shutdownFinished(); return; } QPointer self = this; int ret = jdns_step(sess); QList errors; QList published; QList responses; bool finish_shutdown = false; pErrors = &errors; pPublished = &published; pResponses = &responses; while(1) { jdns_event_t *e = jdns_next_event(sess); if(!e) break; if(e->type == JDNS_EVENT_SHUTDOWN) { finish_shutdown = true; } else if(e->type == JDNS_EVENT_PUBLISH) { if(e->status != JDNS_STATUS_SUCCESS) { QJDns::Error error; if(e->status == JDNS_STATUS_CONFLICT) error = QJDns::ErrorConflict; else error = QJDns::ErrorGeneric; LateError le; le.source_type = 1; le.id = e->id; le.error = error; errors += le; } else { published += e->id; } } else if(e->type == JDNS_EVENT_RESPONSE) { if(e->status != JDNS_STATUS_SUCCESS) { QJDns::Error error; if(e->status == JDNS_STATUS_NXDOMAIN) error = QJDns::ErrorNXDomain; else if(e->status == JDNS_STATUS_TIMEOUT) error = QJDns::ErrorTimeout; else error = QJDns::ErrorGeneric; LateError le; le.source_type = 0; le.id = e->id; le.error = error; errors += le; } else { QJDns::Response out_response; for(int n = 0; n < e->response->answerCount; ++n) out_response.answerRecords += import_record(e->response->answerRecords[n]); LateResponse lr; lr.id = e->id; lr.response = out_response; if(mode == Unicast) lr.do_cancel = true; else lr.do_cancel = false; responses += lr; } } jdns_event_delete(e); } if(ret & JDNS_STEP_TIMER) stepTimeout.start(jdns_next_timer(sess)); else stepTimeout.stop(); need_handle = (ret & JDNS_STEP_HANDLE); // read the lists safely enough so that items can be deleted // behind our back while(!errors.isEmpty()) { LateError i = errors.takeFirst(); if(i.source_type == 0) jdns_cancel_query(sess, i.id); else jdns_cancel_publish(sess, i.id); emit q->error(i.id, i.error); if(!self) return; } while(!published.isEmpty()) { int i = published.takeFirst(); emit q->published(i); if(!self) return; } while(!responses.isEmpty()) { LateResponse i = responses.takeFirst(); if(i.do_cancel) jdns_cancel_query(sess, i.id); emit q->resultsReady(i.id, i.response); if(!self) return; } if(finish_shutdown) { // if we have pending udp packets to write, stick around if(pending > 0) { pending_wait = true; } else { complete_shutdown = true; process(); } } pErrors = 0; pPublished = 0; pResponses = 0; } void removeCancelled(int id) { if(pErrors) { for(int n = 0; n < pErrors->count(); ++n) { if(pErrors->at(n).id == id) { pErrors->removeAt(n); --n; // adjust position } } } if(pPublished) { for(int n = 0; n < pPublished->count(); ++n) { if(pPublished->at(n) == id) { pPublished->removeAt(n); --n; // adjust position } } } if(pResponses) { for(int n = 0; n < pResponses->count(); ++n) { if(pResponses->at(n).id == id) { pResponses->removeAt(n); --n; // adjust position } } } } private slots: void udp_readyRead() { QUdpSocket *sock = (QUdpSocket *)sender(); int handle = handleForSocket.value(sock); if(need_handle) { jdns_set_handle_readable(sess, handle); process(); } else { // eat packet QByteArray buf(4096, 0); QHostAddress from_addr; quint16 from_port; sock->readDatagram(buf.data(), buf.size(), &from_addr, &from_port); } } void udp_bytesWritten(qint64) { if(pending > 0) { --pending; if(shutting_down && pending_wait && pending == 0) { pending_wait = false; complete_shutdown = true; process(); } } } void st_timeout() { doNextStep(); } void doNextStepSlot() { doNextStep(); } void doDebug() { if(new_debug_strings) { new_debug_strings = false; if(!debug_strings.isEmpty()) emit q->debugLinesReady(); } } private: // jdns callbacks static int cb_time_now(jdns_session_t *, void *app) { QJDns::Private *self = (QJDns::Private *)app; return self->clock.elapsed(); } static int cb_rand_int(jdns_session_t *, void *) { return rand() % 65536; } static void cb_debug_line(jdns_session_t *, void *app, const char *str) { QJDns::Private *self = (QJDns::Private *)app; self->debug_strings += QString::fromLatin1(str); self->processDebug(); } static int cb_udp_bind(jdns_session_t *, void *app, const jdns_address_t *addr, int port, const jdns_address_t *maddr) { QJDns::Private *self = (QJDns::Private *)app; // we always pass non-null to jdns_init, so this should be a valid address QHostAddress host = addr2qt(addr); QUdpSocket *sock = new QUdpSocket(self); self->connect(sock, SIGNAL(readyRead()), SLOT(udp_readyRead())); // use queued for bytesWritten, since qt is evil and emits before writeDatagram returns qRegisterMetaType("qint64"); self->connect(sock, SIGNAL(bytesWritten(qint64)), SLOT(udp_bytesWritten(qint64)), Qt::QueuedConnection); QUdpSocket::BindMode mode; mode |= QUdpSocket::ShareAddress; mode |= QUdpSocket::ReuseAddressHint; if(!sock->bind(host, port, mode)) { delete sock; return 0; } if(maddr) { int sd = sock->socketDescriptor(); bool ok; int errorCode; if(maddr->isIpv6) ok = qjdns_sock_setMulticast6(sd, maddr->addr.v6, &errorCode); else ok = qjdns_sock_setMulticast4(sd, maddr->addr.v4, &errorCode); if(!ok) { delete sock; self->debug_strings += QString("failed to setup multicast on the socket (errorCode=%1)").arg(errorCode); self->processDebug(); return 0; } if(maddr->isIpv6) { qjdns_sock_setTTL6(sd, 255); qjdns_sock_setIPv6Only(sd); } else qjdns_sock_setTTL4(sd, 255); } int handle = self->next_handle++; self->socketForHandle.insert(handle, sock); self->handleForSocket.insert(sock, handle); return handle; } static void cb_udp_unbind(jdns_session_t *, void *app, int handle) { QJDns::Private *self = (QJDns::Private *)app; QUdpSocket *sock = self->socketForHandle.value(handle); if(!sock) return; self->socketForHandle.remove(handle); self->handleForSocket.remove(sock); delete sock; } static int cb_udp_read(jdns_session_t *, void *app, int handle, jdns_address_t *addr, int *port, unsigned char *buf, int *bufsize) { QJDns::Private *self = (QJDns::Private *)app; QUdpSocket *sock = self->socketForHandle.value(handle); if(!sock) return 0; // nothing to read? if(!sock->hasPendingDatagrams()) return 0; QHostAddress from_addr; quint16 from_port; int ret = sock->readDatagram((char *)buf, *bufsize, &from_addr, &from_port); if(ret == -1) return 0; qt2addr_set(addr, from_addr); *port = (int)from_port; *bufsize = ret; return 1; } static int cb_udp_write(jdns_session_t *, void *app, int handle, const jdns_address_t *addr, int port, unsigned char *buf, int bufsize) { QJDns::Private *self = (QJDns::Private *)app; QUdpSocket *sock = self->socketForHandle.value(handle); if(!sock) return 0; QHostAddress host = addr2qt(addr); int ret = sock->writeDatagram((const char *)buf, bufsize, host, port); if(ret == -1) { // this can happen if the datagram to send is too big. i'm not sure what else // may cause this. if we return 0, then jdns may try to resend the packet, // which might not work if it is too large (causing the same error over and // over). we'll return success to jdns, so the result is as if the packet // was dropped. return 1; } ++self->pending; return 1; } }; QJDns::QJDns(QObject *parent) :QObject(parent) { d = new Private(this); } QJDns::~QJDns() { delete d; } bool QJDns::init(Mode mode, const QHostAddress &address) { return d->init(mode, address); } void QJDns::shutdown() { d->shutting_down = true; d->pending_wait = false; d->complete_shutdown = false; jdns_shutdown(d->sess); d->process(); } QStringList QJDns::debugLines() { QStringList tmp = d->debug_strings; d->debug_strings.clear(); return tmp; } QJDns::SystemInfo QJDns::systemInfo() { SystemInfo out; jdns_dnsparams_t *params = jdns_system_dnsparams(); for(int n = 0; n < params->nameservers->count; ++n) { NameServer ns; ns.address = addr2qt(params->nameservers->item[n]->address); out.nameServers += ns; } for(int n = 0; n < params->domains->count; ++n) out.domains += str2qt(params->domains->item[n]); for(int n = 0; n < params->hosts->count; ++n) { DnsHost h; h.name = str2qt(params->hosts->item[n]->name); h.address = addr2qt(params->hosts->item[n]->address); out.hosts += h; } jdns_dnsparams_delete(params); return out; } #define PROBE_BASE 20000 #define PROBE_RANGE 100 QHostAddress QJDns::detectPrimaryMulticast(const QHostAddress &address) { my_srand(); QUdpSocket *sock = new QUdpSocket; QUdpSocket::BindMode mode; mode |= QUdpSocket::ShareAddress; mode |= QUdpSocket::ReuseAddressHint; int port = -1; for(int n = 0; n < PROBE_RANGE; ++n) { if(sock->bind(address, PROBE_BASE + n, mode)) { port = PROBE_BASE + n; break; } } if(port == -1) { delete sock; return QHostAddress(); } jdns_address_t *a; if(address.protocol() == QAbstractSocket::IPv6Protocol) a = jdns_address_multicast6_new(); else a = jdns_address_multicast4_new(); QHostAddress maddr = addr2qt(a); jdns_address_delete(a); if(address.protocol() == QAbstractSocket::IPv6Protocol) { int x; if(!qjdns_sock_setMulticast6(sock->socketDescriptor(), maddr.toIPv6Address().c, &x)) { delete sock; return QHostAddress(); } qjdns_sock_setTTL6(sock->socketDescriptor(), 0); } else { int x; if(!qjdns_sock_setMulticast4(sock->socketDescriptor(), maddr.toIPv4Address(), &x)) { delete sock; return QHostAddress(); } qjdns_sock_setTTL4(sock->socketDescriptor(), 0); } QHostAddress result; QByteArray out(128, 0); for(int n = 0; n < out.size(); ++n) out[n] = rand(); if(sock->writeDatagram(out.data(), out.size(), maddr, port) == -1) { delete sock; return QHostAddress(); } while(1) { if(!sock->waitForReadyRead(1000)) { fprintf(stderr, "QJDns::detectPrimaryMulticast: timeout while checking %s\n", qPrintable(address.toString())); delete sock; return QHostAddress(); } QByteArray in(128, 0); QHostAddress from_addr; quint16 from_port; int ret = sock->readDatagram(in.data(), in.size(), &from_addr, &from_port); if(ret == -1) { delete sock; return QHostAddress(); } if(from_port != port) continue; in.resize(ret); if(in != out) continue; result = from_addr; break; } delete sock; return result; } void QJDns::setNameServers(const QList &list) { d->setNameServers(list); } int QJDns::queryStart(const QByteArray &name, int type) { int id = jdns_query(d->sess, (const unsigned char *)name.data(), type); d->process(); return id; } void QJDns::queryCancel(int id) { jdns_cancel_query(d->sess, id); d->removeCancelled(id); d->process(); } int QJDns::publishStart(PublishMode m, const Record &record) { jdns_rr_t *rr = export_record(record); int pubmode; if(m == QJDns::Unique) pubmode = JDNS_PUBLISH_UNIQUE; else pubmode = JDNS_PUBLISH_SHARED; int id = jdns_publish(d->sess, pubmode, rr); jdns_rr_delete(rr); d->process(); return id; } void QJDns::publishUpdate(int id, const Record &record) { jdns_rr_t *rr = export_record(record); jdns_update_publish(d->sess, id, rr); jdns_rr_delete(rr); d->process(); } void QJDns::publishCancel(int id) { jdns_cancel_publish(d->sess, id); d->removeCancelled(id); d->process(); } #include "qjdns.moc" zurl-1.0.0/src/jdns/qjdns.h000066400000000000000000000065301220152020200155070ustar00rootroot00000000000000/* * Copyright (C) 2005,2006 Justin Karneges * * 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. */ // this is the Qt wrapper to jdns. it requires Qt 4.1+ #ifndef QJDNS_H #define QJDNS_H #include #include class QJDns : public QObject { Q_OBJECT public: enum Mode { Unicast, Multicast }; enum PublishMode { Unique, Shared }; enum Type { A = 1, Aaaa = 28, Mx = 15, Srv = 33, Cname = 5, Ptr = 12, Txt = 16, Hinfo = 13, Ns = 2, Any = 255 }; enum Error { ErrorGeneric, ErrorNXDomain, // query only ErrorTimeout, // query only ErrorConflict // publish only }; class NameServer { public: QHostAddress address; int port; NameServer(); }; class DnsHost { public: QByteArray name; QHostAddress address; }; class SystemInfo { public: QList nameServers; QList domains; QList hosts; }; class Record { public: QByteArray owner; int ttl; int type; QByteArray rdata; bool haveKnown; // known QHostAddress address; // for A, Aaaa QByteArray name; // for Mx, Srv, Cname, Ptr, Ns int priority; // for Mx, Srv int weight; // for Srv int port; // for Srv QList texts; // for Txt QByteArray cpu; // for Hinfo QByteArray os; // for Hinfo Record(); bool verify() const; }; class Response { public: QList answerRecords; QList authorityRecords; QList additionalRecords; }; QJDns(QObject *parent = 0); ~QJDns(); bool init(Mode mode, const QHostAddress &address); void shutdown(); QStringList debugLines(); static SystemInfo systemInfo(); static QHostAddress detectPrimaryMulticast(const QHostAddress &address); void setNameServers(const QList &list); int queryStart(const QByteArray &name, int type); void queryCancel(int id); // for multicast mode only int publishStart(PublishMode m, const Record &record); void publishUpdate(int id, const Record &record); void publishCancel(int id); signals: void resultsReady(int id, const QJDns::Response &results); void published(int id); void error(int id, QJDns::Error e); void shutdownFinished(); void debugLinesReady(); private: class Private; friend class Private; Private *d; }; #endif zurl-1.0.0/src/jdns/qjdns_sock.cpp000066400000000000000000000101121220152020200170500ustar00rootroot00000000000000/* * Copyright (C) 2005,2006 Justin Karneges * * 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. */ #include "qjdns_sock.h" #include #include #include #include #ifdef Q_OS_WIN # include # include #endif #ifdef Q_OS_UNIX # include # include # include # include # include # include # include # include #endif #ifndef QT_NO_IPV6 # define HAVE_IPV6 # ifndef s6_addr # define IPPROTO_IPV6 41 struct in6_addr { union { unsigned char _S6_u8[16]; unsigned short _S6_u16[8]; unsigned long _S6_u32[4]; } _S6_un; }; # define s6_addr _S6_un._S6_u8 # endif # ifndef IPV6_JOIN_GROUP # define IPV6_JOIN_GROUP 12 # define IPV6_MULTICAST_HOPS 10 struct ipv6_mreq { struct in6_addr ipv6mr_multiaddr; unsigned int ipv6mr_interface; }; # endif #endif static int get_last_error() { int x; #ifdef Q_OS_WIN x = WSAGetLastError(); #else x = errno; #endif return x; } bool qjdns_sock_setMulticast4(int s, unsigned long int addr, int *errorCode) { int ret; struct ip_mreq mc; memset(&mc, 0, sizeof(mc)); mc.imr_multiaddr.s_addr = htonl(addr); mc.imr_interface.s_addr = INADDR_ANY; ret = setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char *)&mc, sizeof(mc)); if(ret != 0) { if(errorCode) *errorCode = get_last_error(); return false; } return true; } bool qjdns_sock_setMulticast6(int s, unsigned char *addr, int *errorCode) { #ifdef HAVE_IPV6 int ret; struct ipv6_mreq mc; memset(&mc, 0, sizeof(mc)); memcpy(mc.ipv6mr_multiaddr.s6_addr, addr, 16); mc.ipv6mr_interface = 0; ret = setsockopt(s, IPPROTO_IPV6, IPV6_JOIN_GROUP, (const char *)&mc, sizeof(mc)); if(ret != 0) { if(errorCode) *errorCode = get_last_error(); return false; } return true; #else Q_UNUSED(s); Q_UNUSED(addr); Q_UNUSED(errorCode); return false; #endif } bool qjdns_sock_setTTL4(int s, int ttl) { unsigned char cttl; int ret, ittl; cttl = ttl; ittl = ttl; // IP_MULTICAST_TTL might take 1 byte or 4, try both ret = setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (const char *)&cttl, sizeof(cttl)); if(ret != 0) { ret = setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, (const char *)&ittl, sizeof(ittl)); if(ret != 0) return false; } return true; } bool qjdns_sock_setTTL6(int s, int ttl) { #ifdef HAVE_IPV6 unsigned char cttl; int ret, ittl; cttl = ttl; ittl = ttl; // IPV6_MULTICAST_HOPS might take 1 byte or 4, try both ret = setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (const char *)&cttl, sizeof(cttl)); if(ret != 0) { ret = setsockopt(s, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (const char *)&ittl, sizeof(ittl)); if(ret != 0) return false; } return true; #else Q_UNUSED(s); Q_UNUSED(ttl); return false; #endif } bool qjdns_sock_setIPv6Only(int s) { #if defined(HAVE_IPV6) && defined(IPV6_V6ONLY) int x = 1; if(setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, (char *)&x, sizeof(x)) != 0) return false; return true; #else Q_UNUSED(s); return false; #endif } zurl-1.0.0/src/jdns/qjdns_sock.h000066400000000000000000000026541220152020200165310ustar00rootroot00000000000000/* * Copyright (C) 2005,2006 Justin Karneges * * 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. */ #ifndef QJDNS_SOCK_H #define QJDNS_SOCK_H bool qjdns_sock_setMulticast4(int s, unsigned long int addr, int *errorCode); bool qjdns_sock_setMulticast6(int s, unsigned char *addr, int *errorCode); bool qjdns_sock_setTTL4(int s, int ttl); bool qjdns_sock_setTTL6(int s, int ttl); bool qjdns_sock_setIPv6Only(int s); #endif zurl-1.0.0/src/jdnsshared/000077500000000000000000000000001220152020200154025ustar00rootroot00000000000000zurl-1.0.0/src/jdnsshared/jdnsshared.cpp000066400000000000000000000760441220152020200202460ustar00rootroot00000000000000/* * Copyright (C) 2006-2008 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ // Note: JDnsShared supports multiple interfaces for multicast, but only one // for IPv4 and one for IPv6. Sharing multiple interfaces of the same IP // version for multicast is unfortunately not possible without reworking // the jdns subsystem. // // The reason for this limitation is that in order to do multi-interface // multicast, you have to do a single bind to Any, and then use special // functions to determine which interface a packet came from and to // specify which interface a packet should go out on. Again this is just // not possible with the current system and the assumptions made by jdns. // Note: When quering against multiple interfaces with multicast, it is // possible that different answers for a unique record may be reported // on each interface. We don't do anything about this. #include "jdnsshared.h" namespace { // safeobj stuff, from qca void releaseAndDeleteLater(QObject *owner, QObject *obj) { obj->disconnect(owner); obj->setParent(0); obj->deleteLater(); } class SafeTimer : public QObject { Q_OBJECT public: SafeTimer(QObject *parent = 0) : QObject(parent) { t = new QTimer(this); connect(t, SIGNAL(timeout()), SIGNAL(timeout())); } ~SafeTimer() { releaseAndDeleteLater(this, t); } int interval() const { return t->interval(); } bool isActive() const { return t->isActive(); } bool isSingleShot() const { return t->isSingleShot(); } void setInterval(int msec) { t->setInterval(msec); } void setSingleShot(bool singleShot) { t->setSingleShot(singleShot); } int timerId() const { return t->timerId(); } public slots: void start(int msec) { t->start(msec); } void start() { t->start(); } void stop() { t->stop(); } signals: void timeout(); private: QTimer *t; }; // for caching system info class SystemInfoCache { public: QJDns::SystemInfo info; QTime time; }; } Q_GLOBAL_STATIC(QMutex, jdnsshared_mutex) Q_GLOBAL_STATIC(SystemInfoCache, jdnsshared_infocache) static QJDns::SystemInfo get_sys_info() { QMutexLocker locker(jdnsshared_mutex()); SystemInfoCache *c = jdnsshared_infocache(); // cache info for 1/2 second, enough to prevent re-reading of sys // info 20 times because of all the different resolves if(c->time.isNull() || c->time.elapsed() >= 500) { c->info = QJDns::systemInfo(); c->time.start(); } return c->info; } static bool domainCompare(const QByteArray &a, const QByteArray &b) { return (qstricmp(a.data(), b.data()) == 0) ? true: false; } // adapted from jdns_mdnsd.c, _a_match() static bool matchRecordExceptTtl(const QJDns::Record &a, const QJDns::Record &b) { if(a.type != b.type || !domainCompare(a.owner, b.owner)) return false; if(a.type == QJDns::Srv) { if(domainCompare(a.name, b.name) && a.port == b.port && a.priority == b.priority && a.weight == b.weight) { return true; } } else if(a.type == QJDns::Ptr || a.type == QJDns::Ns || a.type == QJDns::Cname) { if(domainCompare(a.name, b.name)) return true; } else if(a.rdata == b.rdata) return true; return false; } static void getHex(unsigned char in, char *hi, char *lo) { QString str; str.sprintf("%02x", in); *hi = str[0].toLatin1(); *lo = str[1].toLatin1(); } static QByteArray getDec(int in) { return QString::number(in).toLatin1(); } static QByteArray makeReverseName(const QHostAddress &addr) { QByteArray out; if(addr.protocol() == QAbstractSocket::IPv6Protocol) { Q_IPV6ADDR raw = addr.toIPv6Address(); for(int n = 0; n < 32; ++n) { char hi, lo; getHex(raw.c[31 - n], &hi, &lo); out += lo; out += '.'; out += hi; out += '.'; } out += "ip6.arpa."; } else { quint32 rawi = addr.toIPv4Address(); int raw[4]; raw[0] = (rawi >> 24) & 0xff; raw[1] = (rawi >> 16) & 0xff; raw[2] = (rawi >> 8) & 0xff; raw[3] = rawi & 0xff; for(int n = 0; n < 4; ++n) { out += getDec(raw[3 - n]); out += '.'; } out += "in-addr.arpa."; } return out; } //---------------------------------------------------------------------------- // Handle //---------------------------------------------------------------------------- namespace { // QJDns uses integer handle ids, but they are only unique within // the relevant QJDns instance. Since we want our handles to be // unique across all instances, we'll make an instance/id pair. class Handle { public: QJDns *jdns; int id; Handle() : jdns(0), id(-1) { } Handle(QJDns *_jdns, int _id) : jdns(_jdns), id(_id) { } bool operator==(const Handle &a) const { if(a.jdns == jdns && a.id == id) return true; return false; } bool operator!=(const Handle &a) const { return !(operator==(a)); } }; // adapted from qHash static inline uint qHash(const Handle &key) { uint h1 = ::qHash(key.jdns); uint h2 = ::qHash(key.id); return ((h1 << 16) | (h1 >> 16)) ^ h2; } } //---------------------------------------------------------------------------- // JDnsShutdown //---------------------------------------------------------------------------- namespace { class JDnsShutdownAgent : public QObject { Q_OBJECT public: void start() { QMetaObject::invokeMethod(this, "started", Qt::QueuedConnection); } signals: void started(); }; class JDnsShutdownWorker : public QObject { Q_OBJECT public: QList list; JDnsShutdownWorker(const QList &_list) : QObject(0), list(_list) { foreach(JDnsShared *i, list) { connect(i, SIGNAL(shutdownFinished()), SLOT(jdns_shutdownFinished())); i->shutdown(); // MUST support DOR-DS, and it does } } signals: void finished(); private slots: void jdns_shutdownFinished() { JDnsShared *i = (JDnsShared *)sender(); list.removeAll(i); delete i; if(list.isEmpty()) emit finished(); } }; class JDnsShutdown : public QThread { Q_OBJECT public: QMutex m; QWaitCondition w; QList list; JDnsShutdownAgent *agent; JDnsShutdownWorker *worker; int phase; void waitForShutdown(const QList &_list) { list = _list; phase = 0; m.lock(); start(); w.wait(&m); foreach(JDnsShared *i, list) { i->setParent(0); i->moveToThread(this); } phase = 1; agent->start(); wait(); } protected: virtual void run() { m.lock(); agent = new JDnsShutdownAgent; connect(agent, SIGNAL(started()), SLOT(agent_started()), Qt::DirectConnection); agent->start(); exec(); delete agent; } private slots: void agent_started() { if(phase == 0) { w.wakeOne(); m.unlock(); } else { worker = new JDnsShutdownWorker(list); connect(worker, SIGNAL(finished()), SLOT(worker_finished()), Qt::DirectConnection); } } void worker_finished() { delete worker; worker = 0; quit(); } }; } //---------------------------------------------------------------------------- // JDnsSharedDebug //---------------------------------------------------------------------------- class JDnsSharedDebugPrivate : public QObject { Q_OBJECT public: JDnsSharedDebug *q; QMutex m; QStringList lines; bool dirty; JDnsSharedDebugPrivate(JDnsSharedDebug *_q) : QObject(_q), q(_q) { dirty = false; } void addDebug(const QString &name, const QStringList &_lines) { if(!_lines.isEmpty()) { QMutexLocker locker(&m); for(int n = 0; n < _lines.count(); ++n) lines += name + ": " + _lines[n]; if(!dirty) { dirty = true; QMetaObject::invokeMethod(this, "doUpdate", Qt::QueuedConnection); } } } private slots: void doUpdate() { { QMutexLocker locker(&m); if(!dirty) return; } emit q->readyRead(); } }; JDnsSharedDebug::JDnsSharedDebug(QObject *parent) :QObject(parent) { d = new JDnsSharedDebugPrivate(this); } JDnsSharedDebug::~JDnsSharedDebug() { delete d; } QStringList JDnsSharedDebug::readDebugLines() { QMutexLocker locker(&d->m); QStringList tmplines = d->lines; d->lines.clear(); d->dirty = false; return tmplines; } //---------------------------------------------------------------------------- // JDnsSharedRequest //---------------------------------------------------------------------------- class JDnsSharedPrivate : public QObject { Q_OBJECT public: class Instance { public: QJDns *jdns; QHostAddress addr; int index; Instance() : jdns(0) { } }; enum PreprocessMode { None, // don't muck with anything FillInAddress, // for A/AAAA FillInPtrOwner6, // for PTR, IPv6 FillInPtrOwner4, // for PTR, IPv4 }; JDnsShared *q; JDnsShared::Mode mode; bool shutting_down; JDnsSharedDebug *db; QString dbname; QList instances; QHash instanceForQJDns; QSet requests; QHash requestForHandle; JDnsSharedPrivate(JDnsShared *_q) : QObject(_q), q(_q) { } JDnsSharedRequest *findRequest(QJDns *jdns, int id) const { Handle h(jdns, id); return requestForHandle.value(h); } void jdns_link(QJDns *jdns) { connect(jdns, SIGNAL(resultsReady(int, const QJDns::Response &)), SLOT(jdns_resultsReady(int, const QJDns::Response &))); connect(jdns, SIGNAL(published(int)), SLOT(jdns_published(int))); connect(jdns, SIGNAL(error(int, QJDns::Error)), SLOT(jdns_error(int, QJDns::Error))); connect(jdns, SIGNAL(shutdownFinished()), SLOT(jdns_shutdownFinished())); connect(jdns, SIGNAL(debugLinesReady()), SLOT(jdns_debugLinesReady())); } int getNewIndex() const { // find lowest unused value for(int n = 0;; ++n) { bool found = false; foreach(Instance *i, instances) { if(i->index == n) { found = true; break; } } if(!found) return n; } } void addDebug(int index, const QString &line) { if(db) db->d->addDebug(dbname + QString::number(index), QStringList() << line); } void doDebug(QJDns *jdns, int index) { QStringList lines = jdns->debugLines(); if(db) db->d->addDebug(dbname + QString::number(index), lines); } PreprocessMode determinePpMode(const QJDns::Record &in) { // Note: since our implementation only allows 1 ipv4 and 1 ipv6 // interface to exist, it is safe to publish both kinds of // records on both interfaces, with the same values. For // example, an A record can be published on both interfaces, // with the value set to the ipv4 interface. If we supported // multiple ipv4 interfaces, then this wouldn't work, because // we wouldn't know which value to use for the A record when // publishing on the ipv6 interface. // publishing our own IP address? null address means the user // wants us to fill in the blank with our address. if((in.type == QJDns::Aaaa || in.type == QJDns::A) && in.address.isNull()) { return FillInAddress; } // publishing our own reverse lookup? partial owner means // user wants us to fill in the rest. else if(in.type == QJDns::Ptr && in.owner == ".ip6.arpa.") { return FillInPtrOwner6; } else if(in.type == QJDns::Ptr && in.owner == ".in-addr.arpa.") { return FillInPtrOwner4; } return None; } QJDns::Record manipulateRecord(const QJDns::Record &in, PreprocessMode ppmode, bool *modified = 0) { if(ppmode == FillInAddress) { QJDns::Record out = in; if(in.type == QJDns::Aaaa) { // are we operating on ipv6? foreach(Instance *i, instances) { if(i->addr.protocol() == QAbstractSocket::IPv6Protocol) { if(modified && !(out.address == i->addr)) *modified = true; out.address = i->addr; break; } } } else // A { // are we operating on ipv4? foreach(Instance *i, instances) { if(i->addr.protocol() == QAbstractSocket::IPv4Protocol) { if(modified && !(out.address == i->addr)) *modified = true; out.address = i->addr; break; } } } return out; } else if(ppmode == FillInPtrOwner6) { QJDns::Record out = in; // are we operating on ipv6? foreach(Instance *i, instances) { if(i->addr.protocol() == QAbstractSocket::IPv6Protocol) { QByteArray newOwner = makeReverseName(i->addr); if(modified && !(out.owner == newOwner)) *modified = true; out.owner = newOwner; break; } } return out; } else if(ppmode == FillInPtrOwner4) { QJDns::Record out = in; // are we operating on ipv4? foreach(Instance *i, instances) { if(i->addr.protocol() == QAbstractSocket::IPv4Protocol) { QByteArray newOwner = makeReverseName(i->addr); if(modified && !(out.owner == newOwner)) *modified = true; out.owner = newOwner; break; } } return out; } if(modified) *modified = false; return in; } bool addInterface(const QHostAddress &addr); void removeInterface(const QHostAddress &addr); void queryStart(JDnsSharedRequest *obj, const QByteArray &name, int qType); void queryCancel(JDnsSharedRequest *obj); void publishStart(JDnsSharedRequest *obj, QJDns::PublishMode m, const QJDns::Record &record); void publishUpdate(JDnsSharedRequest *obj, const QJDns::Record &record); void publishCancel(JDnsSharedRequest *obj); public slots: void late_shutdown() { shutting_down = false; emit q->shutdownFinished(); } private slots: void jdns_resultsReady(int id, const QJDns::Response &results); void jdns_published(int id); void jdns_error(int id, QJDns::Error e); void jdns_shutdownFinished(); void jdns_debugLinesReady(); }; class JDnsSharedRequestPrivate : public QObject { Q_OBJECT public: JDnsSharedRequest *q; JDnsSharedPrivate *jsp; // current action JDnsSharedRequest::Type type; QByteArray name; int qType; QJDns::PublishMode pubmode; JDnsSharedPrivate::PreprocessMode ppmode; QJDns::Record pubrecord; // a single request might have to perform multiple QJDns operations QList handles; // keep a list of handles that successfully publish QList published; // use to weed out dups for multicast QList queryCache; bool success; JDnsSharedRequest::Error error; QList results; SafeTimer lateTimer; JDnsSharedRequestPrivate(JDnsSharedRequest *_q) : QObject(_q), q(_q), lateTimer(this) { connect(&lateTimer, SIGNAL(timeout()), SLOT(lateTimer_timeout())); } void resetSession() { name = QByteArray(); pubrecord = QJDns::Record(); handles.clear(); published.clear(); queryCache.clear(); } private slots: void lateTimer_timeout() { emit q->resultsReady(); } }; JDnsSharedRequest::JDnsSharedRequest(JDnsShared *jdnsShared, QObject *parent) :QObject(parent) { d = new JDnsSharedRequestPrivate(this); d->jsp = jdnsShared->d; } JDnsSharedRequest::~JDnsSharedRequest() { cancel(); delete d; } JDnsSharedRequest::Type JDnsSharedRequest::type() { return d->type; } void JDnsSharedRequest::query(const QByteArray &name, int type) { cancel(); d->jsp->queryStart(this, name, type); } void JDnsSharedRequest::publish(QJDns::PublishMode m, const QJDns::Record &record) { cancel(); d->jsp->publishStart(this, m, record); } void JDnsSharedRequest::publishUpdate(const QJDns::Record &record) { // only allowed to update if we have an active publish if(!d->handles.isEmpty() && d->type == Publish) d->jsp->publishUpdate(this, record); } void JDnsSharedRequest::cancel() { d->lateTimer.stop(); if(!d->handles.isEmpty()) { if(d->type == Query) d->jsp->queryCancel(this); else d->jsp->publishCancel(this); } d->resetSession(); } bool JDnsSharedRequest::success() const { return d->success; } JDnsSharedRequest::Error JDnsSharedRequest::error() const { return d->error; } QList JDnsSharedRequest::results() const { return d->results; } //---------------------------------------------------------------------------- // JDnsShared //---------------------------------------------------------------------------- JDnsShared::JDnsShared(Mode mode, QObject *parent) :QObject(parent) { d = new JDnsSharedPrivate(this); d->mode = mode; d->shutting_down = false; d->db = 0; } JDnsShared::~JDnsShared() { foreach(JDnsSharedPrivate::Instance *i, d->instances) { delete i->jdns; delete i; } delete d; } void JDnsShared::setDebug(JDnsSharedDebug *db, const QString &name) { d->db = db; d->dbname = name; } bool JDnsShared::addInterface(const QHostAddress &addr) { return d->addInterface(addr); } void JDnsShared::removeInterface(const QHostAddress &addr) { d->removeInterface(addr); } void JDnsShared::shutdown() { d->shutting_down = true; if(!d->instances.isEmpty()) { foreach(JDnsSharedPrivate::Instance *i, d->instances) i->jdns->shutdown(); } else QMetaObject::invokeMethod(d, "late_shutdown", Qt::QueuedConnection); } QList JDnsShared::domains() { return get_sys_info().domains; } void JDnsShared::waitForShutdown(const QList &instances) { JDnsShutdown s; s.waitForShutdown(instances); } bool JDnsSharedPrivate::addInterface(const QHostAddress &addr) { if(shutting_down) return false; // make sure we don't have this one already foreach(Instance *i, instances) { if(i->addr == addr) return false; } int index = getNewIndex(); addDebug(index, QString("attempting to use interface %1").arg(addr.toString())); QJDns *jdns; if(mode == JDnsShared::UnicastInternet || mode == JDnsShared::UnicastLocal) { jdns = new QJDns(this); jdns_link(jdns); if(!jdns->init(QJDns::Unicast, addr)) { doDebug(jdns, index); delete jdns; return false; } if(mode == JDnsShared::UnicastLocal) { QJDns::NameServer host; if(addr.protocol() == QAbstractSocket::IPv6Protocol) host.address = QHostAddress("FF02::FB"); else host.address = QHostAddress("224.0.0.251"); host.port = 5353; jdns->setNameServers(QList() << host); } } else // Multicast { // only one multicast interface allowed per IP protocol version. // this is because we bind to INADDR_ANY. bool have_v6 = false; bool have_v4 = false; foreach(Instance *i, instances) { if(i->addr.protocol() == QAbstractSocket::IPv6Protocol) have_v6 = true; else have_v4 = true; } bool is_v6 = (addr.protocol() == QAbstractSocket::IPv6Protocol) ? true : false; if(is_v6 && have_v6) { addDebug(index, "already have an ipv6 interface"); return false; } if(!is_v6 && have_v4) { addDebug(index, "already have an ipv4 interface"); return false; } QHostAddress actualBindAddress; if(is_v6) actualBindAddress = QHostAddress::AnyIPv6; else actualBindAddress = QHostAddress::Any; jdns = new QJDns(this); jdns_link(jdns); if(!jdns->init(QJDns::Multicast, actualBindAddress)) { doDebug(jdns, index); delete jdns; return false; } } Instance *i = new Instance; i->jdns = jdns; i->addr = addr; i->index = index; instances += i; instanceForQJDns.insert(i->jdns, i); addDebug(index, "interface ready"); if(mode == JDnsShared::Multicast) { // extend active requests to this interface foreach(JDnsSharedRequest *obj, requests) { if(obj->d->type == JDnsSharedRequest::Query) { Handle h(i->jdns, i->jdns->queryStart(obj->d->name, obj->d->qType)); obj->d->handles += h; requestForHandle.insert(h, obj); } else // Publish { bool modified; obj->d->pubrecord = manipulateRecord(obj->d->pubrecord, obj->d->ppmode, &modified); // if the record changed, update on the other (existing) interfaces if(modified) { foreach(Handle h, obj->d->handles) h.jdns->publishUpdate(h.id, obj->d->pubrecord); } // publish the record on the new interface Handle h(i->jdns, i->jdns->publishStart(obj->d->pubmode, obj->d->pubrecord)); obj->d->handles += h; requestForHandle.insert(h, obj); } } } return true; } void JDnsSharedPrivate::removeInterface(const QHostAddress &addr) { Instance *i = 0; for(int n = 0; n < instances.count(); ++n) { if(instances[n]->addr == addr) { i = instances[n]; break; } } if(!i) return; int index = i->index; // we don't cancel operations or shutdown jdns, we simply // delete our references. this is because if the interface // is gone, then we have nothing to send on anyway. foreach(JDnsSharedRequest *obj, requests) { for(int n = 0; n < obj->d->handles.count(); ++n) { Handle h = obj->d->handles[n]; if(h.jdns == i->jdns) { // see above, no need to cancel the operation obj->d->handles.removeAt(n); requestForHandle.remove(h); break; } } // remove published reference if(obj->d->type == JDnsSharedRequest::Publish) { for(int n = 0; n < obj->d->published.count(); ++n) { Handle h = obj->d->published[n]; if(h.jdns == i->jdns) { obj->d->published.removeAt(n); break; } } } } // see above, no need to shutdown jdns instanceForQJDns.remove(i->jdns); instances.removeAll(i); delete i->jdns; delete i; // if that was the last interface to be removed, then there should // be no more handles left. let's take action with these // handleless requests. foreach(JDnsSharedRequest *obj, requests) { if(obj->d->handles.isEmpty()) { if(mode == JDnsShared::UnicastInternet || mode == JDnsShared::UnicastLocal) { // for unicast, we'll invalidate with ErrorNoNet obj->d->success = false; obj->d->error = JDnsSharedRequest::ErrorNoNet; obj->d->lateTimer.start(); } else // Multicast { // for multicast, we'll keep all requests alive. // activity will resume when an interface is // added. } } } addDebug(index, QString("removing from %1").arg(addr.toString())); } void JDnsSharedPrivate::queryStart(JDnsSharedRequest *obj, const QByteArray &name, int qType) { obj->d->type = JDnsSharedRequest::Query; obj->d->success = false; obj->d->results.clear(); obj->d->name = name; obj->d->qType = qType; // is the input an IP address and the qType is an address record? if(qType == QJDns::Aaaa || qType == QJDns::A) { QHostAddress addr; if(addr.setAddress(QString::fromLocal8Bit(name))) { if(qType == QJDns::Aaaa && addr.protocol() == QAbstractSocket::IPv6Protocol) { QJDns::Record rec; rec.owner = name; rec.type = QJDns::Aaaa; rec.ttl = 120; rec.haveKnown = true; rec.address = addr; obj->d->success = true; obj->d->results = QList() << rec; obj->d->lateTimer.start(); return; } else if(qType == QJDns::A && addr.protocol() == QAbstractSocket::IPv4Protocol) { QJDns::Record rec; rec.owner = name; rec.type = QJDns::A; rec.ttl = 120; rec.haveKnown = true; rec.address = addr; obj->d->success = true; obj->d->results = QList() << rec; obj->d->lateTimer.start(); return; } } } QJDns::SystemInfo sysInfo = get_sys_info(); // is the input name a known host and the qType is an address record? if(qType == QJDns::Aaaa || qType == QJDns::A) { QByteArray lname = name.toLower(); QList known = sysInfo.hosts; foreach(QJDns::DnsHost host, known) { if(((qType == QJDns::Aaaa && host.address.protocol() == QAbstractSocket::IPv6Protocol) || (qType == QJDns::A && host.address.protocol() == QAbstractSocket::IPv4Protocol)) && host.name.toLower() == lname) { QJDns::Record rec; rec.owner = name; rec.type = qType; rec.ttl = 120; rec.haveKnown = true; rec.address = host.address; obj->d->success = true; obj->d->results = QList() << rec; obj->d->lateTimer.start(); return; } } } // if we have no QJDns instances to operate on, then error if(instances.isEmpty()) { obj->d->error = JDnsSharedRequest::ErrorNoNet; obj->d->lateTimer.start(); return; } if(mode == JDnsShared::UnicastInternet) { // get latest nameservers, split into ipv6/v4, apply to jdns instances QList ns_v6; QList ns_v4; { QList nameServers = sysInfo.nameServers; foreach(QJDns::NameServer ns, nameServers) { if(ns.address.protocol() == QAbstractSocket::IPv6Protocol) ns_v6 += ns; else ns_v4 += ns; } } foreach(Instance *i, instances) { if(i->addr.protocol() == QAbstractSocket::IPv6Protocol) i->jdns->setNameServers(ns_v6); else i->jdns->setNameServers(ns_v4); } } // keep track of this request requests += obj; // query on all jdns instances foreach(Instance *i, instances) { Handle h(i->jdns, i->jdns->queryStart(name, qType)); obj->d->handles += h; // keep track of this handle for this request requestForHandle.insert(h, obj); } } void JDnsSharedPrivate::queryCancel(JDnsSharedRequest *obj) { if(!requests.contains(obj)) return; foreach(Handle h, obj->d->handles) { h.jdns->queryCancel(h.id); requestForHandle.remove(h); } obj->d->handles.clear(); requests.remove(obj); } void JDnsSharedPrivate::publishStart(JDnsSharedRequest *obj, QJDns::PublishMode m, const QJDns::Record &record) { obj->d->type = JDnsSharedRequest::Publish; obj->d->success = false; obj->d->results.clear(); obj->d->pubmode = m; obj->d->ppmode = determinePpMode(record); obj->d->pubrecord = manipulateRecord(record, obj->d->ppmode); // if we have no QJDns instances to operate on, then error if(instances.isEmpty()) { obj->d->error = JDnsSharedRequest::ErrorNoNet; obj->d->lateTimer.start(); return; } // keep track of this request requests += obj; // attempt to publish on all jdns instances foreach(JDnsSharedPrivate::Instance *i, instances) { Handle h(i->jdns, i->jdns->publishStart(m, obj->d->pubrecord)); obj->d->handles += h; // keep track of this handle for this request requestForHandle.insert(h, obj); } } void JDnsSharedPrivate::publishUpdate(JDnsSharedRequest *obj, const QJDns::Record &record) { if(!requests.contains(obj)) return; obj->d->ppmode = determinePpMode(record); obj->d->pubrecord = manipulateRecord(record, obj->d->ppmode); // publish update on all handles for this request foreach(Handle h, obj->d->handles) h.jdns->publishUpdate(h.id, obj->d->pubrecord); } void JDnsSharedPrivate::publishCancel(JDnsSharedRequest *obj) { if(!requests.contains(obj)) return; foreach(Handle h, obj->d->handles) { h.jdns->publishCancel(h.id); requestForHandle.remove(h); } obj->d->handles.clear(); obj->d->published.clear(); requests.remove(obj); } void JDnsSharedPrivate::jdns_resultsReady(int id, const QJDns::Response &results) { QJDns *jdns = (QJDns *)sender(); JDnsSharedRequest *obj = findRequest(jdns, id); Q_ASSERT(obj); obj->d->success = true; obj->d->results = results.answerRecords; if(mode == JDnsShared::UnicastInternet || mode == JDnsShared::UnicastLocal) { // only one response, so "cancel" it for(int n = 0; n < obj->d->handles.count(); ++n) { Handle h = obj->d->handles[n]; if(h.jdns == jdns && h.id == id) { obj->d->handles.removeAt(n); requestForHandle.remove(h); break; } } // cancel related handles foreach(Handle h, obj->d->handles) { h.jdns->queryCancel(h.id); requestForHandle.remove(h); } obj->d->handles.clear(); requests.remove(obj); } else // Multicast { // check our cache to see how we should report these results for(int n = 0; n < obj->d->results.count(); ++n) { QJDns::Record &r = obj->d->results[n]; // do we have this answer already in our cache? QJDns::Record *c = 0; int c_at = -1; for(int k = 0; k < obj->d->queryCache.count(); ++k) { QJDns::Record &tmp = obj->d->queryCache[k]; if(matchRecordExceptTtl(r, tmp)) { c = &tmp; c_at = k; break; } } // don't report duplicates or unknown removals if((c && r.ttl != 0) || (!c && r.ttl == 0)) { obj->d->results.removeAt(n); --n; // adjust position continue; } // if we have it, and it is removed, remove from cache if(c && r.ttl == 0) { obj->d->queryCache.removeAt(c_at); } // otherwise, if we don't have it, add it to the cache else if(!c) { obj->d->queryCache += r; } } if(obj->d->results.isEmpty()) return; } emit obj->resultsReady(); } void JDnsSharedPrivate::jdns_published(int id) { QJDns *jdns = (QJDns *)sender(); JDnsSharedRequest *obj = findRequest(jdns, id); Q_ASSERT(obj); // find handle Handle handle; for(int n = 0; n < obj->d->handles.count(); ++n) { Handle h = obj->d->handles[n]; if(h.jdns == jdns && h.id == id) { handle = h; break; } } obj->d->published += handle; // if this publish has already been considered successful, then // a publish has succeeded on a new interface and there's no // need to report success for this request again if(obj->d->success) return; // all handles published? if(obj->d->published.count() == obj->d->handles.count()) { obj->d->success = true; emit obj->resultsReady(); } } void JDnsSharedPrivate::jdns_error(int id, QJDns::Error e) { QJDns *jdns = (QJDns *)sender(); JDnsSharedRequest *obj = findRequest(jdns, id); Q_ASSERT(obj); // "cancel" it for(int n = 0; n < obj->d->handles.count(); ++n) { Handle h = obj->d->handles[n]; if(h.jdns == jdns && h.id == id) { obj->d->handles.removeAt(n); requestForHandle.remove(h); break; } } if(obj->d->type == JDnsSharedRequest::Query) { // ignore the error if it is not the last error if(!obj->d->handles.isEmpty()) return; requests.remove(obj); obj->d->success = false; JDnsSharedRequest::Error x = JDnsSharedRequest::ErrorGeneric; if(e == QJDns::ErrorNXDomain) x = JDnsSharedRequest::ErrorNXDomain; else if(e == QJDns::ErrorTimeout) x = JDnsSharedRequest::ErrorTimeout; else // ErrorGeneric x = JDnsSharedRequest::ErrorGeneric; obj->d->error = x; emit obj->resultsReady(); } else // Publish { // cancel related handles foreach(Handle h, obj->d->handles) { h.jdns->publishCancel(h.id); requestForHandle.remove(h); } obj->d->handles.clear(); obj->d->published.clear(); requests.remove(obj); obj->d->success = false; JDnsSharedRequest::Error x = JDnsSharedRequest::ErrorGeneric; if(e == QJDns::ErrorConflict) x = JDnsSharedRequest::ErrorConflict; else // ErrorGeneric x = JDnsSharedRequest::ErrorGeneric; obj->d->error = x; emit obj->resultsReady(); } } void JDnsSharedPrivate::jdns_shutdownFinished() { QJDns *jdns = (QJDns *)sender(); addDebug(instanceForQJDns.value(jdns)->index, "jdns_shutdownFinished, removing interface"); Instance *instance = instanceForQJDns.value(jdns); delete instance->jdns; delete instance; instanceForQJDns.remove(jdns); instances.removeAll(instance); if(instances.isEmpty()) late_shutdown(); } void JDnsSharedPrivate::jdns_debugLinesReady() { QJDns *jdns = (QJDns *)sender(); doDebug(jdns, instanceForQJDns.value(jdns)->index); } #include "jdnsshared.moc" zurl-1.0.0/src/jdnsshared/jdnsshared.h000066400000000000000000000501131220152020200177000ustar00rootroot00000000000000/* * Copyright (C) 2006,2007 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ #ifndef JDNSSHARED_H #define JDNSSHARED_H #include "qjdns.h" class JDnsShared; class JDnsSharedPrivate; class JDnsSharedRequestPrivate; class JDnsSharedDebugPrivate; /** \brief Collects debugging information from JDnsShared \note Iris users should utilize NetNames for DNS capabilities, not JDnsSharedDebug. See the JDnsShared documentation for more information. JDnsSharedDebug is used to collect debugging information from one or many JDnsShared objects. To use it, simply create it and pass it to JDnsShared::setDebug(). Example use: \code JDnsSharedDebug *db = new JDnsSharedDebug; connect(db, SIGNAL(debugLinesReady(const QStringList &)), SLOT(db_debugLinesReady(const QStringList &))); JDnsShared *jdnsShared1 = new JDnsShared(JDnsShared::UnicastInternet); jdnsShared1->setDebug(db, "U"); JDnsShared *jdnsShared2 = new JDnsShared(JDnsShared::UnicastLocal); jdnsShared2->setDebug(db, "L"); ... void db_debugLinesReady(const QStringList &lines) { foreach(QString line, lines) printf("%s\n", qPrintable(line)); } \endcode JDnsShared reports debug lines with the name and interface number prepended to each line. For example, if there is debug information to report about the second interface added to \a jdnsShared2 in the above example, the lines would be prepended with "L1: ". Do not destroy JDnsSharedDebug until all of the JDnsShared objects associated with it have been destroyed. \sa JDnsShared JDnsSharedRequest */ class JDnsSharedDebug : public QObject { Q_OBJECT public: /** \brief Constructs a new object with the given \a parent */ JDnsSharedDebug(QObject *parent = 0); /** \brief Destroys the object */ ~JDnsSharedDebug(); /** \brief Read the available debug information Debug information is reported as a series of lines. The lines are of reasonable length, and so if you're storing a backlog of the most recent debug information, it should be safe to make the cut-off point based on lines. \sa readyRead */ QStringList readDebugLines(); signals: /** \brief Emitted when there is debug information to report \sa readDebugLines */ void readyRead(); private: friend class JDnsShared; friend class JDnsSharedPrivate; friend class JDnsSharedDebugPrivate; JDnsSharedDebugPrivate *d; }; /** \brief Performs a DNS operation using JDnsShared \note Iris users should utilize NetNames for DNS capabilities, not JDnsSharedRequest. See the JDnsShared documentation for more information. JDnsSharedRequest is used to perform DNS operations on a JDnsShared object. Many requests may be performed simultaneously, such that a single JDnsShared object can be "shared" across the application. Please see the JDnsShared documentation for more complete information about how the overall system works. Call query() to perform a query. Call publish() (or publishUpdate()) to make DNS records available on the local network (JDnsShared::Multicast mode only). When the operation has something to report, the resultsReady() signal is emitted. Call success() to determine the status of the operation. If success() returns false, then the operation has failed and the reason for the failure can be determined with error(). If success() returns true, then the meaning differs depending on the type of operation being performed:
  • For JDnsShared::UnicastInternet and JDnsShared::UnicastLocal modes, call results() to obtain the records obtained by the query. In these modes, resultsReady() is only emitted once, at which point the operation is no longer active.
  • For JDnsShared::Multicast, operations are long-lived. Query operations never timeout, and resultsReady() may be emitted multiple times. In order to stop the query, either call cancel() or destroy the JDnsSharedRequest object. Similarly, publishing is long-lived. The record stays published as long as the JDnsSharedRequest has not been cancelled or destroyed.
Here is how you might look up an A record: \code JDnsSharedRequest *req = new JDnsSharedRequest(jdnsShared); connect(req, SIGNAL(resultsReady()), SLOT(req_resultsReady())); req->query("psi-im.org", QJDns::A); ... void req_resultsReady() { if(req->success()) { // print all of the IP addresses obtained QList results = req->results(); foreach(QJDns::Record r, results) { if(r.type == QJDns::A) printf("%s\n", qPrintable(r.address.toString()); } } else printf("Error resolving!\n"); } \endcode Here is an example of publishing a record: \code JDnsSharedRequest *pub = new JDnsSharedRequest(jdnsShared); connect(pub, SIGNAL(resultsReady()), SLOT(pub_resultsReady())); // let's publish an A record QJDns::Record rec; rec.owner = "SomeComputer.local."; rec.type = QJDns::A; rec.ttl = 120; rec.haveKnown = true; rec.address = QHostAddress("192.168.0.32"); pub->publish(QJDns::Unique, rec); ... void pub_resultsReady() { if(pub->success()) printf("Record published\n"); else printf("Error publishing!\n"); } \endcode To update an existing record, use publishUpdate(): \code // the IP address of the host changed, so make a new record QJDns::Record rec; rec.owner = "SomeComputer.local."; rec.type = QJDns::A; rec.ttl = 120; rec.haveKnown = true; rec.address = QHostAddress("192.168.0.64"); // update it pub->publishUpdate(rec); \endcode As a special exception, the address value can be left unspecified for A and Aaaa record types, which tells JDnsShared to substitute the address value with the address of whatever interfaces the record gets published on. This is the preferred way to publish the IP address of your own machine, and in fact it is the only way to do so if you have multiple interfaces, because there will likely be a different IP address value for each interface (the record resolves to a different answer depending on which interface a query comes from). \code // let's publish our own A record QJDns::Record rec; rec.owner = "MyComputer.local."; rec.type = QJDns::A; rec.ttl = 120; rec.haveKnown = true; rec.address = QHostAddress(); pub->publish(QJDns::Unique, rec); \endcode When you want to unpublish, call cancel() or destroy the JDnsSharedRequest. \sa JDnsShared */ class JDnsSharedRequest : public QObject { Q_OBJECT public: /** \brief Operation type */ enum Type { Query, ///< Query operation, initiated by query() Publish ///< Publish operation, initiated by publish() or publishUpdate() }; /** \brief Request error */ enum Error { ErrorNoNet, ///< There are no available network interfaces to operate on. This happens if JDnsShared::addInterface() was not called. ErrorGeneric, ///< Generic error during the operation. ErrorNXDomain, ///< The name looked up does not exist. ErrorTimeout, ///< The operation timed out. ErrorConflict ///< Attempt to publish an already published unique record. }; /** \brief Constructs a new object with the given \a jdnsShared and \a parent */ JDnsSharedRequest(JDnsShared *jdnsShared, QObject *parent = 0); /** \brief Destroys the object If there is an active operation, it is cancelled. */ ~JDnsSharedRequest(); /** \brief The type of operation being performed */ Type type(); /** \brief Perform a query operation */ void query(const QByteArray &name, int type); /** \brief Perform a publish operation */ void publish(QJDns::PublishMode m, const QJDns::Record &record); /** \brief Update a record that is currently published */ void publishUpdate(const QJDns::Record &record); /** \brief Cancels the current operation */ void cancel(); /** \brief Indicates whether or not the operation was successful */ bool success() const; /** \brief Returns the reason for error */ Error error() const; /** \brief Returns the results of the operation */ QList results() const; signals: /** \brief Indicates that the operation has something to report After receiving this signal, call success() to check on the status of the operation, followed by results() or error() as appropriate. */ void resultsReady(); private: friend class JDnsShared; friend class JDnsSharedPrivate; friend class JDnsSharedRequestPrivate; JDnsSharedRequestPrivate *d; }; /** \brief Abstraction layer on top of QJDns \note Iris users should utilize NetNames for DNS capabilities, not JDnsShared. JDnsShared is provided for non-Iris users (and it is also used internally by NetNames). To use JDnsShared by itself, simply drop the jdnsshared.h and jdnsshared.cpp files, along with JDNS, into your project. It is not a full replacement for Qt's Q3Dns, as some tasks are left to you, but it covers most of it. QJDns supports everything a typical application should ever need in DNS. However, it is expected that modern applications will need to maintain multiple QJDns instances at the same time, and this is where things can get complicated. For example, most applications will want at least two QJDns instances: one for IPv4 unicast and one for IPv6 unicast. A single JDnsShared object encapsulates multiple instances of QJDns that are related. For example, an IPv4 unicast instance and an IPv6 unicast instance could be coupled within JDnsShared. Then, when a unicast operation is performed on the JDnsShared object, both underlying instances will be queried as appropriate. The application would not need to perform two resolutions itself, nor deal with any related complexity. Further, individual operations are performed using a separate class called JDnsSharedRequest, eliminating the need for the application to directly interface with a central QJDns object or track integer handles. This makes it easier for individual parts of the application to "share" the same instance (or set of instances) of QJDns, hence the name. JDnsShared is a thin abstraction. QJDns subtypes (e.g. QJDns::Type, QJDns::Record, etc) are still used with JDnsShared. Because of the duplication of documentation effort between NetNames and QJDns, there is no formal documentation for QJDns. Users of JDnsShared will need to read qjdns.h, although a basic explanation of the elements can be found below. Types:
QJDns::TypeThis is a convenience enumeration for common DNS record types. For example: A, Aaaa, Srv, etc. The values directly map to the integer values of the DNS protocol (e.g. Srv = 33). See qjdns.h for all of the types and values.
QJDns::RecordThis class holds a DNS record. The main fields are type (integer type, probably something listed in QJDns::Type), rdata (QByteArray of the record value), and haveKnown (boolean to indicate if a decoded form of the record value is also available). See qjdns.h for the possible known fields. You will most-likely always work with known types. Received records that have a type listed in QJDns::Type are guaranteed to be known and will provide a decoded value. If you are creating a record for publishing, you will need to set owner, ttl, and type. If the type to be published is listed in QJDns::Type, then you will need to set haveKnown to true and set the known fields as appropriate, otherwise you need to set rdata. You do not need to supply an encoded form in rdata for known types, it can be left empty in that case.
QJDns::PublishModeThis is for Multicast DNS, and can either be Unique or Shared. A shared record can be published by multiple owners (for example, a "_ssh._tcp.local." PTR record might resolve to many different SSH services owned by different machines). A unique record can only have one owner (for example, a "mycomputer.local." A record would resolve to the IP address of the machine that published it). Attempting to publish a record on a network where a unique record is already present will result in a conflict error.
Functions:
QJDns::detectPrimaryMulticast()Detects a multicast interface. Pass QHostAddress::Any or QHostAddress::AnyIPv6, depending on which type of interface is desired.
To use JDnsShared, first create an instance of it, set it up by calling addInterface() as necessary, and then use JDnsSharedRequest to perform operations on it. Here is an example of how to create and set up a JDnsShared object for typical DNS resolution: \code // construct JDnsShared *dns = new JDnsShared(JDnsShared::UnicastInternet); // add IPv4 and IPv6 interfaces dns->addInterface(QHostAddress::Any); dns->addInterface(QHostAddress::AnyIPv6); // at this point, the object is ready for operation \endcode Perform a resolution like this: \code JDnsSharedRequest *req = new JDnsSharedRequest(dns); connect(req, SIGNAL(resultsReady()), SLOT(req_resultsReady())); req->query("psi-im.org", QJDns::A); ... void req_resultsReady() { if(req->success()) { // print all of the IP addresses obtained QList results = req->results(); foreach(QJDns::Record r, results) { if(r.type == QJDns::A) printf("%s\n", qPrintable(r.address.toString()); } } else printf("Error resolving!\n"); } \endcode It is important to filter the results as shown in the above example. QJDns guarantees at least one record in the results will be of the type queried for, but there may also be CNAME records present (of course, if the query was for a CNAME type, then the results will only be CNAME records). The recommended approach is to simply filter for the record types desired, as shown, rather than single out CNAME specifically. When you are finished with a JDnsShared object, it should be shut down before deleting: \code connect(dns, SIGNAL(shutdownFinished()), SLOT(dns_shutdownFinished())); dns->shutdown(); ... void dns_shutdownFinished() { delete dns; } \endcode Setting up JDnsShared for UnicastLocal and Multicast mode is done the same way as with UnicastInternet. For example, here is how Multicast mode could be set up: \code // construct JDnsShared *dns = new JDnsShared(JDnsShared::Multicast); // add IPv4 interface QHostAddress addr = QJDns::detectPrimaryMulticast(QHostAddress::Any); dns->addInterface(addr); // at this point, the object is ready for operation \endcode JDnsShared provides a lot of functionality, but certain aspects of DNS are deemed out of its scope. Below are the responsibilities of the user of JDnsShared, if a more complete DNS behavior is desired:
  • Querying for several "qualified" names. You should first query for the name as provided, and if that fails then query for name + ".domain" (for every domain the computer is in). See domains().
  • Detecting for ".local" in the name to be queried, and using that to decide whether to query via Multicast/UnicastLocal or UnicastInternet.
  • For zeroconf/Bonjour, keep in mind that JDnsShared only provides low-level record queries. DNS-SD and any higher layers would be your job.
Using a custom DNS implementation, such as JDnsShared, has the drawback that it is difficult to take advantage of platform-specific features (for example, an OS-wide DNS cache or LDAP integration). An application strategy for normal DNS should probably be:
  • If an A or AAAA record is desired, use a native lookup.
  • Else, if the platform has advanced DNS features already (ie, res_query), use those.
  • Else, use JDnsShared.
For Multicast DNS, awareness of the platform is doubly important. There should only be one Multicast DNS "Responder" per computer, and using JDnsShared in Multicast mode at the same time could result in a conflict. An application strategy for Multicast DNS should be:
  • If the platform has a Multicast DNS daemon installed already, use it somehow.
  • Else, use JDnsShared.
\sa JDnsSharedRequest */ class JDnsShared : public QObject { Q_OBJECT public: /** \brief The mode to operate in */ enum Mode { /** For regular DNS resolution. In this mode, lookups are performed on all interfaces, and the first returned result is used. */ UnicastInternet, /** Perform regular DNS resolution using the Multicast DNS address. This is used to resolve large and/or known Multicast DNS names without actually multicasting anything. */ UnicastLocal, /** Multicast DNS querying and publishing. \note For Multicast mode, JDnsShared supports up to one interface for each IP version (e.g. one IPv4 interface and one IPv6 interface), and expects the default/primary multicast interface for that IP version to be used. */ Multicast }; /** \brief Constructs a new object with the given \a mode and \a parent */ JDnsShared(Mode mode, QObject *parent = 0); /** \brief Destroys the object */ ~JDnsShared(); /** \brief Sets the debug object to report to If a debug object is set using this function, then JDnsShared will send output text to it, prefixing each line with \a name. */ void setDebug(JDnsSharedDebug *db, const QString &name); /** \brief Adds an interface to operate on For UnicastInternet and UnicastLocal, these will almost always be QHostAddress::Any or QHostAddress::AnyIPv6 (operate on the default interface for IPv4 or IPv6, respectively). For Multicast, it is expected that the default/primary multicast interface will be used here. Do not pass QHostAddress::Any (or AnyIPv6) with Multicast mode. Returns true if the interface was successfully added, otherwise returns false. */ bool addInterface(const QHostAddress &addr); /** \brief Removes a previously-added interface */ void removeInterface(const QHostAddress &addr); /** \brief Shuts down the object This operation primarily exists for Multicast mode, so that any published records have a chance to be unpublished. If the JDnsShared object is simply deleted without performing a shutdown, then published records will linger on the network until their TTLs expire. When shutdown is complete, the shutdownFinished() signal will be emitted. */ void shutdown(); /** \brief The domains to search in You should perform a separate resolution for every domain configured on this machine. */ static QList domains(); /** \brief Performs a blocking shutdown of many JDnsShared instances This function is a convenient way to shutdown multiple JDnsShared instances synchronously. The internal shutdown procedure uses no more than a few cycles of the eventloop, so it should be safe to call without worry of the application being overly stalled. This function takes ownership of the instances passed to it, and will delete them upon completion. It is worth noting that this function is implemented without the use of a nested eventloop. All of the JDnsShared instances are moved into a temporary thread to perform the shutdown procedure, which should not cause any unexpected behavior in the current thread. \code QList list; list += jdnsShared_unicast; list += jdnsShared_multicast; JDnsShared::waitForShutdown(list); // collect remaining debug information QStringList finalDebugLines = jdnsSharedDebug.readDebugLines(); \endcode */ static void waitForShutdown(const QList &instances); signals: /** \brief Indicates the object has been shut down */ void shutdownFinished(); private: friend class JDnsSharedRequest; friend class JDnsSharedPrivate; JDnsSharedPrivate *d; }; #endif zurl-1.0.0/src/main.cpp000066400000000000000000000026131220152020200147070ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include #include #ifdef USE_CURL #include #endif #ifdef USE_QNAM #include #endif #include "app.h" class AppMain : public QObject { Q_OBJECT public: App *app; public slots: void start() { app = new App(this); connect(app, SIGNAL(quit()), SLOT(app_quit())); app->start(); } void app_quit() { delete app; emit quit(); } signals: void quit(); }; int main(int argc, char **argv) { #ifdef USE_QNAM QCA::Initializer qcaInit; #endif QCoreApplication qapp(argc, argv); AppMain appMain; QObject::connect(&appMain, SIGNAL(quit()), &qapp, SLOT(quit())); QTimer::singleShot(0, &appMain, SLOT(start())); return qapp.exec(); } #include "main.moc" zurl-1.0.0/src/qzmq/000077500000000000000000000000001220152020200142455ustar00rootroot00000000000000zurl-1.0.0/src/src.pri000066400000000000000000000020701220152020200145570ustar00rootroot00000000000000COMMON_DIR = $$PWD/common INCLUDEPATH += $$PWD/jdns include(jdns/jdns.pri) INCLUDEPATH += $$PWD/jdnsshared HEADERS += $$PWD/jdnsshared/jdnsshared.h SOURCES += $$PWD/jdnsshared/jdnsshared.cpp INCLUDEPATH += $$PWD/qzmq/src include(qzmq/src/src.pri) INCLUDEPATH += $$COMMON_DIR DEFINES += NO_IRISNET HEADERS += \ $$COMMON_DIR/processquit.h \ $$COMMON_DIR/tnetstring.h \ $$COMMON_DIR/httpheaders.h \ $$COMMON_DIR/zhttprequestpacket.h \ $$COMMON_DIR/zhttpresponsepacket.h \ $$COMMON_DIR/bufferlist.h \ $$COMMON_DIR/log.h SOURCES += \ $$COMMON_DIR/processquit.cpp \ $$COMMON_DIR/tnetstring.cpp \ $$COMMON_DIR/httpheaders.cpp \ $$COMMON_DIR/zhttprequestpacket.cpp \ $$COMMON_DIR/zhttpresponsepacket.cpp \ $$COMMON_DIR/bufferlist.cpp \ $$COMMON_DIR/log.cpp HEADERS += \ $$PWD/httprequest.h use_curl { DEFINES += USE_CURL SOURCES += $$PWD/httprequest_curl.cpp } else { DEFINES += USE_QNAM SOURCES += $$PWD/httprequest_qnam.cpp } HEADERS += \ $$PWD/appconfig.h \ $$PWD/worker.h \ $$PWD/app.h SOURCES += \ $$PWD/worker.cpp \ $$PWD/app.cpp \ $$PWD/main.cpp zurl-1.0.0/src/src.pro000066400000000000000000000004351220152020200145700ustar00rootroot00000000000000CONFIG += console CONFIG -= app_bundle QT -= gui QT += network TARGET = zurl DESTDIR = .. CONFIG += use_curl MOC_DIR = $$OUT_PWD/_moc OBJECTS_DIR = $$OUT_PWD/_obj include($$OUT_PWD/../conf.pri) include(src.pri) unix:!isEmpty(BINDIR) { target.path = $$BINDIR INSTALLS += target } zurl-1.0.0/src/worker.cpp000066400000000000000000000346631220152020200153060ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "worker.h" #include #include #include #include #include "jdnsshared.h" #include "httprequest.h" #include "zhttprequestpacket.h" #include "zhttpresponsepacket.h" #include "bufferlist.h" #include "log.h" #include "appconfig.h" #define SESSION_EXPIRE 60000 class Worker::Private : public QObject { Q_OBJECT public: Worker *q; JDnsShared *dns; AppConfig *config; QByteArray toAddress; QByteArray rid; int inSeq, outSeq; int outCredits; bool outStream; QVariant userData; int maxResponseSize; bool ignorePolicies; HttpRequest *hreq; bool quiet; bool sentHeader; bool bodySent; bool stuffToRead; BufferList inbuf; // for single mode int bytesReceived; bool pendingSend; QTimer *expireTimer; QTimer *httpExpireTimer; QTimer *keepAliveTimer; Private(JDnsShared *_dns, AppConfig *_config, Worker *_q) : QObject(_q), q(_q), dns(_dns), config(_config), hreq(0), pendingSend(false), expireTimer(0), httpExpireTimer(0), keepAliveTimer(0) { } ~Private() { } void cleanup() { delete hreq; hreq = 0; if(expireTimer) { expireTimer->disconnect(this); expireTimer->setParent(0); expireTimer->deleteLater(); expireTimer = 0; } if(httpExpireTimer) { httpExpireTimer->disconnect(this); httpExpireTimer->setParent(0); httpExpireTimer->deleteLater(); httpExpireTimer = 0; } if(keepAliveTimer) { keepAliveTimer->disconnect(this); keepAliveTimer->setParent(0); keepAliveTimer->deleteLater(); keepAliveTimer = 0; } } void start(const QVariant &vrequest, Mode mode) { outSeq = 0; outCredits = 0; quiet = false; ZhttpRequestPacket request; if(!request.fromVariant(vrequest)) { log_warning("failed to parse zurl request"); QVariantHash vhash = vrequest.toHash(); rid = vhash.value("id").toByteArray(); assert(!rid.isEmpty()); // app layer ensures this toAddress = vhash.value("from").toByteArray(); QByteArray type = vhash.value("type").toByteArray(); if(!toAddress.isEmpty() && type != "error" && type != "cancel") { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); } else { cleanup(); QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection); } return; } rid = request.id; toAddress = request.from; userData = request.userData; sentHeader = false; stuffToRead = false; bytesReceived = 0; ignorePolicies = request.ignorePolicies; // streaming only allowed on streaming interface if(mode == Worker::Stream) outStream = request.stream; else outStream = false; // some required fields if(request.method.isEmpty() || request.uri.isEmpty()) { log_warning("missing request method or missing uri"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } log_info("IN id=%s, %s %s", request.id.data(), qPrintable(request.method), request.uri.toEncoded().data()); // inbound streaming must start with sequence number of 0 if(mode == Worker::Stream && request.more && request.seq != 0) { log_warning("streamed input must start with seq 0"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } // fire and forget if(mode == Worker::Stream && toAddress.isEmpty()) quiet = true; // can't use these two together if(mode == Worker::Single && request.more) { log_warning("cannot use streamed input on router interface"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } bodySent = false; inSeq = request.seq; if(!isAllowed(request.uri.host()) || (!request.connectHost.isEmpty() && !isAllowed(request.connectHost))) { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "policy-violation")); return; } /*if(request.more && !request.headers.contains("Content-Length")) { log_warning("streamed input requires content-length"); QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "length-required")); return; }*/ hreq = new HttpRequest(dns, this); connect(hreq, SIGNAL(nextAddress(const QHostAddress &)), SLOT(req_nextAddress(const QHostAddress &))); connect(hreq, SIGNAL(readyRead()), SLOT(req_readyRead())); connect(hreq, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int))); connect(hreq, SIGNAL(error()), SLOT(req_error())); maxResponseSize = request.maxSize; if(!request.connectHost.isEmpty()) hreq->setConnectHost(request.connectHost); if(request.connectPort != -1) request.uri.setPort(request.connectPort); hreq->setIgnoreTlsErrors(request.ignoreTlsErrors); if(request.credits != -1) outCredits += request.credits; HttpHeaders headers = request.headers; if(!headers.contains("Content-Length")) { if(request.more) { // ensure chunked encoding headers.removeAll("Transfer-Encoding"); headers += HttpHeader("Transfer-Encoding", "chunked"); } else { // ensure content-length if(!request.body.isEmpty() || (request.method != "OPTIONS" && request.method != "HEAD" && request.method != "GET" && request.method != "DELETE")) { headers += HttpHeader("Content-Length", QByteArray::number(request.body.size())); } } } httpExpireTimer = new QTimer(this); connect(httpExpireTimer, SIGNAL(timeout()), SLOT(httpExpire_timeout())); httpExpireTimer->setSingleShot(true); httpExpireTimer->start(config->sessionTimeout * 1000); if(mode == Worker::Stream) { expireTimer = new QTimer(this); connect(expireTimer, SIGNAL(timeout()), SLOT(expire_timeout())); expireTimer->setSingleShot(true); expireTimer->start(SESSION_EXPIRE); keepAliveTimer = new QTimer(this); connect(keepAliveTimer, SIGNAL(timeout()), SLOT(keepAlive_timeout())); keepAliveTimer->start(SESSION_EXPIRE / 2); } hreq->start(request.method, request.uri, headers); if(!request.body.isEmpty()) hreq->writeBody(request.body); if(!request.more) { bodySent = true; hreq->endBody(); } else { // send cts ZhttpResponsePacket resp; resp.type = ZhttpResponsePacket::Credit; resp.credits = config->sessionBufferSize; writeResponse(resp); } } void write(const QVariant &vrequest) { ZhttpRequestPacket request; if(!request.fromVariant(vrequest)) { QVariantHash vhash = vrequest.toHash(); if(vhash["type"].toByteArray() != "cancel") { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); } else { cleanup(); QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection); } return; } // cancel session if a wrong sequenced packet is received if(inSeq == -1 || request.seq == -1 || request.seq != inSeq + 1) { if(request.type != ZhttpRequestPacket::Cancel) { QMetaObject::invokeMethod(this, "respondCancel", Qt::QueuedConnection); } else { cleanup(); QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection); } return; } if(request.type == ZhttpRequestPacket::Cancel) { cleanup(); QMetaObject::invokeMethod(q, "finished", Qt::QueuedConnection); return; } refreshTimeout(); inSeq = request.seq; // all we care about from follow-up writes are body and credits if(request.credits != -1) outCredits += request.credits; if(request.type == ZhttpRequestPacket::Data) { if(bodySent) { QMetaObject::invokeMethod(this, "respondError", Qt::QueuedConnection, Q_ARG(QByteArray, "bad-request")); return; } refreshHttpTimeout(); if(!request.body.isEmpty()) hreq->writeBody(request.body); // the 'more' flag only has significance if body field present if(!request.more) { bodySent = true; hreq->endBody(); } } // if we needed credits to send something, take care of that now if(request.credits != -1 && stuffToRead) trySend(); } static bool matchExp(const QString &exp, const QString &s) { int at = exp.indexOf('*'); if(at != -1) { QString start = exp.mid(0, at); QString end = exp.mid(at + 1); return (s.startsWith(start, Qt::CaseInsensitive) && s.endsWith(end, Qt::CaseInsensitive)); } else return s.compare(exp, Qt::CaseInsensitive); } bool checkAllow(const QString &in) const { foreach(const QString &exp, config->allowExps) { if(matchExp(exp, in)) return true; } return false; } bool checkDeny(const QString &in) const { foreach(const QString &exp, config->denyExps) { if(matchExp(exp, in)) return true; } return false; } bool isAllowed(const QString &in) const { if(ignorePolicies) return true; if(config->defaultPolicy == "allow") return !checkDeny(in) || checkAllow(in); else return checkAllow(in) && !checkDeny(in); } // emits signals, but safe to delete after void writeResponse(const ZhttpResponsePacket &resp) { ZhttpResponsePacket out = resp; out.from = config->clientId; out.id = rid; out.seq = outSeq++; out.userData = userData; // only log if error or body packet. this way we don't log cts or credits-only packets if(out.type == ZhttpResponsePacket::Error) { log_info("OUT ERR id=%s condition=%s", out.id.data(), out.condition.data()); } else if(out.type == ZhttpResponsePacket::Data) { if(resp.code != -1) log_info("OUT id=%s code=%d %d%s", out.id.data(), out.code, out.body.size(), out.more ? " M" : ""); else log_debug("OUT id=%s %d%s", out.id.data(), out.body.size(), out.more ? " M" : ""); } if(!quiet) emit q->readyRead(toAddress, out.toVariant()); } void doSend() { if(!pendingSend) { pendingSend = true; QMetaObject::invokeMethod(this, "trySend", Qt::QueuedConnection); } } void refreshTimeout() { expireTimer->start(SESSION_EXPIRE); } void refreshHttpTimeout() { httpExpireTimer->start(config->sessionTimeout * 1000); } private slots: // emits signals, but safe to delete after void trySend() { QPointer self = this; pendingSend = false; stuffToRead = false; ZhttpResponsePacket resp; resp.type = ZhttpResponsePacket::Data; if(!sentHeader) { resp.code = hreq->responseCode(); resp.reason = hreq->responseReason(); resp.headers = hreq->responseHeaders(); sentHeader = true; } // note: we always set body, even if empty if(outStream) { // note: we skip credits handling if quiet mode QByteArray buf; if(!quiet) buf = hreq->readResponseBody(outCredits); else buf = hreq->readResponseBody(); // all if(!buf.isEmpty()) { if(maxResponseSize != -1 && bytesReceived + buf.size() > maxResponseSize) { respondError("max-size-exceeded"); return; } } resp.body = buf; bytesReceived += resp.body.size(); if(!quiet) outCredits -= resp.body.size(); resp.more = (hreq->bytesAvailable() > 0 || !hreq->isFinished()); if(hreq->bytesAvailable() > 0) stuffToRead = true; } else { resp.body = inbuf.take(); } writeResponse(resp); if(!self) return; if(!resp.more) { cleanup(); emit q->finished(); } } void respondError(const QByteArray &condition) { QPointer self = this; ZhttpResponsePacket resp; resp.type = ZhttpResponsePacket::Error; resp.condition = condition; writeResponse(resp); if(!self) return; cleanup(); emit q->finished(); } void respondCancel() { QPointer self = this; ZhttpResponsePacket resp; resp.type = ZhttpResponsePacket::Cancel; writeResponse(resp); if(!self) return; cleanup(); emit q->finished(); } void req_nextAddress(const QHostAddress &addr) { if(!isAllowed(addr.toString())) respondError("policy-violation"); } void req_readyRead() { refreshHttpTimeout(); stuffToRead = true; if(outStream) { // only wait for credits if not quiet if(!quiet && outCredits < 1) return; } else { // for non-streaming, collect the response QByteArray buf = hreq->readResponseBody(); if(!buf.isEmpty()) { if(maxResponseSize != -1 && bytesReceived + buf.size() > maxResponseSize) { respondError("max-size-exceeded"); return; } inbuf += buf; bytesReceived += buf.size(); } if(!hreq->isFinished()) return; } // this will defer for a cycle, to pick up a potential disconnect as well doSend(); } void req_bytesWritten(int count) { if(!bodySent) { ZhttpResponsePacket resp; resp.type = ZhttpResponsePacket::Credit; resp.credits = count; writeResponse(resp); } } void req_error() { QByteArray condition; switch(hreq->errorCondition()) { case HttpRequest::ErrorPolicy: condition = "policy-violation"; break; case HttpRequest::ErrorConnect: condition = "remote-connection-failed"; break; case HttpRequest::ErrorTls: condition = "tls-error"; break; case HttpRequest::ErrorTimeout: condition = "connection-timeout"; break; case HttpRequest::ErrorBodyNotAllowed: condition = "content-not-allowed"; break; case HttpRequest::ErrorGeneric: default: condition = "undefined-condition"; break; } respondError(condition); } void expire_timeout() { cleanup(); emit q->finished(); } void httpExpire_timeout() { respondError("session-timeout"); } void keepAlive_timeout() { ZhttpResponsePacket resp; resp.type = ZhttpResponsePacket::KeepAlive; writeResponse(resp); } }; Worker::Worker(JDnsShared *dns, AppConfig *config, QObject *parent) : QObject(parent) { d = new Private(dns, config, this); } Worker::~Worker() { delete d; } QByteArray Worker::rid() const { return d->rid; } void Worker::start(const QVariant &request, Mode mode) { d->start(request, mode); } void Worker::write(const QVariant &request) { d->write(request); } #include "worker.moc" zurl-1.0.0/src/worker.h000066400000000000000000000024121220152020200147360ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef WORKER_H #define WORKER_H #include class QVariant; class JDnsShared; class AppConfig; class Worker : public QObject { Q_OBJECT public: enum Mode { Single, // for REQ/REP Stream // for PUSH/PUB }; Worker(JDnsShared *dns, AppConfig *config, QObject *parent = 0); ~Worker(); QByteArray rid() const; void start(const QVariant &request, Mode mode); void write(const QVariant &request); signals: void readyRead(const QByteArray &receiver, const QVariant &response); void finished(); private: class Private; friend class Private; Private *d; }; #endif zurl-1.0.0/tools/000077500000000000000000000000001220152020200136265ustar00rootroot00000000000000zurl-1.0.0/tools/get.py000066400000000000000000000012761220152020200147650ustar00rootroot00000000000000import sys import uuid import tnetstring import zmq if len(sys.argv) < 2: print "usage: %s [url]" % sys.argv[0] sys.exit(1) ctx = zmq.Context() sock = ctx.socket(zmq.REQ) sock.connect("tcp://127.0.0.1:5553") req = dict() req["id"] = str(uuid.uuid4()) req["method"] = "GET" req["uri"] = sys.argv[1] #req["ignore-tls-errors"] = True sock.send("T" + tnetstring.dumps(req)) resp = tnetstring.loads(sock.recv()[1:]) if "type" in resp and resp["type"] == "error": print "error: %s" % resp["condition"] sys.exit(1) print "code=%d reason=[%s]" % (resp["code"], resp["reason"]) for h in resp["headers"]: print "%s: %s" % (h[0], h[1]) if "body" in resp: print "\n%s" % resp["body"] else: print "\n" zurl-1.0.0/tools/getstream.py000066400000000000000000000024061220152020200161750ustar00rootroot00000000000000import sys import time import uuid import tnetstring import zmq client_id = "getstream.py" ctx = zmq.Context() out_sock = ctx.socket(zmq.PUSH) out_sock.connect("tcp://127.0.0.1:5550") out_stream_sock = ctx.socket(zmq.ROUTER) out_stream_sock.connect("tcp://127.0.0.1:5551") in_sock = ctx.socket(zmq.SUB) in_sock.setsockopt(zmq.SUBSCRIBE, client_id) in_sock.connect("tcp://127.0.0.1:5552") time.sleep(0.5) rid = str(uuid.uuid4()) inseq = 0 outseq = 0 out_sock.send("T" + tnetstring.dumps({"from": client_id, "id": rid, "seq": outseq, "method": "GET", "uri": sys.argv[1], "stream": True, "credits": 230000})) outseq += 1 while True: buf = in_sock.recv() at = buf.find(" ") receiver = buf[:at] indata = tnetstring.loads(buf[at + 2:]) if indata["id"] != rid: continue print "IN: %s" % indata assert(indata["seq"] == inseq) inseq += 1 if ("type" in indata and (indata["type"] == "error" or indata["type"] == "cancel")) or ("type" not in indata and "more" not in indata): break raddr = indata["from"] if "body" in indata and len(indata["body"]) > 0: outdata = {"id": rid, "from": client_id, "seq": outseq, "type": "credit", "credits": len(indata["body"])} print "OUT: %s" % outdata out_stream_sock.send_multipart([raddr, "", tnetstring.dumps(outdata)]) outseq += 1 zurl-1.0.0/tools/post.py000066400000000000000000000037021220152020200151670ustar00rootroot00000000000000import sys import time import uuid import tnetstring import zmq client_id = "post.py" ctx = zmq.Context() out_sock = ctx.socket(zmq.PUSH) out_sock.connect("tcp://127.0.0.1:5550") out_stream_sock = ctx.socket(zmq.ROUTER) out_stream_sock.connect("tcp://127.0.0.1:5551") in_sock = ctx.socket(zmq.SUB) in_sock.setsockopt(zmq.SUBSCRIBE, client_id) in_sock.connect("tcp://127.0.0.1:5552") time.sleep(0.5) pos = 0 file = open(sys.argv[2], "r").read() rid = str(uuid.uuid4()) outseq = 0 outcredits = 0 out_sock.send("T" + tnetstring.dumps({"from": client_id, "id": rid, "seq": outseq, "method": "POST", "uri": sys.argv[1], "headers": [["Content-Length", str(len(file))]], "stream": True, "credits": 200000, "more": True})) outseq += 1 while True: buf = in_sock.recv() at = buf.find(" ") receiver = buf[:at] data = tnetstring.loads(buf[at + 2:]) print "IN: %s %s" % (receiver, data) if ("type" in data and data["type"] == "error") or ("type" not in data and "more" not in data): break if "type" in data and data["type"] == "keep-alive": odata = {"id": rid, "from": client_id, "seq": outseq, "type": "keep-alive"} print "OUT: %s" % odata out_stream_sock.send_multipart([raddr, "", "T" + tnetstring.dumps(odata)]) outseq += 1 continue if "credits" in data: outcredits += data["credits"] raddr = data["from"] if "body" in data and len(data["body"]) > 0: odata = {"id": rid, "from": client_id, "seq": outseq, "type": "credit", "credits": len(data["body"])} print "OUT: %s" % odata out_stream_sock.send_multipart([raddr, "", "T" + tnetstring.dumps(odata)]) outseq += 1 if pos < len(file) and outcredits > 0: chunk = file[pos:pos + outcredits] outcredits -= len(chunk) pos += len(chunk) odata = {"id": rid, "from": client_id, "seq": outseq, "body": chunk} print len(chunk), pos, len(file) if pos < len(file): odata["more"] = True print "OUT: %s" % odata out_stream_sock.send_multipart([raddr, "", "T" + tnetstring.dumps(odata)]) outseq += 1 zurl-1.0.0/zurl.conf.example000066400000000000000000000012621220152020200157640ustar00rootroot00000000000000[General] # instance routing id. keep blank for random. set for better error recovery instance_id= # bind PULL for initiating a request in_spec=tcp://*:5550 # bind DEALER for continuing a request in_stream_spec=tcp://*:5551 # bind PUB for responding out_spec=tcp://*:5552 # bind ROUTER for handling non-streamed requests/responses in_req_spec=tcp://*:5553 # default policy, one of "allow" or "deny" defpolicy=allow # hosts to allow allow= # hosts to deny deny=127.*,10.*,192.168.*,*.local # worker count max_open_requests=2000 # input buffer size per request buffer_size=200000 # expiration time (in seconds) for inactive requests timeout=600 # advanced in_hwm=1000 out_hwm=1000 zurl-1.0.0/zurl.pro000066400000000000000000000000431220152020200142010ustar00rootroot00000000000000TEMPLATE = subdirs SUBDIRS += src zurl-1.0.0/zurl.qc000066400000000000000000000004611220152020200140100ustar00rootroot00000000000000 Zurl zurl.pro qcm pax_global_header00006660000000000000000000000064121734201160014507gustar00rootroot0000000000000052 comment=d1c3813c84f7fff7bc340d12f00cd02db8fd42ae zurl-1.0.0/src/common/000077500000000000000000000000001217342011600145605ustar00rootroot00000000000000zurl-1.0.0/src/common/.gitignore000066400000000000000000000000521217342011600165450ustar00rootroot00000000000000*.swp *~ qrc_* *.moc *.o *.pdb ui_* moc_* zurl-1.0.0/src/common/README.md000066400000000000000000000000651217342011600160400ustar00rootroot00000000000000common ====== files common to more than one project zurl-1.0.0/src/common/bufferlist.cpp000066400000000000000000000041211217342011600174270ustar00rootroot00000000000000/* * Copyright (C) 2013 Fanout, 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 . */ #include "bufferlist.h" #include BufferList::BufferList() : size_(0), offset_(0) { } void BufferList::clear() { bufs_.clear(); size_ = 0; offset_ = 0; } void BufferList::append(const QByteArray &buf) { if(buf.size() < 1) return; bufs_ += buf; size_ += buf.size(); } QByteArray BufferList::take(int size) { if(size_ == 0 || size == 0) return QByteArray(); int toRead; if(size > 0) toRead = qMin(size, size_); else toRead = size_; assert(!bufs_.isEmpty()); // if we're reading the exact size of the first buffer, cheaply // return it if(offset_ == 0 && bufs_.first().size() == toRead) { size_ -= toRead; return bufs_.takeFirst(); } QByteArray out; out.resize(toRead); char *outp = out.data(); while(toRead > 0) { QByteArray &buf = bufs_.first(); int bsize = qMin(buf.size() - offset_, toRead); memcpy(outp, buf.data() + offset_, bsize); if(offset_ + bsize >= buf.size()) { bufs_.removeFirst(); offset_ = 0; } else offset_ += bsize; toRead -= bsize; size_ -= bsize; outp += bsize; } return out; } QByteArray BufferList::toByteArray() { if(size_ == 0) return QByteArray(); QByteArray out; while(!bufs_.isEmpty()) { if(offset_ > 0) { out += bufs_.first().mid(offset_); offset_ = 0; bufs_.removeFirst(); } else out += bufs_.takeFirst(); } // keep the rewritten buffer as the only buffer bufs_ += out; return out; } zurl-1.0.0/src/common/bufferlist.h000066400000000000000000000022761217342011600171050ustar00rootroot00000000000000/* * Copyright (C) 2013 Fanout, 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 . */ #ifndef BUFFERLIST_H #define BUFFERLIST_H #include #include class BufferList { public: BufferList(); int size() const { return size_; } bool isEmpty() const { return size_ == 0; } void clear(); void append(const QByteArray &buf); QByteArray take(int size = -1); QByteArray toByteArray(); // non-const because we rewrite the list BufferList & operator+=(const QByteArray &buf) { append(buf); return *this; } private: QList bufs_; int size_; int offset_; }; #endif zurl-1.0.0/src/common/httpheaders.cpp000066400000000000000000000046151217342011600176050ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "httpheaders.h" static QList header_split(const QByteArray &in) { QList parts = in.split(','); for(int n = 0; n < parts.count(); ++n) parts[n] = parts[n].trimmed(); return parts; } bool HttpHeaders::contains(const QByteArray &key) const { for(int n = 0; n < count(); ++n) { if(qstricmp(at(n).first.data(), key.data()) == 0) return true; } return false; } QByteArray HttpHeaders::get(const QByteArray &key) const { for(int n = 0; n < count(); ++n) { const HttpHeader &h = at(n); if(qstricmp(h.first.data(), key.data()) == 0) return h.second; } return QByteArray(); } QList HttpHeaders::getAll(const QByteArray &key, bool split) const { QList out; for(int n = 0; n < count(); ++n) { const HttpHeader &h = at(n); if(qstricmp(h.first.data(), key.data()) == 0) { if(split) out += header_split(h.second); else out += h.second; } } return out; } QList HttpHeaders::takeAll(const QByteArray &key, bool split) { QList out; for(int n = 0; n < count(); ++n) { const HttpHeader &h = at(n); if(qstricmp(h.first.data(), key.data()) == 0) { if(split) out += header_split(h.second); else out += h.second; removeAt(n); --n; // adjust position } } return out; } void HttpHeaders::removeAll(const QByteArray &key) { for(int n = 0; n < count(); ++n) { if(qstricmp(at(n).first.data(), key.data()) == 0) { removeAt(n); --n; // adjust position } } } QByteArray HttpHeaders::join(const QList &values) { QByteArray out; bool first = true; foreach(const QByteArray &val, values) { if(!first) out += ", "; out += val; first = false; } return out; } zurl-1.0.0/src/common/httpheaders.h000066400000000000000000000023441217342011600172470ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef HTTPHEADERS_H #define HTTPHEADERS_H #include #include #include typedef QPair HttpHeader; class HttpHeaders : public QList { public: bool contains(const QByteArray &key) const; QByteArray get(const QByteArray &key) const; QList getAll(const QByteArray &key, bool split = true) const; QList takeAll(const QByteArray &key, bool split = true); void removeAll(const QByteArray &key); static QByteArray join(const QList &values); }; #endif zurl-1.0.0/src/common/log.cpp000066400000000000000000000043341217342011600160510ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "log.h" #include #include #include #include #include Q_GLOBAL_STATIC(QMutex, g_mutex) static int g_level = LOG_LEVEL_DEBUG; static QTime g_time; static void log(int level, const char *fmt, va_list ap) { g_mutex()->lock(); int current_level = g_level; int elapsed = g_time.elapsed(); g_mutex()->unlock(); if(level <= current_level) { QString str; str.vsprintf(fmt, ap); const char *lstr; switch(level) { case LOG_LEVEL_ERROR: lstr = "ERR"; break; case LOG_LEVEL_WARNING: lstr = "WARN"; break; case LOG_LEVEL_INFO: lstr = "INFO"; break; case LOG_LEVEL_DEBUG: default: lstr = "DEBUG"; break; } QTime t(0, 0); t = t.addMSecs(elapsed); fprintf(stderr, "[%s] %s %s\n", lstr, qPrintable(t.toString("HH:mm:ss.zzz")), qPrintable(str)); } } void log_startClock() { QMutexLocker locker(g_mutex()); g_time.start(); } int log_outputLevel() { QMutexLocker locker(g_mutex()); return g_level; } void log_setOutputLevel(int level) { QMutexLocker locker(g_mutex()); g_level = level; } void log_error(const char *fmt, ...) { va_list ap; va_start(ap, fmt); log(LOG_LEVEL_ERROR, fmt, ap); va_end(ap); } void log_warning(const char *fmt, ...) { va_list ap; va_start(ap, fmt); log(LOG_LEVEL_WARNING, fmt, ap); va_end(ap); } void log_info(const char *fmt, ...) { va_list ap; va_start(ap, fmt); log(LOG_LEVEL_INFO, fmt, ap); va_end(ap); } void log_debug(const char *fmt, ...) { va_list ap; va_start(ap, fmt); log(LOG_LEVEL_DEBUG, fmt, ap); va_end(ap); } zurl-1.0.0/src/common/log.h000066400000000000000000000021341217342011600155120ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef LOG_H #define LOG_H // really simply logging stuff #define LOG_LEVEL_ERROR 0 #define LOG_LEVEL_WARNING 1 #define LOG_LEVEL_INFO 2 #define LOG_LEVEL_DEBUG 3 void log_startClock(); int log_outputLevel(); void log_setOutputLevel(int level); void log_error(const char *fmt, ...); void log_warning(const char *fmt, ...); void log_info(const char *fmt, ...); void log_debug(const char *fmt, ...); #endif zurl-1.0.0/src/common/processquit.cpp000066400000000000000000000121101217342011600176400ustar00rootroot00000000000000/* * Copyright (C) 2006 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ #include "processquit.h" #ifndef NO_IRISNET # include "irisnetglobal_p.h" #endif #ifdef QT_GUI_LIB # include #endif #ifdef Q_OS_WIN # include #endif #ifdef Q_OS_UNIX # include # include #endif namespace { // safeobj stuff, from qca void releaseAndDeleteLater(QObject *owner, QObject *obj) { obj->disconnect(owner); obj->setParent(0); obj->deleteLater(); } class SafeSocketNotifier : public QObject { Q_OBJECT public: SafeSocketNotifier(int socket, QSocketNotifier::Type type, QObject *parent = 0) : QObject(parent) { sn = new QSocketNotifier(socket, type, this); connect(sn, SIGNAL(activated(int)), SIGNAL(activated(int))); } ~SafeSocketNotifier() { sn->setEnabled(false); releaseAndDeleteLater(this, sn); } bool isEnabled() const { return sn->isEnabled(); } int socket() const { return sn->socket(); } QSocketNotifier::Type type() const { return sn->type(); } public slots: void setEnabled(bool enable) { sn->setEnabled(enable); } signals: void activated(int socket); private: QSocketNotifier *sn; }; } #ifndef NO_IRISNET namespace XMPP { #endif Q_GLOBAL_STATIC(QMutex, pq_mutex) static ProcessQuit *g_pq = 0; inline bool is_gui_app() { #ifdef QT_GUI_LIB return (QApplication::type() != QApplication::Tty); #else return false; #endif } class ProcessQuit::Private : public QObject { Q_OBJECT public: ProcessQuit *q; bool done; #ifdef Q_OS_WIN bool use_handler; #endif #ifdef Q_OS_UNIX int sig_pipe[2]; SafeSocketNotifier *sig_notifier; #endif Private(ProcessQuit *_q) : QObject(_q), q(_q) { done = false; #ifdef Q_OS_WIN use_handler = !is_gui_app(); if(use_handler) SetConsoleCtrlHandler((PHANDLER_ROUTINE)winHandler, TRUE); #endif #ifdef Q_OS_UNIX if(pipe(sig_pipe) == -1) { // no support then return; } sig_notifier = new SafeSocketNotifier(sig_pipe[0], QSocketNotifier::Read, this); connect(sig_notifier, SIGNAL(activated(int)), SLOT(sig_activated(int))); unixWatchAdd(SIGINT); unixWatchAdd(SIGHUP); unixWatchAdd(SIGTERM); #endif } ~Private() { #ifdef Q_OS_WIN if(use_handler) SetConsoleCtrlHandler((PHANDLER_ROUTINE)winHandler, FALSE); #endif #ifdef Q_OS_UNIX unixWatchRemove(SIGINT); unixWatchRemove(SIGHUP); unixWatchRemove(SIGTERM); delete sig_notifier; close(sig_pipe[0]); close(sig_pipe[1]); #endif } #ifdef Q_OS_WIN static BOOL winHandler(DWORD ctrlType) { Q_UNUSED(ctrlType); QMetaObject::invokeMethod(g_pq->d, "ctrl_ready", Qt::QueuedConnection); return TRUE; } #endif #ifdef Q_OS_UNIX static void unixHandler(int sig) { Q_UNUSED(sig); unsigned char c = 0; if(::write(g_pq->d->sig_pipe[1], &c, 1) == -1) { // TODO: error handling? return; } } void unixWatchAdd(int sig) { struct sigaction sa; sigaction(sig, NULL, &sa); // if the signal is ignored, don't take it over. this is // recommended by the glibc manual if(sa.sa_handler == SIG_IGN) return; sigemptyset(&(sa.sa_mask)); sa.sa_flags = 0; sa.sa_handler = unixHandler; sigaction(sig, &sa, 0); } void unixWatchRemove(int sig) { struct sigaction sa; sigaction(sig, NULL, &sa); // ignored means we skipped it earlier, so we should // skip it again if(sa.sa_handler == SIG_IGN) return; sigemptyset(&(sa.sa_mask)); sa.sa_flags = 0; sa.sa_handler = SIG_DFL; sigaction(sig, &sa, 0); } #endif public slots: void ctrl_ready() { #ifdef Q_OS_WIN do_emit(); #endif } void sig_activated(int) { #ifdef Q_OS_UNIX unsigned char c; if(::read(sig_pipe[0], &c, 1) == -1) { // TODO: error handling? return; } do_emit(); #endif } private: void do_emit() { // only signal once if(!done) { done = true; emit q->quit(); } } }; ProcessQuit::ProcessQuit(QObject *parent) :QObject(parent) { d = new Private(this); } ProcessQuit::~ProcessQuit() { delete d; } ProcessQuit *ProcessQuit::instance() { QMutexLocker locker(pq_mutex()); if(!g_pq) { g_pq = new ProcessQuit; g_pq->moveToThread(QCoreApplication::instance()->thread()); #ifndef NO_IRISNET irisNetAddPostRoutine(cleanup); #endif } return g_pq; } void ProcessQuit::reset() { QMutexLocker locker(pq_mutex()); if(g_pq) g_pq->d->done = false; } void ProcessQuit::cleanup() { delete g_pq; g_pq = 0; } #ifndef NO_IRISNET } #endif #include "processquit.moc" zurl-1.0.0/src/common/processquit.h000066400000000000000000000103711217342011600173140ustar00rootroot00000000000000/* * Copyright (C) 2006 Justin Karneges * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA * */ #ifndef PROCESSQUIT_H #define PROCESSQUIT_H #ifdef NO_IRISNET # include # define IRISNET_EXPORT #else # include "irisnetglobal.h" #endif #ifndef NO_IRISNET namespace XMPP { #endif /** \brief Listens for termination requests ProcessQuit listens for requests to terminate the application process. On Unix platforms, these are the signals SIGINT, SIGHUP, and SIGTERM. On Windows, these are the console control events for Ctrl+C, console window close, and system shutdown. For Windows GUI programs, ProcessQuit has no effect. For GUI programs, ProcessQuit is not a substitute for QSessionManager. The only safe way to handle termination of a GUI program in the usual way is to use QSessionManager. However, ProcessQuit does give additional benefit to Unix GUI programs that might be terminated unconventionally, so it can't hurt to support both. When a termination request is received, the application should exit gracefully, and generally without user interaction. Otherwise, it is at risk of being terminated outside of its control. For example, if a Windows console application does not exit after just a few seconds of attempting to close the console window, Windows will display a prompt to the user asking if the process should be ended immediately. Using ProcessQuit is easy, and it usually amounts to a single line: \code myapp.connect(ProcessQuit::instance(), SIGNAL(quit()), SLOT(do_quit())); \endcode Calling instance() returns a pointer to the global ProcessQuit instance, which will be created if necessary. The quit() signal is emitted when a request to terminate is received. The quit() signal is only emitted once, future termination requests are ignored. Call reset() to allow the quit() signal to be emitted again. */ class IRISNET_EXPORT ProcessQuit : public QObject { Q_OBJECT public: /** \brief Returns the global ProcessQuit instance If the global instance does not exist yet, it will be created, and the termination handlers will be installed. \sa cleanup */ static ProcessQuit *instance(); /** \brief Allows the quit() signal to be emitted again ProcessQuit only emits the quit() signal once, so that if a user repeatedly presses Ctrl-C or sends SIGTERM, your shutdown slot will not be called multiple times. This is normally the desired behavior, but if you are ignoring the termination request then you may want to allow future notifications. Calling this function will allow the quit() signal to be emitted again, if a new termination request arrives. \sa quit */ static void reset(); /** \brief Frees all resources used by ProcessQuit This function will free any resources used by ProcessQuit, including the global instance, and the termination handlers will be uninstalled (reverted to default). Future termination requests will cause the application to exit abruptly. \note You normally do not need to call this function directly. When IrisNet cleans up, it will be called. \sa instance */ static void cleanup(); signals: /** \brief Notification of termination request This signal is emitted when a termination request is received. It is only emitted once, unless reset() is called. Upon receiving this signal, the application should proceed to exit gracefully, and generally without user interaction. \sa reset */ void quit(); private: class Private; friend class Private; Private *d; ProcessQuit(QObject *parent = 0); ~ProcessQuit(); }; #ifndef NO_IRISNET } #endif #endif zurl-1.0.0/src/common/tnetstring.cpp000066400000000000000000000213461217342011600174730ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "tnetstring.h" #include namespace TnetString { QByteArray fromByteArray(const QByteArray &in) { return QByteArray::number(in.size()) + ':' + in + ','; } QByteArray fromInt(int in) { QByteArray val = QByteArray::number(in); return QByteArray::number(val.size()) + ':' + val + '#'; } QByteArray fromDouble(double in) { QByteArray val = QByteArray::number(in); return QByteArray::number(val.size()) + ':' + val + '^'; } QByteArray fromBool(bool in) { QByteArray val = in ? "true" : "false"; return QByteArray::number(val.size()) + ':' + val + '!'; } QByteArray fromNull() { return QByteArray("0:~"); } QByteArray fromVariant(const QVariant &in) { switch(in.type()) { case QVariant::ByteArray: return fromByteArray(in.toByteArray()); case QVariant::Int: return fromInt(in.toInt()); case QVariant::Double: return fromDouble(in.toDouble()); case QVariant::Bool: return fromBool(in.toBool()); case QVariant::Invalid: return fromNull(); case QVariant::Hash: return fromHash(in.toHash()); case QVariant::List: return fromList(in.toList()); default: // unsupported type assert(0); return QByteArray(); } } QByteArray fromHash(const QVariantHash &in) { QByteArray val; QHashIterator it(in); while(it.hasNext()) { it.next(); val += fromByteArray(it.key().toUtf8()); val += fromVariant(it.value()); } return QByteArray::number(val.size()) + ':' + val + '}'; } QByteArray fromList(const QVariantList &in) { QByteArray val; foreach(const QVariant &v, in) val += fromVariant(v); return QByteArray::number(val.size()) + ':' + val + ']'; } bool check(const QByteArray &in, int offset, Type *type, int *dataOffset, int *dataSize) { int at = in.indexOf(':', offset); if(at == -1) return false; bool ok; int size = in.mid(offset, at - offset).toInt(&ok); if(!ok) return false; char typeChar = in[at + 1 + size]; Type type_; switch(typeChar) { case ',': type_ = ByteArray; break; case '#': type_ = Int; break; case '^': type_ = Double; break; case '!': type_ = Bool; break; case '~': type_ = Null; break; case '}': type_ = Hash; break; case ']': type_ = List; break; default: return false; } *type = type_; *dataOffset = at + 1; *dataSize = size; return true; } QByteArray toByteArray(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok) { Q_UNUSED(offset); if(ok) *ok = true; return in.mid(dataOffset, dataSize); } int toInt(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok) { Q_UNUSED(offset); QByteArray val = in.mid(dataOffset, dataSize); bool ok_; int x = val.toInt(&ok_); if(!ok_) x = 0; if(ok) *ok = ok_; return x; } double toDouble(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok) { Q_UNUSED(offset); QByteArray val = in.mid(dataOffset, dataSize); bool ok_; double x = val.toDouble(&ok_); if(!ok_) x = 0; if(ok) *ok = ok_; return x; } bool toBool(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok) { Q_UNUSED(offset); QByteArray val = in.mid(dataOffset, dataSize); if(val == "true") { if(ok) *ok = true; return true; } else if(val == "false") { if(ok) *ok = true; return false; } if(ok) *ok = false; return false; } void toNull(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok) { Q_UNUSED(in); Q_UNUSED(offset); Q_UNUSED(dataOffset); Q_UNUSED(dataSize); *ok = true; } QVariant toVariant(const QByteArray &in, int offset, Type type, int dataOffset, int dataSize, bool *ok) { QVariant val; bool ok_; switch(type) { case ByteArray: val = toByteArray(in, offset, dataOffset, dataSize, &ok_); break; case Int: val = toInt(in, offset, dataOffset, dataSize, &ok_); break; case Double: val = toDouble(in, offset, dataOffset, dataSize, &ok_); break; case Bool: val = toBool(in, offset, dataOffset, dataSize, &ok_); break; case Null: toNull(in, offset, dataOffset, dataSize, &ok_); break; case Hash: val = toHash(in, offset, dataOffset, dataSize, &ok_); break; case List: val = toList(in, offset, dataOffset, dataSize, &ok_); break; } if(!ok_) { if(ok) *ok = false; return QVariant(); } if(ok) *ok = true; return val; } QVariant toVariant(const QByteArray &in, int offset, bool *ok) { Type type; int dataOffset; int dataSize; if(!check(in, offset, &type, &dataOffset, &dataSize)) { if(ok) *ok = false; return QVariant(); } return toVariant(in, offset, type, dataOffset, dataSize, ok); } QVariantHash toHash(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok) { Q_UNUSED(offset); QVariantHash out; int at = dataOffset; while(at < dataSize + dataOffset) { Type itype; int ioffset; int isize; if(!check(in, at, &itype, &ioffset, &isize)) { if(ok) *ok = false; return QVariantHash(); } if(itype != ByteArray) { if(ok) *ok = false; return QVariantHash(); } bool ok_; QByteArray key = toByteArray(in, at, ioffset, isize, &ok_); if(!ok_) { if(ok) *ok = false; return QVariantHash(); } at = ioffset + isize + 1; // position to value if(!check(in, at, &itype, &ioffset, &isize)) { if(ok) *ok = false; return QVariantHash(); } QVariant val = toVariant(in, at, itype, ioffset, isize, &ok_); if(!ok_) { if(ok) *ok = false; return QVariantHash(); } out[QString::fromUtf8(key)] = val; at = ioffset + isize + 1; // position to next item } if(ok) *ok = true; return out; } QVariantList toList(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok) { Q_UNUSED(offset); QVariantList out; int at = dataOffset; while(at < dataOffset + dataSize) { Type itype; int ioffset; int isize; if(!check(in, at, &itype, &ioffset, &isize)) { if(ok) *ok = false; return QVariantList(); } bool ok_; QVariant val = toVariant(in, at, itype, ioffset, isize, &ok_); if(!ok_) { if(ok) *ok = false; return QVariantList(); } out += val; at = ioffset + isize + 1; // position to next item } if(ok) *ok = true; return out; } QString byteArrayToEscapedString(const QByteArray &in) { QString out; for(int n = 0; n < in.size(); ++n) { char c = in[n]; if(c == '\\') out += "\\\\"; else if(c == '\"') out += "\\\""; else if(c == '\n') out += "\\n"; else if(c >= 0x20 && c < 0x7f) out += QChar::fromLatin1(c); else out += QString().sprintf("\\x%02x", (unsigned char)c); } return out; } QString variantToString(const QVariant &in, int indent) { QString out; QVariant::Type type = in.type(); if(type == QVariant::Hash) { QVariantHash hash = in.toHash(); out += '{'; if(indent >= 0) out += '\n'; else out += ' '; QHashIterator it(hash); while(it.hasNext()) { it.next(); if(indent >= 0) out += QString(indent + 2, ' '); out += '\"' + byteArrayToEscapedString(it.key().toUtf8()) + "\": " + variantToString(it.value(), indent >= 0 ? indent + 2 : -1); if(it.hasNext()) out += ','; if(indent >= 0) out += '\n'; else out += ' '; } if(indent >= 0) out += QString(indent, ' '); out += '}'; } else if(type == QVariant::List) { QVariantList list = in.toList(); out += '['; if(indent >= 0) out += '\n'; else out += ' '; for(int n = 0; n < list.count(); ++n) { if(indent >= 0) out += QString(indent + 2, ' '); out += variantToString(list[n], indent >= 0 ? indent + 2 : -1); if(n + 1 < list.count()) out += ','; if(indent >= 0) out += '\n'; else out += ' '; } if(indent >= 0) out += QString(indent, ' '); out += ']'; } else if(type == QVariant::ByteArray) { QByteArray val = in.toByteArray(); out += '\"' + byteArrayToEscapedString(val) + '\"'; } else if(type == QVariant::Int) out += QString::number(in.toInt()); else if(type == QVariant::Double) out += QString::number(in.toDouble()); else if(type == QVariant::Bool) out += in.toBool() ? "true" : "false"; else if(type == QVariant::Invalid) out += "null"; else out += ""; return out; } } zurl-1.0.0/src/common/tnetstring.h000066400000000000000000000043331217342011600171350ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef TNETSTRING_H #define TNETSTRING_H #include namespace TnetString { enum Type { ByteArray, Int, Double, Bool, Null, Hash, List }; QByteArray fromByteArray(const QByteArray &in); QByteArray fromInt(int in); QByteArray fromDouble(double in); QByteArray fromBool(bool in); QByteArray fromNull(); QByteArray fromHash(const QVariantHash &in); QByteArray fromList(const QVariantList &in); QByteArray fromVariant(const QVariant &in); bool check(const QByteArray &in, int offset, Type *type, int *dataOffset, int *dataSize); QByteArray toByteArray(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok = 0); int toInt(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok = 0); double toDouble(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok = 0); bool toBool(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok = 0); void toNull(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok = 0); QVariantHash toHash(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok = 0); QVariantList toList(const QByteArray &in, int offset, int dataOffset, int dataSize, bool *ok = 0); QVariant toVariant(const QByteArray &in, int offset, Type type, int dataOffset, int dataSize, bool *ok = 0); QVariant toVariant(const QByteArray &in, int offset = 0, bool *ok = 0); QString byteArrayToEscapedString(const QByteArray &in); // pass >= 0 for pretty print, -1 for compact QString variantToString(const QVariant &in, int indent = 0); } #endif zurl-1.0.0/src/common/zhttprequestpacket.cpp000066400000000000000000000144641217342011600212470ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "zhttprequestpacket.h" #include "tnetstring.h" QVariant ZhttpRequestPacket::toVariant() const { QVariantHash obj; if(!from.isEmpty()) obj["from"] = from; obj["id"] = id; QByteArray typeStr; switch(type) { case Error: typeStr = "error"; break; case Credit: typeStr = "credit"; break; case KeepAlive: typeStr = "keep-alive"; break; case Cancel: typeStr = "cancel"; break; case HandoffStart: typeStr = "handoff-start"; break; case HandoffProceed: typeStr = "handoff-proceed"; break; default: break; } if(!typeStr.isEmpty()) obj["type"] = typeStr; if(type == Error && !condition.isEmpty()) obj["condition"] = condition; if(seq != -1) obj["seq"] = seq; if(credits != -1) obj["credits"] = credits; if(more) obj["more"] = true; if(stream) obj["stream"] = true; if(maxSize != -1) obj["max-size"] = maxSize; if(!method.isEmpty()) { obj["method"] = method.toLatin1(); obj["uri"] = uri.toEncoded(); QVariantList vheaders; foreach(const HttpHeader &h, headers) { QVariantList vheader; vheader += h.first; vheader += h.second; vheaders += QVariant(vheader); } obj["headers"] = vheaders; } if(!body.isEmpty()) obj["body"] = body; if(userData.isValid()) obj["user-data"] = userData; if(!peerAddress.isNull()) obj["peer-address"] = peerAddress.toString().toUtf8(); if(peerPort != -1) obj["peer-port"] = QByteArray::number(peerPort); if(!connectHost.isEmpty()) obj["connect-host"] = connectHost.toUtf8(); if(connectPort != -1) obj["connect-port"] = connectPort; if(ignorePolicies) obj["ignore-policies"] = true; if(ignoreTlsErrors) obj["ignore-tls-errors"] = true; return obj; } bool ZhttpRequestPacket::fromVariant(const QVariant &in) { if(in.type() != QVariant::Hash) return false; QVariantHash obj = in.toHash(); from.clear(); if(obj.contains("from")) { if(obj["from"].type() != QVariant::ByteArray) return false; from = obj["from"].toByteArray(); } if(!obj.contains("id") || obj["id"].type() != QVariant::ByteArray) return false; id = obj["id"].toByteArray(); type = Data; if(obj.contains("type")) { if(obj["type"].type() != QVariant::ByteArray) return false; QByteArray typeStr = obj["type"].toByteArray(); if(typeStr == "error") type = Error; else if(typeStr == "credit") type = Credit; else if(typeStr == "keep-alive") type = KeepAlive; else if(typeStr == "cancel") type = Cancel; else if(typeStr == "handoff-start") type = HandoffStart; else if(typeStr == "handoff-proceed") type = HandoffProceed; else return false; } if(type == Error) { condition.clear(); if(obj.contains("condition")) { if(obj["condition"].type() != QVariant::ByteArray) return false; condition = obj["condition"].toByteArray(); } } seq = -1; if(obj.contains("seq")) { if(obj["seq"].type() != QVariant::Int) return false; seq = obj["seq"].toInt(); } credits = -1; if(obj.contains("credits")) { if(obj["credits"].type() != QVariant::Int) return false; credits = obj["credits"].toInt(); } more = false; if(obj.contains("more")) { if(obj["more"].type() != QVariant::Bool) return false; more = obj["more"].toBool(); } stream = false; if(obj.contains("stream")) { if(obj["stream"].type() != QVariant::Bool) return false; stream = obj["stream"].toBool(); } maxSize = -1; if(obj.contains("max-size")) { if(obj["max-size"].type() != QVariant::Int) return false; maxSize = obj["max-size"].toInt(); } method.clear(); if(obj.contains("method")) { if(obj["method"].type() != QVariant::ByteArray) return false; method = QString::fromLatin1(obj["method"].toByteArray()); } uri.clear(); if(obj.contains("uri")) { if(obj["uri"].type() != QVariant::ByteArray) return false; uri = QUrl::fromEncoded(obj["uri"].toByteArray(), QUrl::StrictMode); } headers.clear(); if(obj.contains("headers")) { if(obj["headers"].type() != QVariant::List) return false; foreach(const QVariant &i, obj["headers"].toList()) { QVariantList list = i.toList(); if(list.count() != 2) return false; if(list[0].type() != QVariant::ByteArray || list[1].type() != QVariant::ByteArray) return false; headers += QPair(list[0].toByteArray(), list[1].toByteArray()); } } body.clear(); if(obj.contains("body")) { if(obj["body"].type() != QVariant::ByteArray) return false; body = obj["body"].toByteArray(); } userData = obj["user-data"]; peerAddress = QHostAddress(); if(obj.contains("peer-address")) { if(obj["peer-address"].type() != QVariant::ByteArray) return false; peerAddress = QHostAddress(QString::fromUtf8(obj["peer-address"].toByteArray())); } peerPort = -1; if(obj.contains("peer-port")) { if(obj["peer-port"].type() != QVariant::Int) return false; peerPort = obj["peer-port"].toInt(); } connectHost.clear(); if(obj.contains("connect-host")) { if(obj["connect-host"].type() != QVariant::ByteArray) return false; connectHost = QString::fromUtf8(obj["connect-host"].toByteArray()); } connectPort = -1; if(obj.contains("connect-port")) { if(obj["connect-port"].type() != QVariant::Int) return false; connectPort = obj["connect-port"].toInt(); } ignorePolicies = false; if(obj.contains("ignore-policies")) { if(obj["ignore-policies"].type() != QVariant::Bool) return false; ignorePolicies = obj["ignore-policies"].toBool(); } ignoreTlsErrors = false; if(obj.contains("ignore-tls-errors")) { if(obj["ignore-tls-errors"].type() != QVariant::Bool) return false; ignoreTlsErrors = obj["ignore-tls-errors"].toBool(); } return true; } zurl-1.0.0/src/common/zhttprequestpacket.h000066400000000000000000000031251217342011600207040ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef ZHTTPREQUESTPACKET_H #define ZHTTPREQUESTPACKET_H #include #include #include #include "httpheaders.h" class ZhttpRequestPacket { public: enum Type { Data, Error, Credit, KeepAlive, Cancel, HandoffStart, HandoffProceed }; QByteArray from; QByteArray id; Type type; QByteArray condition; int seq; int credits; bool more; bool stream; int maxSize; QString method; QUrl uri; HttpHeaders headers; QByteArray body; QVariant userData; QHostAddress peerAddress; int peerPort; QString connectHost; int connectPort; bool ignorePolicies; bool ignoreTlsErrors; ZhttpRequestPacket() : type((Type)-1), seq(-1), credits(-1), more(false), stream(false), maxSize(-1), peerPort(-1), connectPort(-1), ignorePolicies(false), ignoreTlsErrors(false) { } QVariant toVariant() const; bool fromVariant(const QVariant &in); }; #endif zurl-1.0.0/src/common/zhttpresponsepacket.cpp000066400000000000000000000104311217342011600214030ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #include "zhttpresponsepacket.h" QVariant ZhttpResponsePacket::toVariant() const { QVariantHash obj; if(!from.isEmpty()) obj["from"] = from; obj["id"] = id; QByteArray typeStr; switch(type) { case Error: typeStr = "error"; break; case Credit: typeStr = "credit"; break; case KeepAlive: typeStr = "keep-alive"; break; case Cancel: typeStr = "cancel"; break; case HandoffStart: typeStr = "handoff-start"; break; case HandoffProceed: typeStr = "handoff-proceed"; break; default: break; } if(!typeStr.isEmpty()) obj["type"] = typeStr; if(type == Error && !condition.isEmpty()) obj["condition"] = condition; if(seq != -1) obj["seq"] = seq; if(credits != -1) obj["credits"] = credits; if(more) obj["more"] = true; if(code != -1) { obj["code"] = code; obj["reason"] = reason; QVariantList vheaders; foreach(const HttpHeader &h, headers) { QVariantList vheader; vheader += h.first; vheader += h.second; vheaders += QVariant(vheader); } obj["headers"] = vheaders; } if(!body.isEmpty()) obj["body"] = body; if(userData.isValid()) obj["user-data"] = userData; return obj; } bool ZhttpResponsePacket::fromVariant(const QVariant &in) { if(in.type() != QVariant::Hash) return false; QVariantHash obj = in.toHash(); from.clear(); if(obj.contains("from")) { if(obj["from"].type() != QVariant::ByteArray) return false; from = obj["from"].toByteArray(); } if(!obj.contains("id") || obj["id"].type() != QVariant::ByteArray) return false; id = obj["id"].toByteArray(); type = Data; if(obj.contains("type")) { if(obj["type"].type() != QVariant::ByteArray) return false; QByteArray typeStr = obj["type"].toByteArray(); if(typeStr == "error") type = Error; else if(typeStr == "credit") type = Credit; else if(typeStr == "keep-alive") type = KeepAlive; else if(typeStr == "cancel") type = Cancel; else if(typeStr == "handoff-start") type = HandoffStart; else if(typeStr == "handoff-proceed") type = HandoffProceed; else return false; } if(type == Error) { condition.clear(); if(obj.contains("condition")) { if(obj["condition"].type() != QVariant::ByteArray) return false; condition = obj["condition"].toByteArray(); } } seq = -1; if(obj.contains("seq")) { if(obj["seq"].type() != QVariant::Int) return false; seq = obj["seq"].toInt(); } credits = -1; if(obj.contains("credits")) { if(obj["credits"].type() != QVariant::Int) return false; credits = obj["credits"].toInt(); } more = false; if(obj.contains("more")) { if(obj["more"].type() != QVariant::Bool) return false; more = obj["more"].toBool(); } code = -1; if(obj.contains("code")) { if(obj["code"].type() != QVariant::Int) return false; code = obj["code"].toInt(); } reason.clear(); if(obj.contains("reason")) { if(obj["reason"].type() != QVariant::ByteArray) return false; reason = obj["reason"].toByteArray(); } headers.clear(); if(obj.contains("headers")) { if(obj["headers"].type() != QVariant::List) return false; foreach(const QVariant &i, obj["headers"].toList()) { QVariantList list = i.toList(); if(list.count() != 2) return false; if(list[0].type() != QVariant::ByteArray || list[1].type() != QVariant::ByteArray) return false; headers += QPair(list[0].toByteArray(), list[1].toByteArray()); } } body.clear(); if(obj.contains("body")) { if(obj["body"].type() != QVariant::ByteArray) return false; body = obj["body"].toByteArray(); } userData = obj["user-data"]; return true; } zurl-1.0.0/src/common/zhttpresponsepacket.h000066400000000000000000000024551217342011600210570ustar00rootroot00000000000000/* * Copyright (C) 2012-2013 Fanout, 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 . */ #ifndef ZHTTPRESPONSEPACKET_H #define ZHTTPRESPONSEPACKET_H #include #include "httpheaders.h" class ZhttpResponsePacket { public: enum Type { Data, Error, Credit, KeepAlive, Cancel, HandoffStart, HandoffProceed }; QByteArray from; QByteArray id; Type type; QByteArray condition; int seq; int credits; bool more; int code; QByteArray reason; HttpHeaders headers; QByteArray body; QVariant userData; ZhttpResponsePacket() : type((Type)-1), seq(-1), credits(-1), more(false), code(-1) { } QVariant toVariant() const; bool fromVariant(const QVariant &in); }; #endif pax_global_header00006660000000000000000000000064120627372730014523gustar00rootroot0000000000000052 comment=681a1677cf583432fbe658cf0f768ac641ab9bd2 zurl-1.0.0/src/qzmq/000077500000000000000000000000001206273727300142745ustar00rootroot00000000000000zurl-1.0.0/src/qzmq/COPYING000066400000000000000000000020431206273727300153260ustar00rootroot00000000000000Copyright (C) 2012 Justin Karneges 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. zurl-1.0.0/src/qzmq/README000066400000000000000000000017331206273727300151600ustar00rootroot00000000000000QZmq ---- Author: Justin Karneges Yet another Qt binding for ZeroMQ. It wraps the C API of libzmq. Some features: - Completely event-driven, with both read and write notifications. - Multipart messages are read/written in whole. To make this possible, the Socket object maintains internal buffers, and for example it will not generate a read notification until all parts of a message have arrived. - For convenience, it is not necessary to create a Context explicitly. If a Socket is created without one, then a globally shared Context will be created automatically. - Some handy extra classes. For example, RepRouter makes it easy to write a REP socket server that handles multiple requests simultaneously. To build the examples: echo "LIBS += -lzmq" > conf.pri qmake && make To include the code in your project, just use the files in src. From a qmake project you can include src.pri. It's your responsibility to link to libzmq. zurl-1.0.0/src/qzmq/examples/000077500000000000000000000000001206273727300161125ustar00rootroot00000000000000zurl-1.0.0/src/qzmq/examples/examples.pri000066400000000000000000000002111206273727300204360ustar00rootroot00000000000000exists($$PWD/../conf.pri):include($$PWD/../conf.pri) QT -= gui QT += network INCLUDEPATH += $$PWD/../src include($$PWD/../src/src.pri) zurl-1.0.0/src/qzmq/examples/examples.pro000066400000000000000000000000671206273727300204550ustar00rootroot00000000000000TEMPLATE = subdirs SUBDIRS += helloclient helloserver zurl-1.0.0/src/qzmq/examples/helloclient/000077500000000000000000000000001206273727300204145ustar00rootroot00000000000000zurl-1.0.0/src/qzmq/examples/helloclient/helloclient.cpp000066400000000000000000000020201206273727300234140ustar00rootroot00000000000000#include #include #include #include "qzmqsocket.h" class App : public QObject { Q_OBJECT private: QZmq::Socket sock; public: App() : sock(QZmq::Socket::Req) { } public slots: void start() { connect(&sock, SIGNAL(readyRead()), SLOT(sock_readyRead())); connect(&sock, SIGNAL(messagesWritten(int)), SLOT(sock_messagesWritten(int))); sock.connectToAddress("tcp://localhost:5555"); QByteArray out = "hello"; printf("writing: %s\n", out.data()); sock.write(QList() << out); } signals: void quit(); private slots: void sock_readyRead() { QList resp = sock.read(); printf("read: %s\n", resp[0].data()); emit quit(); } void sock_messagesWritten(int count) { printf("messages written: %d\n", count); } }; int main(int argc, char **argv) { QCoreApplication qapp(argc, argv); App app; QObject::connect(&app, SIGNAL(quit()), &qapp, SLOT(quit())); QTimer::singleShot(0, &app, SLOT(start())); return qapp.exec(); } #include "helloclient.moc" zurl-1.0.0/src/qzmq/examples/helloclient/helloclient.pro000066400000000000000000000000651206273727300234410ustar00rootroot00000000000000include(../examples.pri) SOURCES += helloclient.cpp zurl-1.0.0/src/qzmq/examples/helloserver/000077500000000000000000000000001206273727300204445ustar00rootroot00000000000000zurl-1.0.0/src/qzmq/examples/helloserver/helloserver.cpp000066400000000000000000000021251206273727300235020ustar00rootroot00000000000000#include #include #include #include "qzmqreqmessage.h" #include "qzmqreprouter.h" class App : public QObject { Q_OBJECT private: QZmq::RepRouter sock; public slots: void start() { connect(&sock, SIGNAL(readyRead()), SLOT(sock_readyRead())); connect(&sock, SIGNAL(messagesWritten(int)), SLOT(sock_messagesWritten(int))); sock.bind("tcp://*:5555"); } signals: void quit(); private slots: void sock_readyRead() { QZmq::ReqMessage msg = sock.read(); if(msg.content().isEmpty()) { printf("error: received empty message\n"); return; } printf("read: %s\n", msg.content()[0].data()); QByteArray out = "world"; printf("writing: %s\n", out.data()); sock.write(msg.createReply(QList() << out)); } void sock_messagesWritten(int count) { printf("messages written: %d\n", count); } }; int main(int argc, char **argv) { QCoreApplication qapp(argc, argv); App app; QObject::connect(&app, SIGNAL(quit()), &qapp, SLOT(quit())); QTimer::singleShot(0, &app, SLOT(start())); return qapp.exec(); } #include "helloserver.moc" zurl-1.0.0/src/qzmq/examples/helloserver/helloserver.pro000066400000000000000000000000651206273727300235210ustar00rootroot00000000000000include(../examples.pri) SOURCES += helloserver.cpp zurl-1.0.0/src/qzmq/qzmq.pro000066400000000000000000000000501206273727300160010ustar00rootroot00000000000000TEMPLATE = subdirs SUBDIRS += examples zurl-1.0.0/src/qzmq/src/000077500000000000000000000000001206273727300150635ustar00rootroot00000000000000zurl-1.0.0/src/qzmq/src/qzmqcontext.cpp000066400000000000000000000024771206273727300201760ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #include "qzmqcontext.h" #include #include namespace QZmq { Context::Context(int ioThreads) { context_ = zmq_init(ioThreads); assert(context_); } Context::~Context() { zmq_term(context_); } } zurl-1.0.0/src/qzmq/src/qzmqcontext.h000066400000000000000000000025111206273727300176300ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #ifndef QZMQCONTEXT_H #define QZMQCONTEXT_H namespace QZmq { class Context { public: Context(int ioThreads = 1); ~Context(); // the zmq context void *context() { return context_; } private: void *context_; }; } #endif zurl-1.0.0/src/qzmq/src/qzmqreprouter.cpp000066400000000000000000000044631206273727300205360ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #include "qzmqreprouter.h" #include "qzmqsocket.h" #include "qzmqreqmessage.h" namespace QZmq { class RepRouter::Private : public QObject { Q_OBJECT public: RepRouter *q; Socket *sock; Private(RepRouter *_q) : QObject(_q), q(_q) { sock = new Socket(Socket::Router, this); connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead())); connect(sock, SIGNAL(messagesWritten(int)), SLOT(sock_messagesWritten(int))); } public slots: void sock_readyRead() { emit q->readyRead(); } void sock_messagesWritten(int count) { emit q->messagesWritten(count); } }; RepRouter::RepRouter(QObject *parent) : QObject(parent) { d = new Private(this); } RepRouter::~RepRouter() { delete d; } void RepRouter::setShutdownWaitTime(int msecs) { d->sock->setShutdownWaitTime(msecs); } void RepRouter::connectToAddress(const QString &addr) { d->sock->connectToAddress(addr); } bool RepRouter::bind(const QString &addr) { return d->sock->bind(addr); } bool RepRouter::canRead() const { return d->sock->canRead(); } ReqMessage RepRouter::read() { return ReqMessage(d->sock->read()); } void RepRouter::write(const ReqMessage &message) { d->sock->write(message.toRawMessage()); } } #include "qzmqreprouter.moc" zurl-1.0.0/src/qzmq/src/qzmqreprouter.h000066400000000000000000000032461206273727300202010ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #ifndef QZMQREPROUTER_H #define QZMQREPROUTER_H #include namespace QZmq { class ReqMessage; class RepRouter : public QObject { Q_OBJECT public: RepRouter(QObject *parent = 0); ~RepRouter(); void setShutdownWaitTime(int msecs); void connectToAddress(const QString &addr); bool bind(const QString &addr); bool canRead() const; ReqMessage read(); void write(const ReqMessage &message); signals: void readyRead(); void messagesWritten(int count); private: Q_DISABLE_COPY(RepRouter) class Private; friend class Private; Private *d; }; } #endif zurl-1.0.0/src/qzmq/src/qzmqreqmessage.h000066400000000000000000000042051206273727300203020ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #ifndef QZMQREQMESSAGE_H #define QZMQREQMESSAGE_H namespace QZmq { class ReqMessage { public: ReqMessage() { } ReqMessage(const QList &headers, const QList &content) : headers_(headers), content_(content) { } ReqMessage(const QList &rawMessage) { bool collectHeaders = true; foreach(const QByteArray &part, rawMessage) { if(part.isEmpty()) { collectHeaders = false; continue; } if(collectHeaders) headers_ += part; else content_ += part; } } bool isNull() const { return headers_.isEmpty() && content_.isEmpty(); } QList headers() const { return headers_; } QList content() const { return content_; } ReqMessage createReply(const QList &content) { return ReqMessage(headers_, content); } QList toRawMessage() const { QList out; out += headers_; out += QByteArray(); out += content_; return out; } private: QList headers_; QList content_; }; } #endif zurl-1.0.0/src/qzmq/src/qzmqsocket.cpp000066400000000000000000000245761206273727300200060ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #include "qzmqsocket.h" #include #include #include #include #include #include #include #include "qzmqcontext.h" namespace QZmq { static bool get_rcvmore(void *sock) { qint64 more; size_t opt_len = sizeof(more); int ret = zmq_getsockopt(sock, ZMQ_RCVMORE, &more, &opt_len); assert(ret == 0); return more ? true : false; } static int get_fd(void *sock) { int fd; size_t opt_len = sizeof(fd); int ret = zmq_getsockopt(sock, ZMQ_FD, &fd, &opt_len); assert(ret == 0); return fd; } static int get_events(void *sock) { quint32 events; size_t opt_len = sizeof(events); int ret = zmq_getsockopt(sock, ZMQ_EVENTS, &events, &opt_len); assert(ret == 0); return (int)events; } static void set_subscribe(void *sock, const char *data, int size) { size_t opt_len = size; int ret = zmq_setsockopt(sock, ZMQ_SUBSCRIBE, data, opt_len); assert(ret == 0); } static void set_unsubscribe(void *sock, const char *data, int size) { size_t opt_len = size; zmq_setsockopt(sock, ZMQ_UNSUBSCRIBE, data, opt_len); // note: we ignore errors, such as unsubscribing a nonexisting filter } static void set_linger(void *sock, int value) { size_t opt_len = sizeof(value); int ret = zmq_setsockopt(sock, ZMQ_LINGER, &value, opt_len); assert(ret == 0); } static int get_identity(void *sock, char *data, int size) { size_t opt_len = size; int ret = zmq_getsockopt(sock, ZMQ_IDENTITY, data, &opt_len); assert(ret == 0); return (int)opt_len; } static void set_identity(void *sock, const char *data, int size) { size_t opt_len = size; int ret = zmq_setsockopt(sock, ZMQ_IDENTITY, data, opt_len); if(ret != 0) printf("%d\n", errno); assert(ret == 0); } static int get_hwm(void *sock) { quint64 hwm; size_t opt_len = sizeof(hwm); int ret = zmq_getsockopt(sock, ZMQ_HWM, &hwm, &opt_len); assert(ret == 0); return (int)hwm; } static void set_hwm(void *sock, int value) { quint64 v = value; size_t opt_len = sizeof(v); int ret = zmq_setsockopt(sock, ZMQ_HWM, &v, opt_len); assert(ret == 0); } Q_GLOBAL_STATIC(QMutex, g_mutex) class Global { public: Context context; int refs; Global() : refs(0) { } }; static Global *global = 0; static Context *addGlobalContextRef() { QMutexLocker locker(g_mutex()); if(!global) global = new Global; ++(global->refs); return &(global->context); } static void removeGlobalContextRef() { QMutexLocker locker(g_mutex()); assert(global); assert(global->refs > 0); --(global->refs); if(global->refs == 0) { delete global; global = 0; } } class Socket::Private : public QObject { Q_OBJECT public: Socket *q; bool usingGlobalContext; Context *context; void *sock; QSocketNotifier *sn_read; bool canWrite, canRead; QList pendingRead; bool readComplete; QList< QList > pendingWrites; QTimer *updateTimer; bool pendingUpdate; int shutdownWaitTime; bool writeQueueEnabled; Private(Socket *_q, Socket::Type type, Context *_context) : QObject(_q), q(_q), canWrite(false), canRead(false), readComplete(false), pendingUpdate(false), shutdownWaitTime(-1), writeQueueEnabled(true) { if(_context) { usingGlobalContext = false; context = _context; } else { usingGlobalContext = true; context = addGlobalContextRef(); } int ztype; switch(type) { case Socket::Pair: ztype = ZMQ_PAIR; break; case Socket::Dealer: ztype = ZMQ_DEALER; break; case Socket::Router: ztype = ZMQ_ROUTER; break; case Socket::Req: ztype = ZMQ_REQ; break; case Socket::Rep: ztype = ZMQ_REP; break; case Socket::Push: ztype = ZMQ_PUSH; break; case Socket::Pull: ztype = ZMQ_PULL; break; case Socket::Pub: ztype = ZMQ_PUB; break; case Socket::Sub: ztype = ZMQ_SUB; break; default: assert(0); } sock = zmq_socket(context->context(), ztype); assert(sock != NULL); sn_read = new QSocketNotifier(get_fd(sock), QSocketNotifier::Read, this); connect(sn_read, SIGNAL(activated(int)), SLOT(sn_read_activated())); sn_read->setEnabled(true); updateTimer = new QTimer(this); connect(updateTimer, SIGNAL(timeout()), SLOT(update_timeout())); updateTimer->setSingleShot(true); } ~Private() { set_linger(sock, shutdownWaitTime); zmq_close(sock); if(usingGlobalContext) removeGlobalContextRef(); } QList read() { if(readComplete) { QList out = pendingRead; pendingRead.clear(); readComplete = false; if(canRead && !pendingUpdate) { pendingUpdate = true; updateTimer->start(); } return out; } else return QList(); } void write(const QList &message) { assert(!message.isEmpty()); if(writeQueueEnabled) { pendingWrites += message; if(canWrite && !pendingUpdate) { pendingUpdate = true; updateTimer->start(); } } else { for(int n = 0; n < message.count(); ++n) { const QByteArray &buf = message[n]; zmq_msg_t msg; int ret = zmq_msg_init_size(&msg, buf.size()); assert(ret == 0); memcpy(zmq_msg_data(&msg), buf.data(), buf.size()); ret = zmq_send(sock, &msg, ZMQ_NOBLOCK | (n + 1 < message.count() ? ZMQ_SNDMORE : 0)); if(ret == -1) { assert(errno == EAGAIN); ret = zmq_msg_close(&msg); assert(ret == 0); return; } ret = zmq_msg_close(&msg); assert(ret == 0); } } } void processEvents(bool *readyRead, int *messagesWritten) { bool again; do { again = false; int flags = get_events(sock); if(flags & ZMQ_POLLOUT) { canWrite = true; again = tryWrite(messagesWritten) || again; } else canWrite = false; if(flags & ZMQ_POLLIN) { canRead = true; again = tryRead(readyRead) || again; } } while(again); } bool tryWrite(int *messagesWritten) { if(!pendingWrites.isEmpty()) { QList &message = pendingWrites.first(); QByteArray buf = message.first(); // whether this write succeeds or not, we assume we // can't write afterwards canWrite = false; zmq_msg_t msg; int ret = zmq_msg_init_size(&msg, buf.size()); assert(ret == 0); memcpy(zmq_msg_data(&msg), buf.data(), buf.size()); ret = zmq_send(sock, &msg, ZMQ_NOBLOCK | (message.count() > 1 ? ZMQ_SNDMORE : 0)); if(ret == -1) { assert(errno == EAGAIN); ret = zmq_msg_close(&msg); assert(ret == 0); // if send fails, there should not be any // events change return false; } ret = zmq_msg_close(&msg); assert(ret == 0); message.removeFirst(); if(message.isEmpty()) { pendingWrites.removeFirst(); ++(*messagesWritten); } return true; } return false; } // return true if a read was performed bool tryRead(bool *readyRead) { if(!readComplete) { zmq_msg_t msg; int ret = zmq_msg_init(&msg); assert(ret == 0); ret = zmq_recv(sock, &msg, 0); assert(ret == 0); QByteArray buf((const char *)zmq_msg_data(&msg), zmq_msg_size(&msg)); ret = zmq_msg_close(&msg); assert(ret == 0); pendingRead += buf; canRead = false; if(!get_rcvmore(sock)) { readComplete = true; *readyRead = true; } return true; } return false; } public slots: void sn_read_activated() { bool readyRead = false; int messagesWritten = 0; processEvents(&readyRead, &messagesWritten); if(readyRead) emit q->readyRead(); if(messagesWritten > 0) emit q->messagesWritten(messagesWritten); } void update_timeout() { pendingUpdate = false; bool readyRead = false; int messagesWritten = 0; if(canWrite) { if(tryWrite(&messagesWritten)) processEvents(&readyRead, &messagesWritten); } if(canRead) { if(tryRead(&readyRead)) processEvents(&readyRead, &messagesWritten); } if(readyRead) emit q->readyRead(); if(messagesWritten > 0) emit q->messagesWritten(messagesWritten); } }; Socket::Socket(Type type, QObject *parent) : QObject(parent) { d = new Private(this, type, 0); } Socket::Socket(Type type, Context *context, QObject *parent) : QObject(parent) { d = new Private(this, type, context); } Socket::~Socket() { delete d; } void Socket::setShutdownWaitTime(int msecs) { d->shutdownWaitTime = msecs; } void Socket::setWriteQueueEnabled(bool enable) { d->writeQueueEnabled = enable; } void Socket::subscribe(const QByteArray &filter) { set_subscribe(d->sock, filter.data(), filter.size()); } void Socket::unsubscribe(const QByteArray &filter) { set_unsubscribe(d->sock, filter.data(), filter.size()); } QByteArray Socket::identity() const { QByteArray buf(255, 0); buf.resize(get_identity(d->sock, buf.data(), buf.size())); return buf; } void Socket::setIdentity(const QByteArray &id) { set_identity(d->sock, id.data(), id.size()); } int Socket::hwm() const { return get_hwm(d->sock); } void Socket::setHwm(int hwm) { set_hwm(d->sock, hwm); } void Socket::connectToAddress(const QString &addr) { int ret = zmq_connect(d->sock, addr.toUtf8().data()); assert(ret == 0); } bool Socket::bind(const QString &addr) { int ret = zmq_bind(d->sock, addr.toUtf8().data()); if(ret != 0) return false; return true; } bool Socket::canRead() const { return d->readComplete; } bool Socket::canWriteImmediately() const { return d->canWrite; } QList Socket::read() { return d->read(); } void Socket::write(const QList &message) { d->write(message); } } #include "qzmqsocket.moc" zurl-1.0.0/src/qzmq/src/qzmqsocket.h000066400000000000000000000055441206273727300174450ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #ifndef QZMQSOCKET_H #define QZMQSOCKET_H #include namespace QZmq { class Context; class Socket : public QObject { Q_OBJECT public: enum Type { Pair, Dealer, Router, Req, Rep, Push, Pull, Pub, Sub }; Socket(Type type, QObject *parent = 0); Socket(Type type, Context *context, QObject *parent = 0); ~Socket(); // 0 means drop queue and don't block, -1 means infinite (default = -1) void setShutdownWaitTime(int msecs); // if enabled, messages are queued internally until the socket is able // to accept them. the messagesWritten signal is emitted once writes // have succeeded. otherwise, messages are passed directly to // zmq_send and dropped if they can't be written. default enabled. // disabling the queue is good for socket types where the HWM has a // drop policy. enabling the queue is good when the HWM has a // blocking policy. void setWriteQueueEnabled(bool enable); void subscribe(const QByteArray &filter); void unsubscribe(const QByteArray &filter); QByteArray identity() const; void setIdentity(const QByteArray &id); int hwm() const; void setHwm(int hwm); void connectToAddress(const QString &addr); bool bind(const QString &addr); bool canRead() const; // returns true if this object believes the next write to zmq will // succeed immediately. note that it starts out false until the // value is discovered. also note that the write could still end up // needing to be queued, if the conditions change in between. bool canWriteImmediately() const; QList read(); void write(const QList &message); signals: void readyRead(); void messagesWritten(int count); private: Q_DISABLE_COPY(Socket) class Private; friend class Private; Private *d; }; } #endif zurl-1.0.0/src/qzmq/src/qzmqvalve.cpp000066400000000000000000000044641206273727300176250ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #include "qzmqvalve.h" #include #include "qzmqsocket.h" namespace QZmq { class Valve::Private : public QObject { Q_OBJECT public: Valve *q; QZmq::Socket *sock; bool isOpen; bool pendingRead; Private(Valve *_q) : QObject(_q), q(_q), sock(0), isOpen(false), pendingRead(false) { } void setup(QZmq::Socket *_sock) { sock = _sock; connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead())); } void tryRead() { QPointer self = this; while(isOpen && sock->canRead()) { QList msg = sock->read(); emit q->readyRead(msg); if(!self) return; } } private slots: void sock_readyRead() { tryRead(); } void queuedRead() { pendingRead = false; tryRead(); } }; Valve::Valve(QZmq::Socket *sock, QObject *parent) : QObject(parent) { d = new Private(this); d->setup(sock); } Valve::~Valve() { delete d; } bool Valve::isOpen() const { return d->isOpen; } void Valve::open() { if(!d->isOpen) { d->isOpen = true; if(!d->pendingRead && d->sock->canRead()) { d->pendingRead = true; QMetaObject::invokeMethod(d, "queuedRead", Qt::QueuedConnection); } } } void Valve::close() { d->isOpen = false; } } #include "qzmqvalve.moc" zurl-1.0.0/src/qzmq/src/qzmqvalve.h000066400000000000000000000027561206273727300172740ustar00rootroot00000000000000/* * Copyright (C) 2012 Justin Karneges * * 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. */ #ifndef QZMQVALVE_H #define QZMQVALVE_H #include namespace QZmq { class Socket; class Valve : public QObject { Q_OBJECT public: Valve(QZmq::Socket *sock, QObject *parent = 0); ~Valve(); bool isOpen() const; void open(); void close(); signals: void readyRead(const QList &message); private: class Private; friend class Private; Private *d; }; } #endif zurl-1.0.0/src/qzmq/src/src.pri000066400000000000000000000003571206273727300163730ustar00rootroot00000000000000HEADERS += \ $$PWD/qzmqcontext.h \ $$PWD/qzmqsocket.h \ $$PWD/qzmqvalve.h \ $$PWD/qzmqreqmessage.h \ $$PWD/qzmqreprouter.h SOURCES += \ $$PWD/qzmqcontext.cpp \ $$PWD/qzmqsocket.cpp \ $$PWD/qzmqvalve.cpp \ $$PWD/qzmqreprouter.cpp