pax_global_header00006660000000000000000000000064125647171720014526gustar00rootroot0000000000000052 comment=cd92f69c76cdb93e73e8d15c3634d1b5a9eeea57 libstrophe-0.8.8/000077500000000000000000000000001256471717200137165ustar00rootroot00000000000000libstrophe-0.8.8/.gitignore000066400000000000000000000010601256471717200157030ustar00rootroot00000000000000Makefile test-driver .libs src/*.lo *.la Makefile.in configure libtool ltmain.sh config.guess config.sub install-sh missing compile aclocal.m4 config.log config.status depcomp autom4te.cache .dirstamp .deps .sconsign* src/*.o examples/*.o *.a *.pc *.tar.gz *.zip docs/html TAGS tags examples/active examples/basic examples/bot examples/component examples/roster test_stamp test-suite.log tests/*.o tests/*.log tests/*.trs tests/check_parser tests/test_base64 tests/test_ctx tests/test_hash tests/test_jid tests/test_sasl tests/test_sock m4/ libstrophe.project libstrophe-0.8.8/AUTHORS000066400000000000000000000000371256471717200147660ustar00rootroot00000000000000Jack Moffit libstrophe-0.8.8/COPYING000066400000000000000000001065631256471717200147640ustar00rootroot00000000000000 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 . Copyright (c) 2005-2009 Collecta, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. libstrophe-0.8.8/ChangeLog000066400000000000000000000002351256471717200154700ustar00rootroot000000000000000.8.8 - XML namespace support - XEP-0114 support 0.8.7 - SCRAM-SHA-1 authentication mechanism - pkg-config support 0.8.5 - libtoolize to generate .so libstrophe-0.8.8/Doxyfile000066400000000000000000002263051256471717200154340ustar00rootroot00000000000000# Doxyfile 1.7.6.1 # This file describes the settings to be used by the documentation system # doxygen (www.doxygen.org) for a project. # # All text after a hash (#) is considered a comment and will be ignored. # The format is: # TAG = value [value, ...] # For lists items can also be appended using: # TAG += value [value, ...] # Values that contain spaces should be placed between quotes (" "). #--------------------------------------------------------------------------- # Project related configuration options #--------------------------------------------------------------------------- # This tag specifies the encoding used for all characters in the config file # that follow. The default is UTF-8 which is also the encoding used for all # text before the first occurrence of this tag. Doxygen uses libiconv (or the # iconv built into libc) for the transcoding. See # http://www.gnu.org/software/libiconv for the list of possible encodings. DOXYFILE_ENCODING = UTF-8 # The PROJECT_NAME tag is a single word (or sequence of words) that should # identify the project. Note that if you do not use Doxywizard you need # to put quotes around the project name if it contains spaces. PROJECT_NAME = Strophe # The PROJECT_NUMBER tag can be used to enter a project or revision number. # This could be handy for archiving the generated documentation or # if some version control system is used. PROJECT_NUMBER = 0.8 # Using the PROJECT_BRIEF tag one can provide an optional one line description # for a project that appears at the top of each page and should give viewer # a quick idea about the purpose of the project. Keep the description short. PROJECT_BRIEF = "XMPP client library" # With the PROJECT_LOGO tag one can specify an logo or icon that is # included in the documentation. The maximum height of the logo should not # exceed 55 pixels and the maximum width should not exceed 200 pixels. # Doxygen will copy the logo to the output directory. PROJECT_LOGO = # The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) # base path where the generated documentation will be put. # If a relative path is entered, it will be relative to the location # where doxygen was started. If left blank the current directory will be used. OUTPUT_DIRECTORY = ./docs/ # If the CREATE_SUBDIRS tag is set to YES, then doxygen will create # 4096 sub-directories (in 2 levels) under the output directory of each output # format and will distribute the generated files over these directories. # Enabling this option can be useful when feeding doxygen a huge amount of # source files, where putting all generated files in the same directory would # otherwise cause performance problems for the file system. CREATE_SUBDIRS = NO # The OUTPUT_LANGUAGE tag is used to specify the language in which all # documentation generated by doxygen is written. Doxygen will use this # information to generate all constant output in the proper language. # The default language is English, other supported languages are: # Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, # Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, # Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English # messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, # Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, # Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. OUTPUT_LANGUAGE = English # If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will # include brief member descriptions after the members that are listed in # the file and class documentation (similar to JavaDoc). # Set to NO to disable this. BRIEF_MEMBER_DESC = YES # If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend # the brief description of a member or function before the detailed description. # Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the # brief descriptions will be completely suppressed. REPEAT_BRIEF = YES # This tag implements a quasi-intelligent brief description abbreviator # that is used to form the text in various listings. Each string # in this list, if found as the leading text of the brief description, will be # stripped from the text and the result after processing the whole list, is # used as the annotated text. Otherwise, the brief description is used as-is. # If left blank, the following values are used ("$name" is automatically # replaced with the name of the entity): "The $name class" "The $name widget" # "The $name file" "is" "provides" "specifies" "contains" # "represents" "a" "an" "the" ABBREVIATE_BRIEF = "The $name class" \ "The $name widget" \ "The $name file" \ is \ provides \ specifies \ contains \ represents \ a \ an \ the # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then # Doxygen will generate a detailed section even if there is only a brief # description. ALWAYS_DETAILED_SEC = NO # If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all # inherited members of a class in the documentation of that class as if those # members were ordinary class members. Constructors, destructors and assignment # operators of the base classes will not be shown. INLINE_INHERITED_MEMB = NO # If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full # path before files name in the file list and in the header files. If set # to NO the shortest path that makes the file name unique will be used. FULL_PATH_NAMES = NO # If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag # can be used to strip a user-defined part of the path. Stripping is # only done if one of the specified strings matches the left-hand part of # the path. The tag can be used to show relative paths in the file list. # If left blank the directory from which doxygen is run is used as the # path to strip. STRIP_FROM_PATH = # The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of # the path mentioned in the documentation of a class, which tells # the reader which header file to include in order to use a class. # If left blank only the name of the header file containing the class # definition is used. Otherwise one should specify the include paths that # are normally passed to the compiler using the -I flag. STRIP_FROM_INC_PATH = # If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter # (but less readable) file names. This can be useful if your file system # doesn't support long names like on DOS, Mac, or CD-ROM. SHORT_NAMES = NO # If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen # will interpret the first line (until the first dot) of a JavaDoc-style # comment as the brief description. If set to NO, the JavaDoc # comments will behave just like regular Qt-style comments # (thus requiring an explicit @brief command for a brief description.) JAVADOC_AUTOBRIEF = YES # If the QT_AUTOBRIEF tag is set to YES then Doxygen will # interpret the first line (until the first dot) of a Qt-style # comment as the brief description. If set to NO, the comments # will behave just like regular Qt-style comments (thus requiring # an explicit \brief command for a brief description.) QT_AUTOBRIEF = NO # The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen # treat a multi-line C++ special comment block (i.e. a block of //! or /// # comments) as a brief description. This used to be the default behaviour. # The new default is to treat a multi-line C++ comment block as a detailed # description. Set this tag to YES if you prefer the old behaviour instead. MULTILINE_CPP_IS_BRIEF = NO # If the INHERIT_DOCS tag is set to YES (the default) then an undocumented # member inherits the documentation from any documented member that it # re-implements. INHERIT_DOCS = YES # If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce # a new page for each member. If set to NO, the documentation of a member will # be part of the file/class/namespace that contains it. SEPARATE_MEMBER_PAGES = NO # The TAB_SIZE tag can be used to set the number of spaces in a tab. # Doxygen uses this value to replace tabs by spaces in code fragments. TAB_SIZE = 8 # This tag can be used to specify a number of aliases that acts # as commands in the documentation. An alias has the form "name=value". # For example adding "sideeffect=\par Side Effects:\n" will allow you to # put the command \sideeffect (or @sideeffect) in the documentation, which # will result in a user-defined paragraph with heading "Side Effects:". # You can put \n's in the value part of an alias to insert newlines. ALIASES = # This tag can be used to specify a number of word-keyword mappings (TCL only). # A mapping has the form "name=value". For example adding # "class=itcl::class" will allow you to use the command class in the # itcl::class meaning. TCL_SUBST = # Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C # sources only. Doxygen will then generate output that is more tailored for C. # For instance, some of the names that are used will be different. The list # of all members will be omitted, etc. OPTIMIZE_OUTPUT_FOR_C = YES # Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java # sources only. Doxygen will then generate output that is more tailored for # Java. For instance, namespaces will be presented as packages, qualified # scopes will look different, etc. OPTIMIZE_OUTPUT_JAVA = NO # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran # sources only. Doxygen will then generate output that is more tailored for # Fortran. OPTIMIZE_FOR_FORTRAN = NO # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL # sources. Doxygen will then generate output that is tailored for # VHDL. OPTIMIZE_OUTPUT_VHDL = NO # Doxygen selects the parser to use depending on the extension of the files it # parses. With this tag you can assign which parser to use for a given extension. # Doxygen has a built-in mapping, but you can override or extend it using this # tag. The format is ext=language, where ext is a file extension, and language # is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C, # C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make # doxygen treat .inc files as Fortran files (default is PHP), and .f files as C # (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions # you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. EXTENSION_MAPPING = # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want # to include (a tag file for) the STL sources as input, then you should # set this tag to YES in order to let doxygen match functions declarations and # definitions whose arguments contain STL classes (e.g. func(std::string); v.s. # func(std::string) {}). This also makes the inheritance and collaboration # diagrams that involve STL classes more complete and accurate. BUILTIN_STL_SUPPORT = NO # If you use Microsoft's C++/CLI language, you should set this option to YES to # enable parsing support. CPP_CLI_SUPPORT = NO # Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. # Doxygen will parse them like normal C++ but will assume all classes use public # instead of private inheritance when no explicit protection keyword is present. SIP_SUPPORT = NO # For Microsoft's IDL there are propget and propput attributes to indicate getter # and setter methods for a property. Setting this option to YES (the default) # will make doxygen replace the get and set methods by a property in the # documentation. This will only work if the methods are indeed getting or # setting a simple type. If this is not the case, or you want to show the # methods anyway, you should set this option to NO. IDL_PROPERTY_SUPPORT = YES # If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC # tag is set to YES, then doxygen will reuse the documentation of the first # member in the group (if any) for the other members of the group. By default # all members of a group must be documented explicitly. DISTRIBUTE_GROUP_DOC = NO # Set the SUBGROUPING tag to YES (the default) to allow class member groups of # the same type (for instance a group of public functions) to be put as a # subgroup of that type (e.g. under the Public Functions section). Set it to # NO to prevent subgrouping. Alternatively, this can be done per class using # the \nosubgrouping command. SUBGROUPING = YES # When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and # unions are shown inside the group in which they are included (e.g. using # @ingroup) instead of on a separate page (for HTML and Man pages) or # section (for LaTeX and RTF). INLINE_GROUPED_CLASSES = NO # When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and # unions with only public data fields will be shown inline in the documentation # of the scope in which they are defined (i.e. file, namespace, or group # documentation), provided this scope is documented. If set to NO (the default), # structs, classes, and unions are shown on a separate page (for HTML and Man # pages) or section (for LaTeX and RTF). INLINE_SIMPLE_STRUCTS = NO # When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum # is documented as struct, union, or enum with the name of the typedef. So # typedef struct TypeS {} TypeT, will appear in the documentation as a struct # with name TypeT. When disabled the typedef will appear as a member of a file, # namespace, or class. And the struct will be named TypeS. This can typically # be useful for C code in case the coding convention dictates that all compound # types are typedef'ed and only the typedef is referenced, never the tag name. TYPEDEF_HIDES_STRUCT = YES # The SYMBOL_CACHE_SIZE determines the size of the internal cache use to # determine which symbols to keep in memory and which to flush to disk. # When the cache is full, less often used symbols will be written to disk. # For small to medium size projects (<1000 input files) the default value is # probably good enough. For larger projects a too small cache size can cause # doxygen to be busy swapping symbols to and from disk most of the time # causing a significant performance penalty. # If the system has enough physical memory increasing the cache will improve the # performance by keeping more symbols in memory. Note that the value works on # a logarithmic scale so increasing the size by one will roughly double the # memory usage. The cache size is given by this formula: # 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. SYMBOL_CACHE_SIZE = 0 # Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be # set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given # their name and scope. Since this can be an expensive process and often the # same symbol appear multiple times in the code, doxygen keeps a cache of # pre-resolved symbols. If the cache is too small doxygen will become slower. # If the cache is too large, memory is wasted. The cache size is given by this # formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, # corresponding to a cache size of 2^16 = 65536 symbols. LOOKUP_CACHE_SIZE = 0 #--------------------------------------------------------------------------- # Build related configuration options #--------------------------------------------------------------------------- # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in # documentation are documented, even if no documentation was available. # Private class members and static file members will be hidden unless # the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES EXTRACT_ALL = YES # If the EXTRACT_PRIVATE tag is set to YES all private members of a class # will be included in the documentation. EXTRACT_PRIVATE = YES # If the EXTRACT_STATIC tag is set to YES all static members of a file # will be included in the documentation. EXTRACT_STATIC = YES # If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) # defined locally in source files will be included in the documentation. # If set to NO only classes defined in header files are included. EXTRACT_LOCAL_CLASSES = YES # This flag is only useful for Objective-C code. When set to YES local # methods, which are defined in the implementation section but not in # the interface are included in the documentation. # If set to NO (the default) only methods in the interface are included. EXTRACT_LOCAL_METHODS = YES # If this flag is set to YES, the members of anonymous namespaces will be # extracted and appear in the documentation as a namespace called # 'anonymous_namespace{file}', where file will be replaced with the base # name of the file that contains the anonymous namespace. By default # anonymous namespaces are hidden. EXTRACT_ANON_NSPACES = YES # If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all # undocumented members of documented classes, files or namespaces. # If set to NO (the default) these members will be included in the # various overviews, but no documentation section is generated. # This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_MEMBERS = NO # If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all # undocumented classes that are normally visible in the class hierarchy. # If set to NO (the default) these classes will be included in the various # overviews. This option has no effect if EXTRACT_ALL is enabled. HIDE_UNDOC_CLASSES = NO # If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all # friend (class|struct|union) declarations. # If set to NO (the default) these declarations will be included in the # documentation. HIDE_FRIEND_COMPOUNDS = NO # If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any # documentation blocks found inside the body of a function. # If set to NO (the default) these blocks will be appended to the # function's detailed documentation block. HIDE_IN_BODY_DOCS = NO # The INTERNAL_DOCS tag determines if documentation # that is typed after a \internal command is included. If the tag is set # to NO (the default) then the documentation will be excluded. # Set it to YES to include the internal documentation. INTERNAL_DOCS = NO # If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate # file names in lower-case letters. If set to YES upper-case letters are also # allowed. This is useful if you have classes or files whose names only differ # in case and if your file system supports case sensitive file names. Windows # and Mac users are advised to set this option to NO. CASE_SENSE_NAMES = NO # If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen # will show members with their full class and namespace scopes in the # documentation. If set to YES the scope will be hidden. HIDE_SCOPE_NAMES = NO # If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen # will put a list of the files that are included by a file in the documentation # of that file. SHOW_INCLUDE_FILES = NO # If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen # will list include files with double quotes in the documentation # rather than with sharp brackets. FORCE_LOCAL_INCLUDES = NO # If the INLINE_INFO tag is set to YES (the default) then a tag [inline] # is inserted in the documentation for inline members. INLINE_INFO = YES # If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen # will sort the (detailed) documentation of file and class members # alphabetically by member name. If set to NO the members will appear in # declaration order. SORT_MEMBER_DOCS = NO # If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the # brief documentation of file, namespace and class members alphabetically # by member name. If set to NO (the default) the members will appear in # declaration order. SORT_BRIEF_DOCS = NO # If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen # will sort the (brief and detailed) documentation of class members so that # constructors and destructors are listed first. If set to NO (the default) # the constructors will appear in the respective orders defined by # SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. # This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO # and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. SORT_MEMBERS_CTORS_1ST = NO # If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the # hierarchy of group names into alphabetical order. If set to NO (the default) # the group names will appear in their defined order. SORT_GROUP_NAMES = NO # If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be # sorted by fully-qualified names, including namespaces. If set to # NO (the default), the class list will be sorted only by class name, # not including the namespace part. # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. # Note: This option applies only to the class list, not to the # alphabetical list. SORT_BY_SCOPE_NAME = NO # If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to # do proper type resolution of all parameters of a function it will reject a # match between the prototype and the implementation of a member function even # if there is only one candidate or it is obvious which candidate to choose # by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen # will still accept a match between prototype and implementation in such cases. STRICT_PROTO_MATCHING = NO # The GENERATE_TODOLIST tag can be used to enable (YES) or # disable (NO) the todo list. This list is created by putting \todo # commands in the documentation. GENERATE_TODOLIST = YES # The GENERATE_TESTLIST tag can be used to enable (YES) or # disable (NO) the test list. This list is created by putting \test # commands in the documentation. GENERATE_TESTLIST = YES # The GENERATE_BUGLIST tag can be used to enable (YES) or # disable (NO) the bug list. This list is created by putting \bug # commands in the documentation. GENERATE_BUGLIST = YES # The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or # disable (NO) the deprecated list. This list is created by putting # \deprecated commands in the documentation. GENERATE_DEPRECATEDLIST= YES # The ENABLED_SECTIONS tag can be used to enable conditional # documentation sections, marked by \if sectionname ... \endif. ENABLED_SECTIONS = # The MAX_INITIALIZER_LINES tag determines the maximum number of lines # the initial value of a variable or macro consists of for it to appear in # the documentation. If the initializer consists of more lines than specified # here it will be hidden. Use a value of 0 to hide initializers completely. # The appearance of the initializer of individual variables and macros in the # documentation can be controlled using \showinitializer or \hideinitializer # command in the documentation regardless of this setting. MAX_INITIALIZER_LINES = 30 # Set the SHOW_USED_FILES tag to NO to disable the list of files generated # at the bottom of the documentation of classes and structs. If set to YES the # list will mention the files that were used to generate the documentation. SHOW_USED_FILES = YES # If the sources in your project are distributed over multiple directories # then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy # in the documentation. The default is NO. SHOW_DIRECTORIES = NO # Set the SHOW_FILES tag to NO to disable the generation of the Files page. # This will remove the Files entry from the Quick Index and from the # Folder Tree View (if specified). The default is YES. SHOW_FILES = YES # Set the SHOW_NAMESPACES tag to NO to disable the generation of the # Namespaces page. # This will remove the Namespaces entry from the Quick Index # and from the Folder Tree View (if specified). The default is YES. SHOW_NAMESPACES = YES # The FILE_VERSION_FILTER tag can be used to specify a program or script that # doxygen should invoke to get the current version for each file (typically from # the version control system). Doxygen will invoke the program by executing (via # popen()) the command , where is the value of # the FILE_VERSION_FILTER tag, and is the name of an input file # provided by doxygen. Whatever the program writes to standard output # is used as the file version. See the manual for examples. FILE_VERSION_FILTER = # The LAYOUT_FILE tag can be used to specify a layout file which will be parsed # by doxygen. The layout file controls the global structure of the generated # output files in an output format independent way. The create the layout file # that represents doxygen's defaults, run doxygen with the -l option. # You can optionally specify a file name after the option, if omitted # DoxygenLayout.xml will be used as the name of the layout file. LAYOUT_FILE = # The CITE_BIB_FILES tag can be used to specify one or more bib files # containing the references data. This must be a list of .bib files. The # .bib extension is automatically appended if omitted. Using this command # requires the bibtex tool to be installed. See also # http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style # of the bibliography can be controlled using LATEX_BIB_STYLE. To use this # feature you need bibtex and perl available in the search path. CITE_BIB_FILES = #--------------------------------------------------------------------------- # configuration options related to warning and progress messages #--------------------------------------------------------------------------- # The QUIET tag can be used to turn on/off the messages that are generated # by doxygen. Possible values are YES and NO. If left blank NO is used. QUIET = NO # The WARNINGS tag can be used to turn on/off the warning messages that are # generated by doxygen. Possible values are YES and NO. If left blank # NO is used. WARNINGS = YES # If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings # for undocumented members. If EXTRACT_ALL is set to YES then this flag will # automatically be disabled. WARN_IF_UNDOCUMENTED = YES # If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for # potential errors in the documentation, such as not documenting some # parameters in a documented function, or documenting parameters that # don't exist or using markup commands wrongly. WARN_IF_DOC_ERROR = YES # The WARN_NO_PARAMDOC option can be enabled to get warnings for # functions that are documented, but have no documentation for their parameters # or return value. If set to NO (the default) doxygen will only warn about # wrong or incomplete parameter documentation, but not about the absence of # documentation. WARN_NO_PARAMDOC = YES # The WARN_FORMAT tag determines the format of the warning messages that # doxygen can produce. The string should contain the $file, $line, and $text # tags, which will be replaced by the file and line number from which the # warning originated and the warning text. Optionally the format may contain # $version, which will be replaced by the version of the file (if it could # be obtained via FILE_VERSION_FILTER) WARN_FORMAT = "$file:$line: $text" # The WARN_LOGFILE tag can be used to specify a file to which warning # and error messages should be written. If left blank the output is written # to stderr. WARN_LOGFILE = #--------------------------------------------------------------------------- # configuration options related to the input files #--------------------------------------------------------------------------- # The INPUT tag can be used to specify the files and/or directories that contain # documented source files. You may enter file names like "myfile.cpp" or # directories like "/usr/src/myproject". Separate the files or directories # with spaces. INPUT = ./ # This tag can be used to specify the character encoding of the source files # that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is # also the default input encoding. Doxygen uses libiconv (or the iconv built # into libc) for the transcoding. See http://www.gnu.org/software/libiconv for # the list of possible encodings. INPUT_ENCODING = UTF-8 # If the value of the INPUT tag contains directories, you can use the # FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank the following patterns are tested: # *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh # *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py # *.f90 *.f *.for *.vhd *.vhdl FILE_PATTERNS = *.c \ *.h # The RECURSIVE tag can be used to turn specify whether or not subdirectories # should be searched for input files as well. Possible values are YES and NO. # If left blank NO is used. RECURSIVE = YES # The EXCLUDE tag can be used to specify files and/or directories that should be # excluded from the INPUT source files. This way you can easily exclude a # subdirectory from a directory tree whose root is specified with the INPUT tag. # Note that relative paths are relative to the directory from which doxygen is # run. EXCLUDE = examples \ tests # The EXCLUDE_SYMLINKS tag can be used to select whether or not files or # directories that are symbolic links (a Unix file system feature) are excluded # from the input. EXCLUDE_SYMLINKS = NO # If the value of the INPUT tag contains directories, you can use the # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude # certain files from those directories. Note that the wildcards are matched # against the file with absolute path, so to exclude all test directories # for example use the pattern */test/* EXCLUDE_PATTERNS = .svn # The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names # (namespaces, classes, functions, etc.) that should be excluded from the # output. The symbol name can be a fully qualified name, a word, or if the # wildcard * is used, a substring. Examples: ANamespace, AClass, # AClass::ANamespace, ANamespace::*Test EXCLUDE_SYMBOLS = # The EXAMPLE_PATH tag can be used to specify one or more files or # directories that contain example code fragments that are included (see # the \include command). EXAMPLE_PATH = # If the value of the EXAMPLE_PATH tag contains directories, you can use the # EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp # and *.h) to filter out the source-files in the directories. If left # blank all files are included. EXAMPLE_PATTERNS = * # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be # searched for input files to be used with the \include or \dontinclude # commands irrespective of the value of the RECURSIVE tag. # Possible values are YES and NO. If left blank NO is used. EXAMPLE_RECURSIVE = NO # The IMAGE_PATH tag can be used to specify one or more files or # directories that contain image that are included in the documentation (see # the \image command). IMAGE_PATH = # The INPUT_FILTER tag can be used to specify a program that doxygen should # invoke to filter for each input file. Doxygen will invoke the filter program # by executing (via popen()) the command , where # is the value of the INPUT_FILTER tag, and is the name of an # input file. Doxygen will then use the output that the filter program writes # to standard output. # If FILTER_PATTERNS is specified, this tag will be # ignored. INPUT_FILTER = # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern # basis. # Doxygen will compare the file name with each pattern and apply the # filter if there is a match. # The filters are a list of the form: # pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further # info on how filters are used. If FILTER_PATTERNS is empty or if # non of the patterns match the file name, INPUT_FILTER is applied. FILTER_PATTERNS = # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using # INPUT_FILTER) will be used to filter the input files when producing source # files to browse (i.e. when SOURCE_BROWSER is set to YES). FILTER_SOURCE_FILES = NO # The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file # pattern. A pattern will override the setting for FILTER_PATTERN (if any) # and it is also possible to disable source filtering for a specific pattern # using *.ext= (so without naming a filter). This option only has effect when # FILTER_SOURCE_FILES is enabled. FILTER_SOURCE_PATTERNS = #--------------------------------------------------------------------------- # configuration options related to source browsing #--------------------------------------------------------------------------- # If the SOURCE_BROWSER tag is set to YES then a list of source files will # be generated. Documented entities will be cross-referenced with these sources. # Note: To get rid of all source code in the generated output, make sure also # VERBATIM_HEADERS is set to NO. SOURCE_BROWSER = NO # Setting the INLINE_SOURCES tag to YES will include the body # of functions and classes directly in the documentation. INLINE_SOURCES = NO # Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct # doxygen to hide any special comment blocks from generated source code # fragments. Normal C and C++ comments will always remain visible. STRIP_CODE_COMMENTS = YES # If the REFERENCED_BY_RELATION tag is set to YES # then for each documented function all documented # functions referencing it will be listed. REFERENCED_BY_RELATION = NO # If the REFERENCES_RELATION tag is set to YES # then for each documented function all documented entities # called/used by that function will be listed. REFERENCES_RELATION = NO # If the REFERENCES_LINK_SOURCE tag is set to YES (the default) # and SOURCE_BROWSER tag is set to YES, then the hyperlinks from # functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will # link to the source code. # Otherwise they will link to the documentation. REFERENCES_LINK_SOURCE = YES # If the USE_HTAGS tag is set to YES then the references to source code # will point to the HTML generated by the htags(1) tool instead of doxygen # built-in source browser. The htags tool is part of GNU's global source # tagging system (see http://www.gnu.org/software/global/global.html). You # will need version 4.8.6 or higher. USE_HTAGS = NO # If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen # will generate a verbatim copy of the header file for each class for # which an include is specified. Set to NO to disable this. VERBATIM_HEADERS = NO #--------------------------------------------------------------------------- # configuration options related to the alphabetical class index #--------------------------------------------------------------------------- # If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index # of all compounds will be generated. Enable this if the project # contains a lot of classes, structs, unions or interfaces. ALPHABETICAL_INDEX = NO # If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then # the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns # in which this list will be split (can be a number in the range [1..20]) COLS_IN_ALPHA_INDEX = 5 # In case all classes in a project start with a common prefix, all # classes will be put under the same header in the alphabetical index. # The IGNORE_PREFIX tag can be used to specify one or more prefixes that # should be ignored while generating the index headers. IGNORE_PREFIX = #--------------------------------------------------------------------------- # configuration options related to the HTML output #--------------------------------------------------------------------------- # If the GENERATE_HTML tag is set to YES (the default) Doxygen will # generate HTML output. GENERATE_HTML = YES # The HTML_OUTPUT tag is used to specify where the HTML docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `html' will be used as the default path. HTML_OUTPUT = html # The HTML_FILE_EXTENSION tag can be used to specify the file extension for # each generated HTML page (for example: .htm,.php,.asp). If it is left blank # doxygen will generate files with .html extension. HTML_FILE_EXTENSION = .html # The HTML_HEADER tag can be used to specify a personal HTML header for # each generated HTML page. If it is left blank doxygen will generate a # standard header. Note that when using a custom header you are responsible # for the proper inclusion of any scripts and style sheets that doxygen # needs, which is dependent on the configuration options used. # It is advised to generate a default header using "doxygen -w html # header.html footer.html stylesheet.css YourConfigFile" and then modify # that header. Note that the header is subject to change so you typically # have to redo this when upgrading to a newer version of doxygen or when # changing the value of configuration settings such as GENERATE_TREEVIEW! HTML_HEADER = # The HTML_FOOTER tag can be used to specify a personal HTML footer for # each generated HTML page. If it is left blank doxygen will generate a # standard footer. HTML_FOOTER = docs/footer.html # The HTML_STYLESHEET tag can be used to specify a user-defined cascading # style sheet that is used by each HTML page. It can be used to # fine-tune the look of the HTML output. If the tag is left blank doxygen # will generate a default style sheet. Note that doxygen will try to copy # the style sheet file to the HTML output directory, so don't put your own # style sheet in the HTML output directory as well, or it will be erased! HTML_STYLESHEET = # The HTML_EXTRA_FILES tag can be used to specify one or more extra images or # other source files which should be copied to the HTML output directory. Note # that these files will be copied to the base HTML output directory. Use the # $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these # files. In the HTML_STYLESHEET file, use the file name only. Also note that # the files will be copied as-is; there are no commands or markers available. HTML_EXTRA_FILES = # The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. # Doxygen will adjust the colors in the style sheet and background images # according to this color. Hue is specified as an angle on a colorwheel, # see http://en.wikipedia.org/wiki/Hue for more information. # For instance the value 0 represents red, 60 is yellow, 120 is green, # 180 is cyan, 240 is blue, 300 purple, and 360 is red again. # The allowed range is 0 to 359. HTML_COLORSTYLE_HUE = 220 # The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of # the colors in the HTML output. For a value of 0 the output will use # grayscales only. A value of 255 will produce the most vivid colors. HTML_COLORSTYLE_SAT = 100 # The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to # the luminance component of the colors in the HTML output. Values below # 100 gradually make the output lighter, whereas values above 100 make # the output darker. The value divided by 100 is the actual gamma applied, # so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, # and 100 does not change the gamma. HTML_COLORSTYLE_GAMMA = 80 # If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML # page will contain the date and time when the page was generated. Setting # this to NO can help when comparing the output of multiple runs. HTML_TIMESTAMP = YES # If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, # files or namespaces will be aligned in HTML using tables. If set to # NO a bullet list will be used. HTML_ALIGN_MEMBERS = YES # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML # documentation will contain sections that can be hidden and shown after the # page has loaded. For this to work a browser that supports # JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox # Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). HTML_DYNAMIC_SECTIONS = NO # If the GENERATE_DOCSET tag is set to YES, additional index files # will be generated that can be used as input for Apple's Xcode 3 # integrated development environment, introduced with OSX 10.5 (Leopard). # To create a documentation set, doxygen will generate a Makefile in the # HTML output directory. Running make will produce the docset in that # directory and running "make install" will install the docset in # ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find # it at startup. # See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html # for more information. GENERATE_DOCSET = NO # When GENERATE_DOCSET tag is set to YES, this tag determines the name of the # feed. A documentation feed provides an umbrella under which multiple # documentation sets from a single provider (such as a company or product suite) # can be grouped. DOCSET_FEEDNAME = "Doxygen generated docs" # When GENERATE_DOCSET tag is set to YES, this tag specifies a string that # should uniquely identify the documentation set bundle. This should be a # reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen # will append .docset to the name. DOCSET_BUNDLE_ID = org.doxygen.Project # When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify # the documentation publisher. This should be a reverse domain-name style # string, e.g. com.mycompany.MyDocSet.documentation. DOCSET_PUBLISHER_ID = org.doxygen.Publisher # The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. DOCSET_PUBLISHER_NAME = Publisher # If the GENERATE_HTMLHELP tag is set to YES, additional index files # will be generated that can be used as input for tools like the # Microsoft HTML help workshop to generate a compiled HTML help file (.chm) # of the generated HTML documentation. GENERATE_HTMLHELP = YES # If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can # be used to specify the file name of the resulting .chm file. You # can add a path in front of the file if the result should not be # written to the html output directory. CHM_FILE = # If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can # be used to specify the location (absolute path including file name) of # the HTML help compiler (hhc.exe). If non-empty doxygen will try to run # the HTML help compiler on the generated index.hhp. HHC_LOCATION = # If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag # controls if a separate .chi index file is generated (YES) or that # it should be included in the master .chm file (NO). GENERATE_CHI = NO # If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING # is used to encode HtmlHelp index (hhk), content (hhc) and project file # content. CHM_INDEX_ENCODING = # If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag # controls whether a binary table of contents is generated (YES) or a # normal table of contents (NO) in the .chm file. BINARY_TOC = NO # The TOC_EXPAND flag can be set to YES to add extra items for group members # to the contents of the HTML help documentation and to the tree view. TOC_EXPAND = NO # If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and # QHP_VIRTUAL_FOLDER are set, an additional index file will be generated # that can be used as input for Qt's qhelpgenerator to generate a # Qt Compressed Help (.qch) of the generated HTML documentation. GENERATE_QHP = NO # If the QHG_LOCATION tag is specified, the QCH_FILE tag can # be used to specify the file name of the resulting .qch file. # The path specified is relative to the HTML output folder. QCH_FILE = # The QHP_NAMESPACE tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#namespace QHP_NAMESPACE = org.doxygen.Project # The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating # Qt Help Project output. For more information please see # http://doc.trolltech.com/qthelpproject.html#virtual-folders QHP_VIRTUAL_FOLDER = doc # If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to # add. For more information please see # http://doc.trolltech.com/qthelpproject.html#custom-filters QHP_CUST_FILTER_NAME = # The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the # custom filter to add. For more information please see # # Qt Help Project / Custom Filters. QHP_CUST_FILTER_ATTRS = # The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this # project's # filter section matches. # # Qt Help Project / Filter Attributes. QHP_SECT_FILTER_ATTRS = # If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can # be used to specify the location of Qt's qhelpgenerator. # If non-empty doxygen will try to run qhelpgenerator on the generated # .qhp file. QHG_LOCATION = # If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files # will be generated, which together with the HTML files, form an Eclipse help # plugin. To install this plugin and make it available under the help contents # menu in Eclipse, the contents of the directory containing the HTML and XML # files needs to be copied into the plugins directory of eclipse. The name of # the directory within the plugins directory should be the same as # the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before # the help appears. GENERATE_ECLIPSEHELP = NO # A unique identifier for the eclipse help plugin. When installing the plugin # the directory name containing the HTML and XML files should also have # this name. ECLIPSE_DOC_ID = org.doxygen.Project # The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) # at top of each HTML page. The value NO (the default) enables the index and # the value YES disables it. Since the tabs have the same information as the # navigation tree you can set this option to NO if you already set # GENERATE_TREEVIEW to YES. DISABLE_INDEX = YES # The GENERATE_TREEVIEW tag is used to specify whether a tree-like index # structure should be generated to display hierarchical information. # If the tag value is set to YES, a side panel will be generated # containing a tree-like index structure (just like the one that # is generated for HTML Help). For this to work a browser that supports # JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). # Windows users are probably better off using the HTML help feature. # Since the tree basically has the same information as the tab index you # could consider to set DISABLE_INDEX to NO when enabling this option. GENERATE_TREEVIEW = NONE # The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values # (range [0,1..20]) that doxygen will group on one line in the generated HTML # documentation. Note that a value of 0 will completely suppress the enum # values from appearing in the overview section. ENUM_VALUES_PER_LINE = 4 # By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, # and Class Hierarchy pages using a tree view instead of an ordered list. USE_INLINE_TREES = NO # If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be # used to set the initial width (in pixels) of the frame in which the tree # is shown. TREEVIEW_WIDTH = 250 # When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open # links to external symbols imported via tag files in a separate window. EXT_LINKS_IN_WINDOW = NO # Use this tag to change the font size of Latex formulas included # as images in the HTML documentation. The default is 10. Note that # when you change the font size after a successful doxygen run you need # to manually remove any form_*.png images from the HTML output directory # to force them to be regenerated. FORMULA_FONTSIZE = 10 # Use the FORMULA_TRANPARENT tag to determine whether or not the images # generated for formulas are transparent PNGs. Transparent PNGs are # not supported properly for IE 6.0, but are supported on all modern browsers. # Note that when changing this option you need to delete any form_*.png files # in the HTML output before the changes have effect. FORMULA_TRANSPARENT = YES # Enable the USE_MATHJAX option to render LaTeX formulas using MathJax # (see http://www.mathjax.org) which uses client side Javascript for the # rendering instead of using prerendered bitmaps. Use this if you do not # have LaTeX installed or if you want to formulas look prettier in the HTML # output. When enabled you also need to install MathJax separately and # configure the path to it using the MATHJAX_RELPATH option. USE_MATHJAX = NO # When MathJax is enabled you need to specify the location relative to the # HTML output directory using the MATHJAX_RELPATH option. The destination # directory should contain the MathJax.js script. For instance, if the mathjax # directory is located at the same level as the HTML output directory, then # MATHJAX_RELPATH should be ../mathjax. The default value points to the # mathjax.org site, so you can quickly see the result without installing # MathJax, but it is strongly recommended to install a local copy of MathJax # before deployment. MATHJAX_RELPATH = http://www.mathjax.org/mathjax # The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension # names that should be enabled during MathJax rendering. MATHJAX_EXTENSIONS = # When the SEARCHENGINE tag is enabled doxygen will generate a search box # for the HTML output. The underlying search engine uses javascript # and DHTML and should work on any modern browser. Note that when using # HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets # (GENERATE_DOCSET) there is already a search function so this one should # typically be disabled. For large projects the javascript based search engine # can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. SEARCHENGINE = NO # When the SERVER_BASED_SEARCH tag is enabled the search engine will be # implemented using a PHP enabled web server instead of at the web client # using Javascript. Doxygen will generate the search PHP script and index # file to put on the web server. The advantage of the server # based approach is that it scales better to large projects and allows # full text search. The disadvantages are that it is more difficult to setup # and does not have live searching capabilities. SERVER_BASED_SEARCH = NO #--------------------------------------------------------------------------- # configuration options related to the LaTeX output #--------------------------------------------------------------------------- # If the GENERATE_LATEX tag is set to YES (the default) Doxygen will # generate Latex output. GENERATE_LATEX = NO # The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `latex' will be used as the default path. LATEX_OUTPUT = latex # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be # invoked. If left blank `latex' will be used as the default command name. # Note that when enabling USE_PDFLATEX this option is only used for # generating bitmaps for formulas in the HTML output, but not in the # Makefile that is written to the output directory. LATEX_CMD_NAME = latex # The MAKEINDEX_CMD_NAME tag can be used to specify the command name to # generate index for LaTeX. If left blank `makeindex' will be used as the # default command name. MAKEINDEX_CMD_NAME = makeindex # If the COMPACT_LATEX tag is set to YES Doxygen generates more compact # LaTeX documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_LATEX = NO # The PAPER_TYPE tag can be used to set the paper type that is used # by the printer. Possible values are: a4, letter, legal and # executive. If left blank a4wide will be used. PAPER_TYPE = a4wide # The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX # packages that should be included in the LaTeX output. EXTRA_PACKAGES = # The LATEX_HEADER tag can be used to specify a personal LaTeX header for # the generated latex document. The header should contain everything until # the first chapter. If it is left blank doxygen will generate a # standard header. Notice: only use this tag if you know what you are doing! LATEX_HEADER = # The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for # the generated latex document. The footer should contain everything after # the last chapter. If it is left blank doxygen will generate a # standard footer. Notice: only use this tag if you know what you are doing! LATEX_FOOTER = # If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated # is prepared for conversion to pdf (using ps2pdf). The pdf file will # contain links (just like the HTML output) instead of page references # This makes the output suitable for online browsing using a pdf viewer. PDF_HYPERLINKS = YES # If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of # plain latex in the generated Makefile. Set this option to YES to get a # higher quality PDF documentation. USE_PDFLATEX = YES # If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. # command to the generated LaTeX files. This will instruct LaTeX to keep # running if errors occur, instead of asking the user for help. # This option is also used when generating formulas in HTML. LATEX_BATCHMODE = NO # If LATEX_HIDE_INDICES is set to YES then doxygen will not # include the index chapters (such as File Index, Compound Index, etc.) # in the output. LATEX_HIDE_INDICES = NO # If LATEX_SOURCE_CODE is set to YES then doxygen will include # source code with syntax highlighting in the LaTeX output. # Note that which sources are shown also depends on other settings # such as SOURCE_BROWSER. LATEX_SOURCE_CODE = NO # The LATEX_BIB_STYLE tag can be used to specify the style to use for the # bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See # http://en.wikipedia.org/wiki/BibTeX for more info. LATEX_BIB_STYLE = plain #--------------------------------------------------------------------------- # configuration options related to the RTF output #--------------------------------------------------------------------------- # If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output # The RTF output is optimized for Word 97 and may not look very pretty with # other RTF readers or editors. GENERATE_RTF = NO # The RTF_OUTPUT tag is used to specify where the RTF docs will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `rtf' will be used as the default path. RTF_OUTPUT = rtf # If the COMPACT_RTF tag is set to YES Doxygen generates more compact # RTF documents. This may be useful for small projects and may help to # save some trees in general. COMPACT_RTF = NO # If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated # will contain hyperlink fields. The RTF file will # contain links (just like the HTML output) instead of page references. # This makes the output suitable for online browsing using WORD or other # programs which support those fields. # Note: wordpad (write) and others do not support links. RTF_HYPERLINKS = NO # Load style sheet definitions from file. Syntax is similar to doxygen's # config file, i.e. a series of assignments. You only have to provide # replacements, missing definitions are set to their default value. RTF_STYLESHEET_FILE = # Set optional variables used in the generation of an rtf document. # Syntax is similar to doxygen's config file. RTF_EXTENSIONS_FILE = #--------------------------------------------------------------------------- # configuration options related to the man page output #--------------------------------------------------------------------------- # If the GENERATE_MAN tag is set to YES (the default) Doxygen will # generate man pages GENERATE_MAN = NO # The MAN_OUTPUT tag is used to specify where the man pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `man' will be used as the default path. MAN_OUTPUT = man # The MAN_EXTENSION tag determines the extension that is added to # the generated man pages (default is the subroutine's section .3) MAN_EXTENSION = .3 # If the MAN_LINKS tag is set to YES and Doxygen generates man output, # then it will generate one additional man file for each entity # documented in the real man page(s). These additional files # only source the real man page, but without them the man command # would be unable to find the correct page. The default is NO. MAN_LINKS = NO #--------------------------------------------------------------------------- # configuration options related to the XML output #--------------------------------------------------------------------------- # If the GENERATE_XML tag is set to YES Doxygen will # generate an XML file that captures the structure of # the code including all documentation. GENERATE_XML = NO # The XML_OUTPUT tag is used to specify where the XML pages will be put. # If a relative path is entered the value of OUTPUT_DIRECTORY will be # put in front of it. If left blank `xml' will be used as the default path. XML_OUTPUT = xml # The XML_SCHEMA tag can be used to specify an XML schema, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_SCHEMA = # The XML_DTD tag can be used to specify an XML DTD, # which can be used by a validating XML parser to check the # syntax of the XML files. XML_DTD = # If the XML_PROGRAMLISTING tag is set to YES Doxygen will # dump the program listings (including syntax highlighting # and cross-referencing information) to the XML output. Note that # enabling this will significantly increase the size of the XML output. XML_PROGRAMLISTING = YES #--------------------------------------------------------------------------- # configuration options for the AutoGen Definitions output #--------------------------------------------------------------------------- # If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will # generate an AutoGen Definitions (see autogen.sf.net) file # that captures the structure of the code including all # documentation. Note that this feature is still experimental # and incomplete at the moment. GENERATE_AUTOGEN_DEF = NO #--------------------------------------------------------------------------- # configuration options related to the Perl module output #--------------------------------------------------------------------------- # If the GENERATE_PERLMOD tag is set to YES Doxygen will # generate a Perl module file that captures the structure of # the code including all documentation. Note that this # feature is still experimental and incomplete at the # moment. GENERATE_PERLMOD = NO # If the PERLMOD_LATEX tag is set to YES Doxygen will generate # the necessary Makefile rules, Perl scripts and LaTeX code to be able # to generate PDF and DVI output from the Perl module output. PERLMOD_LATEX = NO # If the PERLMOD_PRETTY tag is set to YES the Perl module output will be # nicely formatted so it can be parsed by a human reader. # This is useful # if you want to understand what is going on. # On the other hand, if this # tag is set to NO the size of the Perl module output will be much smaller # and Perl will parse it just the same. PERLMOD_PRETTY = YES # The names of the make variables in the generated doxyrules.make file # are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. # This is useful so different doxyrules.make files included by the same # Makefile don't overwrite each other's variables. PERLMOD_MAKEVAR_PREFIX = #--------------------------------------------------------------------------- # Configuration options related to the preprocessor #--------------------------------------------------------------------------- # If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will # evaluate all C-preprocessor directives found in the sources and include # files. ENABLE_PREPROCESSING = YES # If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro # names in the source code. If set to NO (the default) only conditional # compilation will be performed. Macro expansion can be done in a controlled # way by setting EXPAND_ONLY_PREDEF to YES. MACRO_EXPANSION = YES # If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES # then the macro expansion is limited to the macros specified with the # PREDEFINED and EXPAND_AS_DEFINED tags. EXPAND_ONLY_PREDEF = YES # If the SEARCH_INCLUDES tag is set to YES (the default) the includes files # pointed to by INCLUDE_PATH will be searched when a #include is found. SEARCH_INCLUDES = YES # The INCLUDE_PATH tag can be used to specify one or more directories that # contain include files that are not input files but should be processed by # the preprocessor. INCLUDE_PATH = # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard # patterns (like *.h and *.hpp) to filter out the header-files in the # directories. If left blank, the patterns specified with FILE_PATTERNS will # be used. INCLUDE_FILE_PATTERNS = # The PREDEFINED tag can be used to specify one or more macro names that # are defined before the preprocessor is started (similar to the -D option of # gcc). The argument of the tag is a list of macros of the form: name # or name=definition (no spaces). If the definition and the = are # omitted =1 is assumed. To prevent a macro definition from being # undefined via #undef or recursively expanded use the := operator # instead of the = operator. PREDEFINED = "VA_START(f)=" \ "VA_SHIFT(v,t)=" \ "MIN(p,q)=" \ "MAX(p,q)=" \ "char_to_int(p)=" \ "GET_32BIT_LSB_FIRST(cp)=" \ "PUT_32BIT_LSB_FIRST(cp, value)=" \ "F1(x,y,z)=" \ "F2(x,y,z)=" \ "F3(x,y,z)=" \ "F4(x,y,z)=" \ "MD5STEP(f,w,x,y,z,data,s)=" \ "rol(value,bits)=" \ "blk0(i)=" \ "blk(i)=" \ "R0(v,w,x,y,z,i)=" \ "R1(v,w,x,y,z,i)=" \ "R2(v,w,x,y,z,i)=" \ "R3(v,w,x,y,z,i)=" \ "R4(v,w,x,y,z,i)=" # If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then # this tag can be used to specify a list of macro names that should be expanded. # The macro definition that is found in the sources will be used. # Use the PREDEFINED tag if you want to use a different macro definition that # overrules the definition found in the source code. EXPAND_AS_DEFINED = # If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then # doxygen's preprocessor will remove all references to function-like macros # that are alone on a line, have an all uppercase name, and do not end with a # semicolon, because these will confuse the parser if not removed. SKIP_FUNCTION_MACROS = YES #--------------------------------------------------------------------------- # Configuration::additions related to external references #--------------------------------------------------------------------------- # The TAGFILES option can be used to specify one or more tagfiles. # Optionally an initial location of the external documentation # can be added for each tagfile. The format of a tag file without # this location is as follows: # # TAGFILES = file1 file2 ... # Adding location for the tag files is done as follows: # # TAGFILES = file1=loc1 "file2 = loc2" ... # where "loc1" and "loc2" can be relative or absolute paths or # URLs. If a location is present for each tag, the installdox tool # does not have to be run to correct the links. # Note that each tag file must have a unique name # (where the name does NOT include the path) # If a tag file is not located in the directory in which doxygen # is run, you must also specify the path to the tagfile here. TAGFILES = # When a file name is specified after GENERATE_TAGFILE, doxygen will create # a tag file that is based on the input files it reads. GENERATE_TAGFILE = # If the ALLEXTERNALS tag is set to YES all external classes will be listed # in the class index. If set to NO only the inherited external classes # will be listed. ALLEXTERNALS = NO # If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed # in the modules index. If set to NO, only the current project's groups will # be listed. EXTERNAL_GROUPS = YES # The PERL_PATH should be the absolute path and name of the perl script # interpreter (i.e. the result of `which perl'). PERL_PATH = /usr/bin/perl #--------------------------------------------------------------------------- # Configuration options related to the dot tool #--------------------------------------------------------------------------- # If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will # generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base # or super classes. Setting the tag to NO turns the diagrams off. Note that # this option also works with HAVE_DOT disabled, but it is recommended to # install and use dot, since it yields more powerful graphs. CLASS_DIAGRAMS = NO # You can define message sequence charts within doxygen comments using the \msc # command. Doxygen will then run the mscgen tool (see # http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the # documentation. The MSCGEN_PATH tag allows you to specify the directory where # the mscgen tool resides. If left empty the tool is assumed to be found in the # default search path. MSCGEN_PATH = /Applications/Doxygen.app/Contents/Resources/ # If set to YES, the inheritance and collaboration graphs will hide # inheritance and usage relations if the target is undocumented # or is not a class. HIDE_UNDOC_RELATIONS = YES # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is # available from the path. This tool is part of Graphviz, a graph visualization # toolkit from AT&T and Lucent Bell Labs. The other options in this section # have no effect if this option is set to NO (the default) HAVE_DOT = NO # The DOT_NUM_THREADS specifies the number of dot invocations doxygen is # allowed to run in parallel. When set to 0 (the default) doxygen will # base this on the number of processors available in the system. You can set it # explicitly to a value larger than 0 to get control over the balance # between CPU load and processing speed. DOT_NUM_THREADS = 0 # By default doxygen will use the Helvetica font for all dot files that # doxygen generates. When you want a differently looking font you can specify # the font name using DOT_FONTNAME. You need to make sure dot is able to find # the font, which can be done by putting it in a standard location or by setting # the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the # directory containing the font. DOT_FONTNAME = FreeSans # The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. # The default size is 10pt. DOT_FONTSIZE = 10 # By default doxygen will tell dot to use the Helvetica font. # If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to # set the path where dot can find it. DOT_FONTPATH = # If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect inheritance relations. Setting this tag to YES will force the # CLASS_DIAGRAMS tag to NO. CLASS_GRAPH = YES # If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen # will generate a graph for each documented class showing the direct and # indirect implementation dependencies (inheritance, containment, and # class references variables) of the class with other documented classes. COLLABORATION_GRAPH = YES # If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen # will generate a graph for groups, showing the direct groups dependencies GROUP_GRAPHS = YES # If the UML_LOOK tag is set to YES doxygen will generate inheritance and # collaboration diagrams in a style similar to the OMG's Unified Modeling # Language. UML_LOOK = NO # If set to YES, the inheritance and collaboration graphs will show the # relations between templates and their instances. TEMPLATE_RELATIONS = NO # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT # tags are set to YES then doxygen will generate a graph for each documented # file showing the direct and indirect include dependencies of the file with # other documented files. INCLUDE_GRAPH = YES # If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and # HAVE_DOT tags are set to YES then doxygen will generate a graph for each # documented header file showing the documented files that directly or # indirectly include this file. INCLUDED_BY_GRAPH = YES # If the CALL_GRAPH and HAVE_DOT options are set to YES then # doxygen will generate a call dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable call graphs # for selected functions only using the \callgraph command. CALL_GRAPH = NO # If the CALLER_GRAPH and HAVE_DOT tags are set to YES then # doxygen will generate a caller dependency graph for every global function # or class method. Note that enabling this option will significantly increase # the time of a run. So in most cases it will be better to enable caller # graphs for selected functions only using the \callergraph command. CALLER_GRAPH = NO # If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen # will generate a graphical hierarchy of all classes instead of a textual one. GRAPHICAL_HIERARCHY = YES # If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES # then doxygen will show the dependencies a directory has on other directories # in a graphical way. The dependency relations are determined by the #include # relations between the files in the directories. DIRECTORY_GRAPH = YES # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images # generated by dot. Possible values are svg, png, jpg, or gif. # If left blank png will be used. If you choose svg you need to set # HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible in IE 9+ (other browsers do not have this requirement). DOT_IMAGE_FORMAT = png # If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to # enable generation of interactive SVG images that allow zooming and panning. # Note that this requires a modern browser other than Internet Explorer. # Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you # need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files # visible. Older versions of IE do not have SVG support. INTERACTIVE_SVG = NO # The tag DOT_PATH can be used to specify the path where the dot tool can be # found. If left blank, it is assumed the dot tool can be found in the path. DOT_PATH = /Applications/Doxygen.app/Contents/Resources/ # The DOTFILE_DIRS tag can be used to specify one or more directories that # contain dot files that are included in the documentation (see the # \dotfile command). DOTFILE_DIRS = # The MSCFILE_DIRS tag can be used to specify one or more directories that # contain msc files that are included in the documentation (see the # \mscfile command). MSCFILE_DIRS = # The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of # nodes that will be shown in the graph. If the number of nodes in a graph # becomes larger than this value, doxygen will truncate the graph, which is # visualized by representing a node as a red box. Note that doxygen if the # number of direct children of the root node in a graph is already larger than # DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note # that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. DOT_GRAPH_MAX_NODES = 50 # The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the # graphs generated by dot. A depth value of 3 means that only nodes reachable # from the root by following a path via at most 3 edges will be shown. Nodes # that lay further from the root node will be omitted. Note that setting this # option to 1 or 2 may greatly reduce the computation time needed for large # code bases. Also note that the size of a graph can be further restricted by # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. MAX_DOT_GRAPH_DEPTH = 1000 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent # background. This is disabled by default, because dot on Windows does not # seem to support this out of the box. Warning: Depending on the platform used, # enabling this option may lead to badly anti-aliased labels on the edges of # a graph (i.e. they become hard to read). DOT_TRANSPARENT = YES # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output # files in one run (i.e. multiple -o and -T options on the command line). This # makes dot run faster, but since only newer versions of dot (>1.8.10) # support this, this feature is disabled by default. DOT_MULTI_TARGETS = NO # If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will # generate a legend page explaining the meaning of the various boxes and # arrows in the dot generated graphs. GENERATE_LEGEND = YES # If the DOT_CLEANUP tag is set to YES (the default) Doxygen will # remove the intermediate dot files that are used to generate # the various graphs. DOT_CLEANUP = YES libstrophe-0.8.8/GPL-LICENSE.txt000066400000000000000000001045131256471717200161650ustar00rootroot00000000000000 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 . libstrophe-0.8.8/LICENSE.txt000066400000000000000000000003111256471717200155340ustar00rootroot00000000000000libstrophe XMPP client library Copyright (C) 2005-2009 Collecta, Inc. This program is dual licensed under the MIT and GPLv3 licenses. Please the files MIT-LICENSE.txt and GPL-LICENSE.txt for details. libstrophe-0.8.8/MIT-LICENSE.txt000066400000000000000000000020471256471717200161730ustar00rootroot00000000000000Copyright (c) 2005-2009 Collecta, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. libstrophe-0.8.8/Makefile.am000066400000000000000000000042301256471717200157510ustar00rootroot00000000000000AUTOMAKE_OPTIONS = subdir-objects ACLOCAL_AMFLAGS = -I m4 AM_CFLAGS = -g -Wall PARSER_CFLAGS=@PARSER_CFLAGS@ PARSER_LIBS=@PARSER_LIBS@ SSL_CFLAGS = @openssl_CFLAGS@ SSL_LIBS = @openssl_LIBS@ STROPHE_FLAGS = -I$(top_srcdir) STROPHE_LIBS = libstrophe.la ## Main build targets lib_LTLIBRARIES = libstrophe.la libstrophe_la_CFLAGS = $(SSL_CFLAGS) $(STROPHE_FLAGS) $(PARSER_CFLAGS) libstrophe_la_LDFLAGS = $(SSL_LIBS) $(PARSER_LIBS) # Export only public API libstrophe_la_LDFLAGS += -export-symbols-regex '^xmpp_' libstrophe_la_SOURCES = src/auth.c src/conn.c src/ctx.c \ src/event.c src/handler.c src/hash.c \ src/jid.c src/md5.c src/sasl.c src/scram.c src/sha1.c \ src/snprintf.c src/sock.c src/stanza.c src/thread.c \ src/tls_openssl.c src/util.c \ src/common.h src/hash.h src/md5.h src/ostypes.h src/parser.h \ src/sasl.h src/scram.h src/sha1.h src/sock.h src/thread.h src/tls.h \ src/util.h if PARSER_EXPAT libstrophe_la_SOURCES += src/parser_expat.c else libstrophe_la_SOURCES += src/parser_libxml2.c endif include_HEADERS = strophe.h noinst_HEADERS = strophepp.h pkgconfig_DATA = libstrophe.pc EXTRA_DIST = docs ## Examples noinst_PROGRAMS = examples/active examples/roster examples/basic examples/bot examples/component examples_active_SOURCES = examples/active.c examples_active_CFLAGS = $(STROPHE_FLAGS) examples_active_LDADD = $(STROPHE_LIBS) examples_roster_SOURCES = examples/roster.c examples_roster_CFLAGS = $(STROPHE_FLAGS) examples_roster_LDADD = $(STROPHE_LIBS) examples_basic_SOURCES = examples/basic.c examples_basic_CFLAGS = $(STROPHE_FLAGS) examples_basic_LDADD = $(STROPHE_LIBS) examples_bot_SOURCES = examples/bot.c examples_bot_CFLAGS = $(STROPHE_FLAGS) examples_bot_LDADD = $(STROPHE_LIBS) examples_component_SOURCES = examples/component.c examples_component_CFLAGS = $(STROPHE_FLAGS) examples_component_LDADD = $(STROPHE_LIBS) ## Tests TESTS = tests/check_parser check_PROGRAMS = tests/check_parser tests_check_parser_SOURCES = tests/check_parser.c tests/test.h tests_check_parser_CFLAGS = @check_CFLAGS@ $(PARSER_CFLAGS) $(STROPHE_FLAGS) \ -I$(top_srcdir)/src tests_check_parser_LDADD = @check_LIBS@ $(STROPHE_LIBS) tests_check_parser_LDFLAGS = -static libstrophe-0.8.8/NEWS000066400000000000000000000000001256471717200144030ustar00rootroot00000000000000libstrophe-0.8.8/README000077700000000000000000000000001256471717200172722README.markdownustar00rootroot00000000000000libstrophe-0.8.8/README.markdown000066400000000000000000000032101256471717200164130ustar00rootroot00000000000000# libstrophe libstrophe is a lightweight XMPP client library written in C. It has minimal dependencies and is configurable for various environments. It runs well on both Linux, Unix, and Windows based platforms. Its goals are: - usable quickly - well documented - reliable ## Build Instructions If you are building from a source control checkout, run: ./bootstrap.sh to generate the `configure` script. From the top-level directory, run the following commands: ./configure make This will create a static library, also in the top-level directory, which can be linked into other programs. The public API is defined in `strophe.h` which is also in the top-level directory. The `examples` directory contains some examples of how to use the library; these may be helpful in addition to the API documentation To install on your system, as root (or using sudo): make install Note, the default install path is `/usr/local/`, to specify another path use the `--prefix` option during configure, e.g.: ./configure --prefix=/usr ## Requirements libstrophe requires: - expat or libxml2 - expat is the default; use --with-libxml2 to switch - libresolv on UNIX systems - make sure you include -lresolv if you are compiling by hand. - libtool In addition, if you wish to run the unit tests, you will need the check package. ### OS X (with Homebrew package manager) You can install libstrophe with: brew install libstrophe ## Documentation API documentation is inline with the code and conforms to Doxygen standards. You can generate an HTML version of the API documentation by running: doxygen Then open `docs/html/index.html`. libstrophe-0.8.8/TODO000066400000000000000000000000001256471717200143740ustar00rootroot00000000000000libstrophe-0.8.8/bootstrap.sh000077500000000000000000000001321256471717200162660ustar00rootroot00000000000000#!/bin/sh # Some versions of aclocal fail if m4/ doesn't exist mkdir -p m4 autoreconf -i libstrophe-0.8.8/configure.ac000066400000000000000000000072571256471717200162170ustar00rootroot00000000000000AC_INIT([libstrophe], [0.8.8], [jack@metajack.im]) AC_CONFIG_MACRO_DIR([m4]) AM_INIT_AUTOMAKE([foreign]) LT_INIT([dlopen]) AC_PROG_CC AM_PROG_CC_C_O PKG_PROG_PKG_CONFIG AC_CANONICAL_HOST AS_CASE([$host_os], [freebsd*], [PLATFORM="freebsd"], [PLATFORM="nix"]) PKG_CHECK_MODULES([openssl], [openssl], [PC_REQUIRES+=(openssl)], [AC_CHECK_HEADER([openssl/ssl.h], [ openssl_LIBS="-lssl -lcrypto" PC_LIBS+=($openssl_LIBS) ], [AC_MSG_ERROR([openssl not found; openssl required])] )]) PKG_CHECK_MODULES([check], [check >= 0.9.4], [], [AC_MSG_WARN([libcheck not found; unit tests will not be compilable])]) AC_ARG_WITH([libxml2], [AS_HELP_STRING([--with-libxml2], [use libxml2 for XML parsing])], [with_libxml2=check], [with_libxml2=no]) if test "x$with_libxml2" != xno; then PKG_CHECK_MODULES([libxml2], [libxml-2.0 >= 2.7], [ with_libxml2=yes PC_REQUIRES+=(libxml-2.0) ], [ old_CFLAGS=$CFLAGS CFLAGS="-I${includedir}/libxml2" AC_CHECK_HEADER([libxml/parser.h], [ with_libxml2=yes libxml2_CFLAGS="-I${includedir}/libxml2" libxml2_LIBS="-lxml2" PC_LIBS+=($libxml2_LIBS) PC_CFLAGS+=($libxml2_CFLAGS) ], [AC_MSG_ERROR([libxml2 not found.])]) CFLAGS=$old_CFLAGS ]) else PKG_CHECK_MODULES([expat], [expat >= 2.0.0], [PC_REQUIRES+=(expat)], [AC_CHECK_HEADER([expat.h], [ expat_LIBS="-lexpat" PC_LIBS+=($expat_LIBS) ], [AC_MSG_ERROR([expat not found; expat required.])] ) ]) fi if test "x$with_libxml2" = xyes; then with_parser=libxml2 PARSER_NAME=libxml2 PARSER_CFLAGS=$libxml2_CFLAGS PARSER_LIBS=$libxml2_LIBS else with_parser=expat PARSER_NAME=expat PARSER_CFLAGS=$expat_CFLAGS PARSER_LIBS=$expat_LIBS fi AC_MSG_NOTICE([libstrophe will use the $with_parser XML parser]) AC_SEARCH_LIBS([socket], [socket]) if test "x$PLATFORM" != xfreebsd; then AC_CHECK_LIB([resolv], [res_query], [], [AC_CHECK_LIB([resolv], [__res_query], [], [AC_MSG_ERROR([libresolv not found; libresolv required.])])]) PC_LIBS+=(-lresolv) else AC_MSG_NOTICE([skipping libresolv checks for freebsd]) fi AC_CHECK_HEADERS([arpa/nameser_compat.h]) m4_ifdef([PKG_INSTALLDIR], [PKG_INSTALLDIR], [AC_ARG_WITH([pkgconfigdir], [AS_HELP_STRING([--with-pkgconfigdir], [install directory for libstrophe.pc pkg-config file])], [],[with_pkgconfigdir='$(libdir)/pkgconfig']) AC_SUBST([pkgconfigdir], [${with_pkgconfigdir}])]) AM_CONDITIONAL([PARSER_EXPAT], [test x$with_parser != xlibxml2]) AC_SUBST([PC_REQUIRES], [${PC_REQUIRES[[@]]}]) AC_SUBST([PC_CFLAGS], [${PC_CFLAGS[[@]]}]) AC_SUBST([PC_LIBS], [${PC_LIBS[[@]]}]) AC_SUBST(PARSER_NAME) AC_SUBST(PARSER_CFLAGS) AC_SUBST(PARSER_LIBS) AC_CONFIG_FILES([Makefile libstrophe.pc]) AC_OUTPUT libstrophe-0.8.8/docs/000077500000000000000000000000001256471717200146465ustar00rootroot00000000000000libstrophe-0.8.8/docs/footer.html000066400000000000000000000000201256471717200170220ustar00rootroot00000000000000 libstrophe-0.8.8/examples/000077500000000000000000000000001256471717200155345ustar00rootroot00000000000000libstrophe-0.8.8/examples/active.c000066400000000000000000000057661256471717200171710ustar00rootroot00000000000000/* active.c ** libstrophe XMPP client library -- basic usage example ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /* This example demonstrates basic handler functions by printing out ** active resources on a jabberd 2.x server. This program requires ** an admin account on a jabberd 2.x account in order to run. */ #include #include #include int handle_reply(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { xmpp_stanza_t *query, *item; char *type; type = xmpp_stanza_get_type(stanza); if (strcmp(type, "error") == 0) fprintf(stderr, "ERROR: query failed\n"); else { query = xmpp_stanza_get_child_by_name(stanza, "query"); printf("Active Sessions:\n"); for (item = xmpp_stanza_get_children(query); item; item = xmpp_stanza_get_next(item)) printf("\t %s\n", xmpp_stanza_get_attribute(item, "jid")); printf("END OF LIST\n"); } /* disconnect */ xmpp_disconnect(conn); return 0; } void conn_handler(xmpp_conn_t * const conn, const xmpp_conn_event_t status, const int error, xmpp_stream_error_t * const stream_error, void * const userdata) { xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata; xmpp_stanza_t *iq, *query; if (status == XMPP_CONN_CONNECT) { fprintf(stderr, "DEBUG: connected\n"); /* create iq stanza for request */ iq = xmpp_stanza_new(ctx); xmpp_stanza_set_name(iq, "iq"); xmpp_stanza_set_type(iq, "get"); xmpp_stanza_set_id(iq, "active1"); xmpp_stanza_set_attribute(iq, "to", "xxxxxxxxx.com"); query = xmpp_stanza_new(ctx); xmpp_stanza_set_name(query, "query"); xmpp_stanza_set_ns(query, XMPP_NS_DISCO_ITEMS); xmpp_stanza_set_attribute(query, "node", "sessions"); xmpp_stanza_add_child(iq, query); /* we can release the stanza since it belongs to iq now */ xmpp_stanza_release(query); /* set up reply handler */ xmpp_id_handler_add(conn, handle_reply, "active1", ctx); /* send out the stanza */ xmpp_send(conn, iq); /* release the stanza */ xmpp_stanza_release(iq); } else { fprintf(stderr, "DEBUG: disconnected\n"); xmpp_stop(ctx); } } int main(int argc, char **argv) { xmpp_ctx_t *ctx; xmpp_conn_t *conn; if (argc != 3) { fprintf(stderr, "Usage: active \n\n"); return 1; } /* initialize lib */ xmpp_initialize(); /* create a context */ ctx = xmpp_ctx_new(NULL, NULL); /* create a connection */ conn = xmpp_conn_new(ctx); /* setup authentication information */ xmpp_conn_set_jid(conn, argv[1]); xmpp_conn_set_pass(conn, argv[2]); /* initiate connection */ xmpp_connect_client(conn, NULL, 0, conn_handler, ctx); /* start the event loop */ xmpp_run(ctx); /* release our connection and context */ xmpp_conn_release(conn); xmpp_ctx_free(ctx); /* shutdown lib */ xmpp_shutdown(); return 0; } libstrophe-0.8.8/examples/basic.c000066400000000000000000000036741256471717200167730ustar00rootroot00000000000000/* basic.c ** libstrophe XMPP client library -- basic usage example ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include #include /* define a handler for connection events */ void conn_handler(xmpp_conn_t * const conn, const xmpp_conn_event_t status, const int error, xmpp_stream_error_t * const stream_error, void * const userdata) { xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata; if (status == XMPP_CONN_CONNECT) { fprintf(stderr, "DEBUG: connected\n"); xmpp_disconnect(conn); } else { fprintf(stderr, "DEBUG: disconnected\n"); xmpp_stop(ctx); } } int main(int argc, char **argv) { xmpp_ctx_t *ctx; xmpp_conn_t *conn; xmpp_log_t *log; char *jid, *pass, *host; /* take a jid and password on the command line */ if (argc < 3 || argc > 4) { fprintf(stderr, "Usage: basic []\n\n"); return 1; } jid = argv[1]; pass = argv[2]; host = NULL; if (argc == 4) host = argv[3]; /* init library */ xmpp_initialize(); /* create a context */ log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG); /* pass NULL instead to silence output */ ctx = xmpp_ctx_new(NULL, log); /* create a connection */ conn = xmpp_conn_new(ctx); /* setup authentication information */ xmpp_conn_set_jid(conn, jid); xmpp_conn_set_pass(conn, pass); /* initiate connection */ xmpp_connect_client(conn, host, 0, conn_handler, ctx); /* enter the event loop - our connect handler will trigger an exit */ xmpp_run(ctx); /* release our connection and context */ xmpp_conn_release(conn); xmpp_ctx_free(ctx); /* final shutdown of the library */ xmpp_shutdown(); return 0; } libstrophe-0.8.8/examples/bot.c000066400000000000000000000115101256471717200164620ustar00rootroot00000000000000/* bot.c ** libstrophe XMPP client library -- basic usage example ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /* simple bot example ** ** This example was provided by Matthew Wild . ** ** This bot responds to basic messages and iq version requests. */ #include #include #include #include int version_handler(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { xmpp_stanza_t *reply, *query, *name, *version, *text; char *ns; xmpp_ctx_t *ctx = (xmpp_ctx_t*)userdata; printf("Received version request from %s\n", xmpp_stanza_get_attribute(stanza, "from")); reply = xmpp_stanza_new(ctx); xmpp_stanza_set_name(reply, "iq"); xmpp_stanza_set_type(reply, "result"); xmpp_stanza_set_id(reply, xmpp_stanza_get_id(stanza)); xmpp_stanza_set_attribute(reply, "to", xmpp_stanza_get_attribute(stanza, "from")); query = xmpp_stanza_new(ctx); xmpp_stanza_set_name(query, "query"); ns = xmpp_stanza_get_ns(xmpp_stanza_get_children(stanza)); if (ns) { xmpp_stanza_set_ns(query, ns); } name = xmpp_stanza_new(ctx); xmpp_stanza_set_name(name, "name"); xmpp_stanza_add_child(query, name); text = xmpp_stanza_new(ctx); xmpp_stanza_set_text(text, "libstrophe example bot"); xmpp_stanza_add_child(name, text); version = xmpp_stanza_new(ctx); xmpp_stanza_set_name(version, "version"); xmpp_stanza_add_child(query, version); text = xmpp_stanza_new(ctx); xmpp_stanza_set_text(text, "1.0"); xmpp_stanza_add_child(version, text); xmpp_stanza_add_child(reply, query); xmpp_send(conn, reply); xmpp_stanza_release(reply); return 1; } int message_handler(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { xmpp_stanza_t *reply, *body, *text; char *intext, *replytext; xmpp_ctx_t *ctx = (xmpp_ctx_t*)userdata; if(!xmpp_stanza_get_child_by_name(stanza, "body")) return 1; if(xmpp_stanza_get_attribute(stanza, "type") !=NULL && !strcmp(xmpp_stanza_get_attribute(stanza, "type"), "error")) return 1; intext = xmpp_stanza_get_text(xmpp_stanza_get_child_by_name(stanza, "body")); printf("Incoming message from %s: %s\n", xmpp_stanza_get_attribute(stanza, "from"), intext); reply = xmpp_stanza_new(ctx); xmpp_stanza_set_name(reply, "message"); xmpp_stanza_set_type(reply, xmpp_stanza_get_type(stanza)?xmpp_stanza_get_type(stanza):"chat"); xmpp_stanza_set_attribute(reply, "to", xmpp_stanza_get_attribute(stanza, "from")); body = xmpp_stanza_new(ctx); xmpp_stanza_set_name(body, "body"); replytext = malloc(strlen(" to you too!") + strlen(intext) + 1); strcpy(replytext, intext); strcat(replytext, " to you too!"); text = xmpp_stanza_new(ctx); xmpp_stanza_set_text(text, replytext); xmpp_stanza_add_child(body, text); xmpp_stanza_add_child(reply, body); xmpp_send(conn, reply); xmpp_stanza_release(reply); free(replytext); return 1; } /* define a handler for connection events */ void conn_handler(xmpp_conn_t * const conn, const xmpp_conn_event_t status, const int error, xmpp_stream_error_t * const stream_error, void * const userdata) { xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata; if (status == XMPP_CONN_CONNECT) { xmpp_stanza_t* pres; fprintf(stderr, "DEBUG: connected\n"); xmpp_handler_add(conn,version_handler, "jabber:iq:version", "iq", NULL, ctx); xmpp_handler_add(conn,message_handler, NULL, "message", NULL, ctx); /* Send initial so that we appear online to contacts */ pres = xmpp_stanza_new(ctx); xmpp_stanza_set_name(pres, "presence"); xmpp_send(conn, pres); xmpp_stanza_release(pres); } else { fprintf(stderr, "DEBUG: disconnected\n"); xmpp_stop(ctx); } } int main(int argc, char **argv) { xmpp_ctx_t *ctx; xmpp_conn_t *conn; xmpp_log_t *log; char *jid, *pass; /* take a jid and password on the command line */ if (argc != 3) { fprintf(stderr, "Usage: bot \n\n"); return 1; } jid = argv[1]; pass = argv[2]; /* init library */ xmpp_initialize(); /* create a context */ log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG); /* pass NULL instead to silence output */ ctx = xmpp_ctx_new(NULL, log); /* create a connection */ conn = xmpp_conn_new(ctx); /* setup authentication information */ xmpp_conn_set_jid(conn, jid); xmpp_conn_set_pass(conn, pass); /* initiate connection */ xmpp_connect_client(conn, NULL, 0, conn_handler, ctx); /* enter the event loop - our connect handler will trigger an exit */ xmpp_run(ctx); /* release our connection and context */ xmpp_conn_release(conn); xmpp_ctx_free(ctx); /* final shutdown of the library */ xmpp_shutdown(); return 0; } libstrophe-0.8.8/examples/component.c000066400000000000000000000047271256471717200177140ustar00rootroot00000000000000/* component.c ** libstrophe XMPP client library -- external component (XEP-0114) example ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /* This example demonstrates simple connection to a server ** as an external component. See XEP-0114 for more details. ** This program requires correctly configured server to run. */ #include #include #include /* define a handler for connection events */ void conn_handler(xmpp_conn_t * const conn, const xmpp_conn_event_t status, const int error, xmpp_stream_error_t * const stream_error, void * const userdata) { xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata; if (status == XMPP_CONN_CONNECT) { fprintf(stderr, "DEBUG: connected\n"); xmpp_disconnect(conn); } else { fprintf(stderr, "DEBUG: disconnected\n"); xmpp_stop(ctx); } } int main(int argc, char **argv) { xmpp_ctx_t *ctx; xmpp_conn_t *conn; xmpp_log_t *log; char *jid, *pass, *host, *port_err = NULL; unsigned short port = 0; /* take a jid and password on the command line */ if (argc < 4 || argc > 5) { fprintf(stderr, "Usage: component []\n\n"); return 1; } jid = argv[1]; pass = argv[2]; host = argv[3]; if (argc == 5) { short tmp_port = (short) strtol(argv[4], &port_err, 10); if (tmp_port < 0 || *port_err != '\0') { fprintf(stderr, "Invalid value of [%s].\n", argv[4]); return 1; } port = (unsigned short) tmp_port; } /* init library */ xmpp_initialize(); /* create a context */ log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG); /* pass NULL instead to silence output */ ctx = xmpp_ctx_new(NULL, log); /* create a connection */ conn = xmpp_conn_new(ctx); /* setup authentication information */ xmpp_conn_set_jid(conn, jid); xmpp_conn_set_pass(conn, pass); /* initiate connection */ xmpp_connect_component(conn, host, port, conn_handler, ctx); /* enter the event loop - our connect handler will trigger an exit */ xmpp_run(ctx); /* release our connection and context */ xmpp_conn_release(conn); xmpp_ctx_free(ctx); /* final shutdown of the library */ xmpp_shutdown(); return 0; } libstrophe-0.8.8/examples/roster.c000066400000000000000000000060711256471717200172220ustar00rootroot00000000000000/* roster.c ** libstrophe XMPP client library -- handler example ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /* This example demonstrates basic handler functions by printing out ** the user's roster. */ #include #include #include int handle_reply(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { xmpp_stanza_t *query, *item; char *type, *name; type = xmpp_stanza_get_type(stanza); if (strcmp(type, "error") == 0) fprintf(stderr, "ERROR: query failed\n"); else { query = xmpp_stanza_get_child_by_name(stanza, "query"); printf("Roster:\n"); for (item = xmpp_stanza_get_children(query); item; item = xmpp_stanza_get_next(item)) if ((name = xmpp_stanza_get_attribute(item, "name"))) printf("\t %s (%s) sub=%s\n", name, xmpp_stanza_get_attribute(item, "jid"), xmpp_stanza_get_attribute(item, "subscription")); else printf("\t %s sub=%s\n", xmpp_stanza_get_attribute(item, "jid"), xmpp_stanza_get_attribute(item, "subscription")); printf("END OF LIST\n"); } /* disconnect */ xmpp_disconnect(conn); return 0; } void conn_handler(xmpp_conn_t * const conn, const xmpp_conn_event_t status, const int error, xmpp_stream_error_t * const stream_error, void * const userdata) { xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata; xmpp_stanza_t *iq, *query; if (status == XMPP_CONN_CONNECT) { fprintf(stderr, "DEBUG: connected\n"); /* create iq stanza for request */ iq = xmpp_stanza_new(ctx); xmpp_stanza_set_name(iq, "iq"); xmpp_stanza_set_type(iq, "get"); xmpp_stanza_set_id(iq, "roster1"); query = xmpp_stanza_new(ctx); xmpp_stanza_set_name(query, "query"); xmpp_stanza_set_ns(query, XMPP_NS_ROSTER); xmpp_stanza_add_child(iq, query); /* we can release the stanza since it belongs to iq now */ xmpp_stanza_release(query); /* set up reply handler */ xmpp_id_handler_add(conn, handle_reply, "roster1", ctx); /* send out the stanza */ xmpp_send(conn, iq); /* release the stanza */ xmpp_stanza_release(iq); } else { fprintf(stderr, "DEBUG: disconnected\n"); xmpp_stop(ctx); } } int main(int argc, char **argv) { xmpp_ctx_t *ctx; xmpp_conn_t *conn; if (argc != 3) { fprintf(stderr, "Usage: roster \n\n"); return 1; } /* initialize lib */ xmpp_initialize(); /* create a context */ ctx = xmpp_ctx_new(NULL, NULL); /* create a connection */ conn = xmpp_conn_new(ctx); /* setup authentication information */ xmpp_conn_set_jid(conn, argv[1]); xmpp_conn_set_pass(conn, argv[2]); /* initiate connection */ xmpp_connect_client(conn, NULL, 0, conn_handler, ctx); /* start the event loop */ xmpp_run(ctx); /* release our connection and context */ xmpp_conn_release(conn); xmpp_ctx_free(ctx); /* shutdown lib */ xmpp_shutdown(); return 0; } libstrophe-0.8.8/expat/000077500000000000000000000000001256471717200150375ustar00rootroot00000000000000libstrophe-0.8.8/libstrophe.pc.in000066400000000000000000000005421256471717200170230ustar00rootroot00000000000000prefix=@prefix@ exec_prefix=@exec_prefix@ libdir=@libdir@ includedir=@includedir@ Name: libstrophe Description: A simple, lightweight C library for writing XMPP clients URL: http://strophe.im/libstrophe/ Version: @VERSION@ Requires: Requires.private: @PC_REQUIRES@ Libs: -L${libdir} -lstrophe Libs.private: @PC_LIBS@ Cflags: -I${includedir} @PC_CFLAGS@ libstrophe-0.8.8/rpm/000077500000000000000000000000001256471717200145145ustar00rootroot00000000000000libstrophe-0.8.8/rpm/README000066400000000000000000000011011256471717200153650ustar00rootroot000000000000001. Setup yum install gcc make expat-devel libstrophe Fedora: yum install fedora-packager cd ~ rpmdev-setuptree CentOS: mkdir -p ~/rpmbuild/{BUILD,RPMS,SOURCES,SPECS,SRPMS} Then make a tarball of sources: tar czf libstrophe_git.tar.gz libstrophe 2. Build cp libstrophe.spec ~/rpmbuild/SPECS cp libstrophe_git.tar.gz ~/rpmbuild/SOURCES rpmbuild -bb ~/rpmbuild/SPECS/libstrophe.spec 3. Install yum localinstall ~/rpmbuild/RPMS//libstrophe-1.1..rpm Or, if localinstall is not recognised: rpm -i ~/rpmbuild/RPMS//libstrophe-1.1..rpm libstrophe-0.8.8/rpm/libstrophe.spec000066400000000000000000000020551256471717200175450ustar00rootroot00000000000000Name: libstrophe Version: 1 Release: 1%{?dist}_git Summary: xmpp library in C Group: Application/System License: MIT/GPLv3 URL: http://strophe.im/libstrophe/ Source0: libstrophe_git.tar.gz BuildRequires: automake BuildRequires: libtool BuildRequires: openssl-devel BuildRequires: expat-devel Requires: expat %description XMPP library in C %package devel Summary: Headers and libraries for building apps that use libstrophe Group: Development/Libraries Requires: %{name} = %{version}-%{release} %description devel This package contains headers and libraries required to build applications that use the strophe XMPP library. %prep %setup -n libstrophe ./bootstrap.sh %build %configure make %{?_smp_mflags} %install make install DESTDIR=%{buildroot} %post -p /sbin/ldconfig %postun -p /sbin/ldconfig %files %defattr(-,root,root,-) %{_libdir}/libstrophe.so* %doc %files devel %defattr(-,root,root,-) %{_libdir}/libstrophe.a %{_libdir}/libstrophe.la %{_libdir}/pkgconfig/libstrophe.pc %{_includedir}/strophe.h %doc %changelog libstrophe-0.8.8/src/000077500000000000000000000000001256471717200145055ustar00rootroot00000000000000libstrophe-0.8.8/src/auth.c000066400000000000000000001062461256471717200156230ustar00rootroot00000000000000/* auth.c ** strophe XMPP client library -- auth functions and handlers ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express or ** implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Authentication function and handlers. */ #include #include #include #include #include "strophe.h" #include "common.h" #include "sasl.h" #include "sha1.h" #ifdef _MSC_VER #define strcasecmp stricmp #endif /* TODO: these should configurable at runtime on a per connection basis */ #ifndef FEATURES_TIMEOUT /** @def FEATURES_TIMEOUT * Time to wait for <stream:features/> stanza. */ #define FEATURES_TIMEOUT 15000 /* 15 seconds */ #endif #ifndef BIND_TIMEOUT /** @def BIND_TIMEOUT * Time to wait for <bind/> stanza reply. */ #define BIND_TIMEOUT 15000 /* 15 seconds */ #endif #ifndef SESSION_TIMEOUT /** @def SESSION_TIMEOUT * Time to wait for <session/> stanza reply. */ #define SESSION_TIMEOUT 15000 /* 15 seconds */ #endif #ifndef LEGACY_TIMEOUT /** @def LEGACY_TIMEOUT * Time to wait for legacy authentication to complete. */ #define LEGACY_TIMEOUT 15000 /* 15 seconds */ #endif #ifndef HANDSHAKE_TIMEOUT /** @def HANDSHAKE_TIMEOUT * Time to wait for component authentication to complete */ #define HANDSHAKE_TIMEOUT 15000 /* 15 seconds */ #endif static void _auth(xmpp_conn_t * const conn); static void _handle_open_sasl(xmpp_conn_t * const conn); static int _handle_component_auth(xmpp_conn_t * const conn); static int _handle_component_hs_response(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static int _handle_missing_legacy(xmpp_conn_t * const conn, void * const userdata); static int _handle_legacy(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static int _handle_features_sasl(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static int _handle_sasl_result(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static int _handle_digestmd5_challenge(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static int _handle_digestmd5_rspauth(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static int _handle_scram_sha1_challenge(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static char *_make_scram_sha1_init_msg(xmpp_conn_t * const conn); static int _handle_missing_features_sasl(xmpp_conn_t * const conn, void * const userdata); static int _handle_missing_bind(xmpp_conn_t * const conn, void * const userdata); static int _handle_bind(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static int _handle_session(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); static int _handle_missing_session(xmpp_conn_t * const conn, void * const userdata); static int _handle_missing_handshake(xmpp_conn_t * const conn, void * const userdata); /* stream:error handler */ static int _handle_error(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { xmpp_stanza_t *child; char *name; /* free old stream error if it's still there */ if (conn->stream_error) { xmpp_stanza_release(conn->stream_error->stanza); if (conn->stream_error->text) xmpp_free(conn->ctx, conn->stream_error->text); xmpp_free(conn->ctx, conn->stream_error); } /* create stream error structure */ conn->stream_error = (xmpp_stream_error_t *)xmpp_alloc(conn->ctx, sizeof(xmpp_stream_error_t)); conn->stream_error->text = NULL; conn->stream_error->type = XMPP_SE_UNDEFINED_CONDITION; if (conn->stream_error) { child = xmpp_stanza_get_children(stanza); do { char *ns = NULL; if (child) { ns = xmpp_stanza_get_ns(child); } if (ns && strcmp(ns, XMPP_NS_STREAMS_IETF) == 0) { name = xmpp_stanza_get_name(child); if (strcmp(name, "text") == 0) { if (conn->stream_error->text) xmpp_free(conn->ctx, conn->stream_error->text); conn->stream_error->text = xmpp_stanza_get_text(child); } else if (strcmp(name, "bad-format") == 0) conn->stream_error->type = XMPP_SE_BAD_FORMAT; else if (strcmp(name, "bad-namespace-prefix") == 0) conn->stream_error->type = XMPP_SE_BAD_NS_PREFIX; else if (strcmp(name, "conflict") == 0) conn->stream_error->type = XMPP_SE_CONFLICT; else if (strcmp(name, "connection-timeout") == 0) conn->stream_error->type = XMPP_SE_CONN_TIMEOUT; else if (strcmp(name, "host-gone") == 0) conn->stream_error->type = XMPP_SE_HOST_GONE; else if (strcmp(name, "host-unknown") == 0) conn->stream_error->type = XMPP_SE_HOST_UNKNOWN; else if (strcmp(name, "improper-addressing") == 0) conn->stream_error->type = XMPP_SE_IMPROPER_ADDR; else if (strcmp(name, "internal-server-error") == 0) conn->stream_error->type = XMPP_SE_INTERNAL_SERVER_ERROR; else if (strcmp(name, "invalid-from") == 0) conn->stream_error->type = XMPP_SE_INVALID_FROM; else if (strcmp(name, "invalid-id") == 0) conn->stream_error->type = XMPP_SE_INVALID_ID; else if (strcmp(name, "invalid-namespace") == 0) conn->stream_error->type = XMPP_SE_INVALID_NS; else if (strcmp(name, "invalid-xml") == 0) conn->stream_error->type = XMPP_SE_INVALID_XML; else if (strcmp(name, "not-authorized") == 0) conn->stream_error->type = XMPP_SE_NOT_AUTHORIZED; else if (strcmp(name, "policy-violation") == 0) conn->stream_error->type = XMPP_SE_POLICY_VIOLATION; else if (strcmp(name, "remote-connection-failed") == 0) conn->stream_error->type = XMPP_SE_REMOTE_CONN_FAILED; else if (strcmp(name, "resource-constraint") == 0) conn->stream_error->type = XMPP_SE_RESOURCE_CONSTRAINT; else if (strcmp(name, "restricted-xml") == 0) conn->stream_error->type = XMPP_SE_RESTRICTED_XML; else if (strcmp(name, "see-other-host") == 0) conn->stream_error->type = XMPP_SE_SEE_OTHER_HOST; else if (strcmp(name, "system-shutdown") == 0) conn->stream_error->type = XMPP_SE_SYSTEM_SHUTDOWN; else if (strcmp(name, "undefined-condition") == 0) conn->stream_error->type = XMPP_SE_UNDEFINED_CONDITION; else if (strcmp(name, "unsupported-encoding") == 0) conn->stream_error->type = XMPP_SE_UNSUPPORTED_ENCODING; else if (strcmp(name, "unsupported-stanza-type") == 0) conn->stream_error->type = XMPP_SE_UNSUPPORTED_STANZA_TYPE; else if (strcmp(name, "unsupported-version") == 0) conn->stream_error->type = XMPP_SE_UNSUPPORTED_VERSION; else if (strcmp(name, "xml-not-well-formed") == 0) conn->stream_error->type = XMPP_SE_XML_NOT_WELL_FORMED; } } while ((child = xmpp_stanza_get_next(child))); conn->stream_error->stanza = xmpp_stanza_clone(stanza); } return 1; } /* stream:features handlers */ static int _handle_missing_features(xmpp_conn_t * const conn, void * const userdata) { xmpp_debug(conn->ctx, "xmpp", "didn't get stream features"); /* legacy auth will be attempted */ _auth(conn); return 0; } static int _handle_features(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { xmpp_stanza_t *child, *mech; char *text; /* remove the handler that detects missing stream:features */ xmpp_timed_handler_delete(conn, _handle_missing_features); /* check for TLS */ if (!conn->secured) { if (!conn->tls_disabled) { child = xmpp_stanza_get_child_by_name(stanza, "starttls"); if (child && (strcmp(xmpp_stanza_get_ns(child), XMPP_NS_TLS) == 0)) conn->tls_support = 1; } else { conn->tls_support = 0; } } /* check for SASL */ child = xmpp_stanza_get_child_by_name(stanza, "mechanisms"); if (child && (strcmp(xmpp_stanza_get_ns(child), XMPP_NS_SASL) == 0)) { for (mech = xmpp_stanza_get_children(child); mech; mech = xmpp_stanza_get_next(mech)) { if (xmpp_stanza_get_name(mech) && strcmp(xmpp_stanza_get_name(mech), "mechanism") == 0) { text = xmpp_stanza_get_text(mech); if (strcasecmp(text, "PLAIN") == 0) conn->sasl_support |= SASL_MASK_PLAIN; else if (strcasecmp(text, "DIGEST-MD5") == 0) conn->sasl_support |= SASL_MASK_DIGESTMD5; else if (strcasecmp(text, "SCRAM-SHA-1") == 0) conn->sasl_support |= SASL_MASK_SCRAMSHA1; else if (strcasecmp(text, "ANONYMOUS") == 0) conn->sasl_support |= SASL_MASK_ANONYMOUS; xmpp_free(conn->ctx, text); } } } _auth(conn); return 0; } /* returns the correct auth id for a component or a client. * returned string must be freed by caller */ static char *_get_authid(xmpp_conn_t * const conn) { char *authid = NULL; if (conn->type == XMPP_CLIENT) { /* authid is the node portion of jid */ if (!conn->jid) return NULL; authid = xmpp_jid_node(conn->ctx, conn->jid); } return authid; } static int _handle_proceedtls_default(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { char *name; name = xmpp_stanza_get_name(stanza); xmpp_debug(conn->ctx, "xmpp", "handle proceedtls called for %s", name); if (strcmp(name, "proceed") == 0) { xmpp_debug(conn->ctx, "xmpp", "proceeding with TLS"); conn->tls = tls_new(conn->ctx, conn->sock); if (!tls_start(conn->tls)) { xmpp_debug(conn->ctx, "xmpp", "Couldn't start TLS! error %d", tls_error(conn->tls)); tls_free(conn->tls); conn->tls = NULL; conn->tls_failed = 1; /* failed tls spoils the connection, so disconnect */ xmpp_disconnect(conn); } else { conn->secured = 1; conn_prepare_reset(conn, auth_handle_open); conn_open_stream(conn); } } return 0; } static int _handle_sasl_result(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { char *name; name = xmpp_stanza_get_name(stanza); /* the server should send a or stanza */ if (strcmp(name, "failure") == 0) { xmpp_debug(conn->ctx, "xmpp", "SASL %s auth failed", (char *)userdata); /* fall back to next auth method */ _auth(conn); } else if (strcmp(name, "success") == 0) { /* SASL PLAIN auth successful, we need to restart the stream */ xmpp_debug(conn->ctx, "xmpp", "SASL %s auth successful", (char *)userdata); /* reset parser */ conn_prepare_reset(conn, _handle_open_sasl); /* send stream tag */ conn_open_stream(conn); } else { /* got unexpected reply */ xmpp_error(conn->ctx, "xmpp", "Got unexpected reply to SASL %s"\ "authentication.", (char *)userdata); xmpp_disconnect(conn); } return 0; } /* handle the challenge phase of digest auth */ static int _handle_digestmd5_challenge(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { char *text; char *response; xmpp_stanza_t *auth, *authdata; char *name; name = xmpp_stanza_get_name(stanza); xmpp_debug(conn->ctx, "xmpp",\ "handle digest-md5 (challenge) called for %s", name); if (strcmp(name, "challenge") == 0) { text = xmpp_stanza_get_text(stanza); response = sasl_digest_md5(conn->ctx, text, conn->jid, conn->pass); if (!response) { disconnect_mem_error(conn); return 0; } xmpp_free(conn->ctx, text); auth = xmpp_stanza_new(conn->ctx); if (!auth) { disconnect_mem_error(conn); return 0; } xmpp_stanza_set_name(auth, "response"); xmpp_stanza_set_ns(auth, XMPP_NS_SASL); authdata = xmpp_stanza_new(conn->ctx); if (!authdata) { disconnect_mem_error(conn); return 0; } xmpp_stanza_set_text(authdata, response); xmpp_free(conn->ctx, response); xmpp_stanza_add_child(auth, authdata); xmpp_stanza_release(authdata); handler_add(conn, _handle_digestmd5_rspauth, XMPP_NS_SASL, NULL, NULL, NULL); xmpp_send(conn, auth); xmpp_stanza_release(auth); } else { return _handle_sasl_result(conn, stanza, "DIGEST-MD5"); } /* remove ourselves */ return 0; } /* handle the rspauth phase of digest auth */ static int _handle_digestmd5_rspauth(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { xmpp_stanza_t *auth; char *name; name = xmpp_stanza_get_name(stanza); xmpp_debug(conn->ctx, "xmpp", "handle digest-md5 (rspauth) called for %s", name); if (strcmp(name, "challenge") == 0) { /* assume it's an rspauth response */ auth = xmpp_stanza_new(conn->ctx); if (!auth) { disconnect_mem_error(conn); return 0; } xmpp_stanza_set_name(auth, "response"); xmpp_stanza_set_ns(auth, XMPP_NS_SASL); xmpp_send(conn, auth); xmpp_stanza_release(auth); } else { return _handle_sasl_result(conn, stanza, "DIGEST-MD5"); } return 1; } /* handle the challenge phase of SCRAM-SHA-1 auth */ static int _handle_scram_sha1_challenge(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { char *text; char *response; xmpp_stanza_t *auth, *authdata; char *name; char *challenge; char *scram_init = (char *)userdata; name = xmpp_stanza_get_name(stanza); xmpp_debug(conn->ctx, "xmpp", "handle SCRAM-SHA-1 (challenge) called for %s", name); if (strcmp(name, "challenge") == 0) { text = xmpp_stanza_get_text(stanza); if (!text) goto err; challenge = (char *)base64_decode(conn->ctx, text, strlen(text)); xmpp_free(conn->ctx, text); if (!challenge) goto err; response = sasl_scram_sha1(conn->ctx, challenge, scram_init, conn->jid, conn->pass); xmpp_free(conn->ctx, challenge); if (!response) goto err; auth = xmpp_stanza_new(conn->ctx); if (!auth) goto err_free_response; xmpp_stanza_set_name(auth, "response"); xmpp_stanza_set_ns(auth, XMPP_NS_SASL); authdata = xmpp_stanza_new(conn->ctx); if (!authdata) goto err_release_auth; xmpp_stanza_set_text(authdata, response); xmpp_free(conn->ctx, response); xmpp_stanza_add_child(auth, authdata); xmpp_stanza_release(authdata); xmpp_send(conn, auth); xmpp_stanza_release(auth); } else { xmpp_free(conn->ctx, scram_init); return _handle_sasl_result(conn, stanza, "SCRAM-SHA-1"); } return 1; err_release_auth: xmpp_stanza_release(auth); err_free_response: xmpp_free(conn->ctx, response); err: xmpp_free(conn->ctx, scram_init); disconnect_mem_error(conn); return 0; } static char *_get_nonce(xmpp_ctx_t *ctx) { unsigned char buffer[sizeof(clock_t) + sizeof(time_t)] = {0}; clock_t ticks = clock(); time_t t; if (ticks != (clock_t)-1) { *(clock_t *)buffer = ticks; } t = time((time_t *)(buffer + sizeof(clock_t))); if (t == (time_t)-1) { *(time_t *)(buffer + sizeof(clock_t)) = (time_t)rand(); } return base64_encode(ctx, buffer, sizeof(buffer)); } static char *_make_scram_sha1_init_msg(xmpp_conn_t * const conn) { size_t message_len; char *node; char *message; char *nonce; node = xmpp_jid_node(conn->ctx, conn->jid); if (!node) { return NULL; } nonce = _get_nonce(conn->ctx); if (!nonce) { return NULL; } message_len = strlen(node) + strlen(nonce) + 8 + 1; message = xmpp_alloc(conn->ctx, message_len); if (message) { xmpp_snprintf(message, message_len, "n,,n=%s,r=%s", node, nonce); xmpp_free(conn->ctx, node); } xmpp_free(conn->ctx, nonce); return message; } static xmpp_stanza_t *_make_starttls(xmpp_conn_t * const conn) { xmpp_stanza_t *starttls; /* build start stanza */ starttls = xmpp_stanza_new(conn->ctx); if (starttls) { xmpp_stanza_set_name(starttls, "starttls"); xmpp_stanza_set_ns(starttls, XMPP_NS_TLS); } return starttls; } static xmpp_stanza_t *_make_sasl_auth(xmpp_conn_t * const conn, const char * const mechanism) { xmpp_stanza_t *auth; /* build auth stanza */ auth = xmpp_stanza_new(conn->ctx); if (auth) { xmpp_stanza_set_name(auth, "auth"); xmpp_stanza_set_ns(auth, XMPP_NS_SASL); xmpp_stanza_set_attribute(auth, "mechanism", mechanism); } return auth; } /* authenticate the connection * this may get called multiple times. if any auth method fails, * this will get called again until one auth method succeeds or every * method fails */ static void _auth(xmpp_conn_t * const conn) { xmpp_stanza_t *auth, *authdata, *query, *child, *iq; char *str, *authid; char *scram_init; int anonjid; /* if there is no node in conn->jid, we assume anonymous connect */ str = xmpp_jid_node(conn->ctx, conn->jid); if (str == NULL) { anonjid = 1; } else { xmpp_free(conn->ctx, str); anonjid = 0; } if (conn->tls_support) { tls_t *tls = tls_new(conn->ctx, conn->sock); /* If we couldn't init tls, it isn't there, so go on */ if (!tls) { conn->tls_support = 0; _auth(conn); return; } else { tls_free(tls); } auth = _make_starttls(conn); if (!auth) { disconnect_mem_error(conn); return; } handler_add(conn, _handle_proceedtls_default, XMPP_NS_TLS, NULL, NULL, NULL); xmpp_send(conn, auth); xmpp_stanza_release(auth); /* TLS was tried, unset flag */ conn->tls_support = 0; } else if (anonjid && conn->sasl_support & SASL_MASK_ANONYMOUS) { /* some crap here */ auth = _make_sasl_auth(conn, "ANONYMOUS"); if (!auth) { disconnect_mem_error(conn); return; } handler_add(conn, _handle_sasl_result, XMPP_NS_SASL, NULL, NULL, "ANONYMOUS"); xmpp_send(conn, auth); xmpp_stanza_release(auth); /* SASL ANONYMOUS was tried, unset flag */ conn->sasl_support &= ~SASL_MASK_ANONYMOUS; } else if (anonjid) { xmpp_error(conn->ctx, "auth", "No node in JID, and SASL ANONYMOUS unsupported."); xmpp_disconnect(conn); } else if (conn->sasl_support & SASL_MASK_SCRAMSHA1) { auth = _make_sasl_auth(conn, "SCRAM-SHA-1"); if (!auth) { disconnect_mem_error(conn); return; } /* don't free scram_init on success */ scram_init = _make_scram_sha1_init_msg(conn); if (!scram_init) { xmpp_stanza_release(auth); disconnect_mem_error(conn); return; } str = (char *)base64_encode(conn->ctx, (unsigned char *)scram_init, strlen(scram_init)); if (!str) { xmpp_free(conn->ctx, scram_init); xmpp_stanza_release(auth); disconnect_mem_error(conn); return; } authdata = xmpp_stanza_new(conn->ctx); if (!authdata) { xmpp_free(conn->ctx, str); xmpp_free(conn->ctx, scram_init); xmpp_stanza_release(auth); disconnect_mem_error(conn); return; } xmpp_stanza_set_text(authdata, str); xmpp_free(conn->ctx, str); xmpp_stanza_add_child(auth, authdata); xmpp_stanza_release(authdata); handler_add(conn, _handle_scram_sha1_challenge, XMPP_NS_SASL, NULL, NULL, (void *)scram_init); xmpp_send(conn, auth); xmpp_stanza_release(auth); /* SASL SCRAM-SHA-1 was tried, unset flag */ conn->sasl_support &= ~SASL_MASK_SCRAMSHA1; } else if (conn->sasl_support & SASL_MASK_DIGESTMD5) { auth = _make_sasl_auth(conn, "DIGEST-MD5"); if (!auth) { disconnect_mem_error(conn); return; } handler_add(conn, _handle_digestmd5_challenge, XMPP_NS_SASL, NULL, NULL, NULL); xmpp_send(conn, auth); xmpp_stanza_release(auth); /* SASL DIGEST-MD5 was tried, unset flag */ conn->sasl_support &= ~SASL_MASK_DIGESTMD5; } else if (conn->sasl_support & SASL_MASK_PLAIN) { auth = _make_sasl_auth(conn, "PLAIN"); if (!auth) { disconnect_mem_error(conn); return; } authdata = xmpp_stanza_new(conn->ctx); if (!authdata) { disconnect_mem_error(conn); return; } authid = _get_authid(conn); if (!authid) { disconnect_mem_error(conn); return; } str = sasl_plain(conn->ctx, authid, conn->pass); if (!str) { disconnect_mem_error(conn); return; } xmpp_stanza_set_text(authdata, str); xmpp_free(conn->ctx, str); xmpp_free(conn->ctx, authid); xmpp_stanza_add_child(auth, authdata); xmpp_stanza_release(authdata); handler_add(conn, _handle_sasl_result, XMPP_NS_SASL, NULL, NULL, "PLAIN"); xmpp_send(conn, auth); xmpp_stanza_release(auth); /* SASL PLAIN was tried */ conn->sasl_support &= ~SASL_MASK_PLAIN; } else if (conn->type == XMPP_CLIENT) { /* legacy client authentication */ iq = xmpp_stanza_new(conn->ctx); if (!iq) { disconnect_mem_error(conn); return; } xmpp_stanza_set_name(iq, "iq"); xmpp_stanza_set_type(iq, "set"); xmpp_stanza_set_id(iq, "_xmpp_auth1"); query = xmpp_stanza_new(conn->ctx); if (!query) { xmpp_stanza_release(iq); disconnect_mem_error(conn); return; } xmpp_stanza_set_name(query, "query"); xmpp_stanza_set_ns(query, XMPP_NS_AUTH); xmpp_stanza_add_child(iq, query); xmpp_stanza_release(query); child = xmpp_stanza_new(conn->ctx); if (!child) { xmpp_stanza_release(iq); disconnect_mem_error(conn); return; } xmpp_stanza_set_name(child, "username"); xmpp_stanza_add_child(query, child); xmpp_stanza_release(child); authdata = xmpp_stanza_new(conn->ctx); if (!authdata) { xmpp_stanza_release(iq); disconnect_mem_error(conn); return; } str = xmpp_jid_node(conn->ctx, conn->jid); xmpp_stanza_set_text(authdata, str); xmpp_free(conn->ctx, str); xmpp_stanza_add_child(child, authdata); xmpp_stanza_release(authdata); child = xmpp_stanza_new(conn->ctx); if (!child) { xmpp_stanza_release(iq); disconnect_mem_error(conn); return; } xmpp_stanza_set_name(child, "password"); xmpp_stanza_add_child(query, child); xmpp_stanza_release(child); authdata = xmpp_stanza_new(conn->ctx); if (!authdata) { xmpp_stanza_release(iq); disconnect_mem_error(conn); return; } xmpp_stanza_set_text(authdata, conn->pass); xmpp_stanza_add_child(child, authdata); xmpp_stanza_release(authdata); child = xmpp_stanza_new(conn->ctx); if (!child) { xmpp_stanza_release(iq); disconnect_mem_error(conn); return; } xmpp_stanza_set_name(child, "resource"); xmpp_stanza_add_child(query, child); xmpp_stanza_release(child); authdata = xmpp_stanza_new(conn->ctx); if (!authdata) { xmpp_stanza_release(iq); disconnect_mem_error(conn); return; } str = xmpp_jid_resource(conn->ctx, conn->jid); if (str) { xmpp_stanza_set_text(authdata, str); xmpp_free(conn->ctx, str); } else { xmpp_stanza_release(authdata); xmpp_stanza_release(iq); xmpp_error(conn->ctx, "auth", "Cannot authenticate without resource"); xmpp_disconnect(conn); return; } xmpp_stanza_add_child(child, authdata); xmpp_stanza_release(authdata); handler_add_id(conn, _handle_legacy, "_xmpp_auth1", NULL); handler_add_timed(conn, _handle_missing_legacy, LEGACY_TIMEOUT, NULL); xmpp_send(conn, iq); xmpp_stanza_release(iq); } } /** Set up handlers at stream start. * This function is called internally to Strophe for handling the opening * of an XMPP stream. It's called by the parser when a stream is opened * or reset, and adds the initial handlers for and * . This function is not intended for use outside * of Strophe. * * @param conn a Strophe connection object */ void auth_handle_open(xmpp_conn_t * const conn) { /* reset all timed handlers */ handler_reset_timed(conn, 0); /* setup handler for stream:error */ handler_add(conn, _handle_error, XMPP_NS_STREAMS, "error", NULL, NULL); /* setup handlers for incoming */ handler_add(conn, _handle_features, XMPP_NS_STREAMS, "features", NULL, NULL); handler_add_timed(conn, _handle_missing_features, FEATURES_TIMEOUT, NULL); } /* called when stream:stream tag received after SASL auth */ static void _handle_open_sasl(xmpp_conn_t * const conn) { xmpp_debug(conn->ctx, "xmpp", "Reopened stream successfully."); /* setup stream:features handlers */ handler_add(conn, _handle_features_sasl, XMPP_NS_STREAMS, "features", NULL, NULL); handler_add_timed(conn, _handle_missing_features_sasl, FEATURES_TIMEOUT, NULL); } static int _handle_features_sasl(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { xmpp_stanza_t *bind, *session, *iq, *res, *text; char *resource; /* remove missing features handler */ xmpp_timed_handler_delete(conn, _handle_missing_features_sasl); /* we are expecting and since this is a XMPP style connection */ bind = xmpp_stanza_get_child_by_name(stanza, "bind"); if (bind && strcmp(xmpp_stanza_get_ns(bind), XMPP_NS_BIND) == 0) { /* resource binding is required */ conn->bind_required = 1; } session = xmpp_stanza_get_child_by_name(stanza, "session"); if (session && strcmp(xmpp_stanza_get_ns(session), XMPP_NS_SESSION) == 0) { /* session establishment required */ conn->session_required = 1; } /* if bind is required, go ahead and start it */ if (conn->bind_required) { /* bind resource */ /* setup response handlers */ handler_add_id(conn, _handle_bind, "_xmpp_bind1", NULL); handler_add_timed(conn, _handle_missing_bind, BIND_TIMEOUT, NULL); /* send bind request */ iq = xmpp_stanza_new(conn->ctx); if (!iq) { disconnect_mem_error(conn); return 0; } xmpp_stanza_set_name(iq, "iq"); xmpp_stanza_set_type(iq, "set"); xmpp_stanza_set_id(iq, "_xmpp_bind1"); bind = xmpp_stanza_copy(bind); if (!bind) { xmpp_stanza_release(iq); disconnect_mem_error(conn); return 0; } /* request a specific resource if we have one */ resource = xmpp_jid_resource(conn->ctx, conn->jid); if ((resource != NULL) && (strlen(resource) == 0)) { /* jabberd2 doesn't handle an empty resource */ xmpp_free(conn->ctx, resource); resource = NULL; } /* if we have a resource to request, do it. otherwise the server will assign us one */ if (resource) { res = xmpp_stanza_new(conn->ctx); if (!res) { xmpp_stanza_release(bind); xmpp_stanza_release(iq); disconnect_mem_error(conn); return 0; } xmpp_stanza_set_name(res, "resource"); text = xmpp_stanza_new(conn->ctx); if (!text) { xmpp_stanza_release(res); xmpp_stanza_release(bind); xmpp_stanza_release(iq); disconnect_mem_error(conn); return 0; } xmpp_stanza_set_text(text, resource); xmpp_stanza_add_child(res, text); xmpp_stanza_release(text); xmpp_stanza_add_child(bind, res); xmpp_stanza_release(res); xmpp_free(conn->ctx, resource); } xmpp_stanza_add_child(iq, bind); xmpp_stanza_release(bind); /* send bind request */ xmpp_send(conn, iq); xmpp_stanza_release(iq); } else { /* can't bind, disconnect */ xmpp_error(conn->ctx, "xmpp", "Stream features does not allow "\ "resource bind."); xmpp_disconnect(conn); } return 0; } static int _handle_missing_features_sasl(xmpp_conn_t * const conn, void * const userdata) { xmpp_error(conn->ctx, "xmpp", "Did not receive stream features "\ "after SASL authentication."); xmpp_disconnect(conn); return 0; } static int _handle_bind(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { char *type; xmpp_stanza_t *iq, *session; /* delete missing bind handler */ xmpp_timed_handler_delete(conn, _handle_missing_bind); /* server has replied to bind request */ type = xmpp_stanza_get_type(stanza); if (type && strcmp(type, "error") == 0) { xmpp_error(conn->ctx, "xmpp", "Binding failed."); xmpp_disconnect(conn); } else if (type && strcmp(type, "result") == 0) { xmpp_stanza_t *binding = xmpp_stanza_get_child_by_name(stanza, "bind"); xmpp_debug(conn->ctx, "xmpp", "Bind successful."); if (binding) { xmpp_stanza_t *jid_stanza = xmpp_stanza_get_child_by_name(binding, "jid"); if (jid_stanza) { conn->bound_jid = xmpp_stanza_get_text(jid_stanza); } } /* establish a session if required */ if (conn->session_required) { /* setup response handlers */ handler_add_id(conn, _handle_session, "_xmpp_session1", NULL); handler_add_timed(conn, _handle_missing_session, SESSION_TIMEOUT, NULL); /* send session request */ iq = xmpp_stanza_new(conn->ctx); if (!iq) { disconnect_mem_error(conn); return 0; } xmpp_stanza_set_name(iq, "iq"); xmpp_stanza_set_type(iq, "set"); xmpp_stanza_set_id(iq, "_xmpp_session1"); session = xmpp_stanza_new(conn->ctx); if (!session) { xmpp_stanza_release(iq); disconnect_mem_error(conn); } xmpp_stanza_set_name(session, "session"); xmpp_stanza_set_ns(session, XMPP_NS_SESSION); xmpp_stanza_add_child(iq, session); xmpp_stanza_release(session); /* send session establishment request */ xmpp_send(conn, iq); xmpp_stanza_release(iq); } else { conn->authenticated = 1; /* call connection handler */ conn->conn_handler(conn, XMPP_CONN_CONNECT, 0, NULL, conn->userdata); } } else { xmpp_error(conn->ctx, "xmpp", "Server sent malformed bind reply."); xmpp_disconnect(conn); } return 0; } static int _handle_missing_bind(xmpp_conn_t * const conn, void * const userdata) { xmpp_error(conn->ctx, "xmpp", "Server did not reply to bind request."); xmpp_disconnect(conn); return 0; } static int _handle_session(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { char *type; /* delete missing session handler */ xmpp_timed_handler_delete(conn, _handle_missing_session); /* server has replied to the session request */ type = xmpp_stanza_get_type(stanza); if (type && strcmp(type, "error") == 0) { xmpp_error(conn->ctx, "xmpp", "Session establishment failed."); xmpp_disconnect(conn); } else if (type && strcmp(type, "result") == 0) { xmpp_debug(conn->ctx, "xmpp", "Session establishment successful."); conn->authenticated = 1; /* call connection handler */ conn->conn_handler(conn, XMPP_CONN_CONNECT, 0, NULL, conn->userdata); } else { xmpp_error(conn->ctx, "xmpp", "Server sent malformed session reply."); xmpp_disconnect(conn); } return 0; } static int _handle_missing_session(xmpp_conn_t * const conn, void * const userdata) { xmpp_error(conn->ctx, "xmpp", "Server did not reply to session request."); xmpp_disconnect(conn); return 0; } static int _handle_legacy(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { char *type, *name; /* delete missing handler */ xmpp_timed_handler_delete(conn, _handle_missing_legacy); /* server responded to legacy auth request */ type = xmpp_stanza_get_type(stanza); name = xmpp_stanza_get_name(stanza); if (!type || strcmp(name, "iq") != 0) { xmpp_error(conn->ctx, "xmpp", "Server sent us an unexpected response "\ "to legacy authentication request."); xmpp_disconnect(conn); } else if (strcmp(type, "error") == 0) { /* legacy client auth failed, no more fallbacks */ xmpp_error(conn->ctx, "xmpp", "Legacy client authentication failed."); xmpp_disconnect(conn); } else if (strcmp(type, "result") == 0) { /* auth succeeded */ xmpp_debug(conn->ctx, "xmpp", "Legacy auth succeeded."); conn->authenticated = 1; conn->conn_handler(conn, XMPP_CONN_CONNECT, 0, NULL, conn->userdata); } else { xmpp_error(conn->ctx, "xmpp", "Server sent us a legacy authentication "\ "response with a bad type."); xmpp_disconnect(conn); } return 0; } static int _handle_missing_legacy(xmpp_conn_t * const conn, void * const userdata) { xmpp_error(conn->ctx, "xmpp", "Server did not reply to legacy "\ "authentication request."); xmpp_disconnect(conn); return 0; } void auth_handle_component_open(xmpp_conn_t * const conn) { /* reset all timed handlers */ handler_reset_timed(conn, 0); handler_add(conn, _handle_error, XMPP_NS_STREAMS, "error", NULL, NULL); handler_add(conn, _handle_component_hs_response, NULL, "handshake", NULL, NULL); handler_add_timed(conn, _handle_missing_handshake, HANDSHAKE_TIMEOUT, NULL); _handle_component_auth(conn); } /* Will compute SHA1 and authenticate the component to the server */ int _handle_component_auth(xmpp_conn_t * const conn) { uint8_t md_value[SHA1_DIGEST_SIZE]; SHA1_CTX mdctx; char *digest; size_t i; /* Feed the session id and passphrase to the algorithm. * We need to compute SHA1(session_id + passphrase) */ SHA1_Init(&mdctx); SHA1_Update(&mdctx, (uint8_t*)conn->stream_id, strlen(conn->stream_id)); SHA1_Update(&mdctx, (uint8_t*)conn->pass, strlen(conn->pass)); SHA1_Final(&mdctx, md_value); digest = xmpp_alloc(conn->ctx, 2*sizeof(md_value)+1); if (digest) { /* convert the digest into string representation */ for (i = 0; i < sizeof(md_value); i++) xmpp_snprintf(digest+i*2, 3, "%02x", md_value[i]); digest[2*sizeof(md_value)] = '\0'; xmpp_debug(conn->ctx, "auth", "Digest: %s, len: %d", digest, strlen(digest)); /* Send the digest to the server */ xmpp_send_raw_string(conn, "%s", XMPP_NS_COMPONENT, digest); xmpp_debug(conn->ctx, "auth", "Sent component handshake to the server."); xmpp_free(conn->ctx, digest); } else { xmpp_debug(conn->ctx, "auth", "Couldn't allocate memory for component "\ "handshake digest."); xmpp_disconnect(conn); return XMPP_EMEM; } return 0; } /* Check if the received stanza is and set auth to true * and fire connection handler. */ int _handle_component_hs_response(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata) { char *name; xmpp_timed_handler_delete(conn, _handle_missing_handshake); name = xmpp_stanza_get_name(stanza); if (strcmp(name, "handshake") != 0) { char *msg; size_t msg_size; xmpp_stanza_to_text(stanza, &msg, &msg_size); if (msg) { xmpp_debug(conn->ctx, "auth", "Handshake failed: %s", msg); xmpp_free(conn->ctx, msg); } xmpp_disconnect(conn); return XMPP_EINT; } else { conn->authenticated = 1; conn->conn_handler(conn, XMPP_CONN_CONNECT, 0, NULL, conn->userdata); } /* We don't need this handler anymore, return 0 so it can be deleted * from the list of handlers. */ return 0; } int _handle_missing_handshake(xmpp_conn_t * const conn, void * const userdata) { xmpp_error(conn->ctx, "xmpp", "Server did not reply to handshake request."); xmpp_disconnect(conn); return 0; } libstrophe-0.8.8/src/common.h000066400000000000000000000151101256471717200161440ustar00rootroot00000000000000/* common.h ** strophe XMPP client library -- internal common structures ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express or ** implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Internally used functions and structures. */ #ifndef __LIBSTROPHE_COMMON_H__ #define __LIBSTROPHE_COMMON_H__ #include #include #include "strophe.h" #include "ostypes.h" #include "sock.h" #include "tls.h" #include "hash.h" #include "util.h" #include "parser.h" /** run-time context **/ typedef enum { XMPP_LOOP_NOTSTARTED, XMPP_LOOP_RUNNING, XMPP_LOOP_QUIT } xmpp_loop_status_t; typedef struct _xmpp_connlist_t { xmpp_conn_t *conn; struct _xmpp_connlist_t *next; } xmpp_connlist_t; struct _xmpp_ctx_t { const xmpp_mem_t *mem; const xmpp_log_t *log; xmpp_loop_status_t loop_status; xmpp_connlist_t *connlist; }; /* convenience functions for accessing the context */ void *xmpp_alloc(const xmpp_ctx_t * const ctx, const size_t size); void *xmpp_realloc(const xmpp_ctx_t * const ctx, void *p, const size_t size); char *xmpp_strdup(const xmpp_ctx_t * const ctx, const char * const s); void xmpp_log(const xmpp_ctx_t * const ctx, const xmpp_log_level_t level, const char * const area, const char * const fmt, va_list ap); /* wrappers for xmpp_log at specific levels */ void xmpp_error(const xmpp_ctx_t * const ctx, const char * const area, const char * const fmt, ...); void xmpp_warn(const xmpp_ctx_t * const ctx, const char * const area, const char * const fmt, ...); void xmpp_info(const xmpp_ctx_t * const ctx, const char * const area, const char * const fmt, ...); void xmpp_debug(const xmpp_ctx_t * const ctx, const char * const area, const char * const fmt, ...); /** jid */ /* these return new strings that must be xmpp_free()'d */ char *xmpp_jid_new(xmpp_ctx_t *ctx, const char *node, const char *domain, const char *resource); char *xmpp_jid_bare(xmpp_ctx_t *ctx, const char *jid); char *xmpp_jid_node(xmpp_ctx_t *ctx, const char *jid); char *xmpp_jid_domain(xmpp_ctx_t *ctx, const char *jid); char *xmpp_jid_resource(xmpp_ctx_t *ctx, const char *jid); /** connection **/ /* opaque connection object */ typedef enum { XMPP_STATE_DISCONNECTED, XMPP_STATE_CONNECTING, XMPP_STATE_CONNECTED } xmpp_conn_state_t; typedef struct _xmpp_send_queue_t xmpp_send_queue_t; struct _xmpp_send_queue_t { char *data; size_t len; size_t written; xmpp_send_queue_t *next; }; typedef struct _xmpp_handlist_t xmpp_handlist_t; struct _xmpp_handlist_t { /* common members */ int user_handler; void *handler; void *userdata; int enabled; /* handlers are added disabled and enabled after the * handler chain is processed to prevent stanzas from * getting processed by newly added handlers */ xmpp_handlist_t *next; union { /* timed handlers */ struct { unsigned long period; uint64_t last_stamp; }; /* id handlers */ struct { char *id; }; /* normal handlers */ struct { char *ns; char *name; char *type; }; }; }; #define SASL_MASK_PLAIN 0x01 #define SASL_MASK_DIGESTMD5 0x02 #define SASL_MASK_ANONYMOUS 0x04 #define SASL_MASK_SCRAMSHA1 0x08 typedef void (*xmpp_open_handler)(xmpp_conn_t * const conn); struct _xmpp_conn_t { unsigned int ref; xmpp_ctx_t *ctx; xmpp_conn_type_t type; xmpp_conn_state_t state; uint64_t timeout_stamp; int error; xmpp_stream_error_t *stream_error; sock_t sock; tls_t *tls; int tls_support; int tls_disabled; int tls_failed; /* set when tls fails, so we don't try again */ int sasl_support; /* if true, field is a bitfield of supported mechanisms */ int secured; /* set when stream is secured with TLS */ /* if server returns or we must do them */ int bind_required; int session_required; char *lang; char *domain; char *connectdomain; char *connectport; char *jid; char *pass; char *bound_jid; char *stream_id; /* send queue and parameters */ int blocking_send; int send_queue_max; int send_queue_len; xmpp_send_queue_t *send_queue_head; xmpp_send_queue_t *send_queue_tail; /* xml parser */ int reset_parser; parser_t *parser; /* timeouts */ unsigned int connect_timeout; /* event handlers */ /* stream open handler */ xmpp_open_handler open_handler; /* user handlers only get called after authentication */ int authenticated; /* connection events handler */ xmpp_conn_handler conn_handler; void *userdata; /* other handlers */ xmpp_handlist_t *timed_handlers; hash_t *id_handlers; xmpp_handlist_t *handlers; }; void conn_disconnect(xmpp_conn_t * const conn); void conn_disconnect_clean(xmpp_conn_t * const conn); void conn_open_stream(xmpp_conn_t * const conn); void conn_prepare_reset(xmpp_conn_t * const conn, xmpp_open_handler handler); void conn_parser_reset(xmpp_conn_t * const conn); typedef enum { XMPP_STANZA_UNKNOWN, XMPP_STANZA_TEXT, XMPP_STANZA_TAG } xmpp_stanza_type_t; struct _xmpp_stanza_t { int ref; xmpp_ctx_t *ctx; xmpp_stanza_type_t type; xmpp_stanza_t *prev; xmpp_stanza_t *next; xmpp_stanza_t *children; xmpp_stanza_t *parent; char *data; hash_t *attributes; }; /* handler management */ void handler_fire_stanza(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza); uint64_t handler_fire_timed(xmpp_ctx_t * const ctx); void handler_reset_timed(xmpp_conn_t *conn, int user_only); void handler_add_timed(xmpp_conn_t * const conn, xmpp_timed_handler handler, const unsigned long period, void * const userdata); void handler_add_id(xmpp_conn_t * const conn, xmpp_handler handler, const char * const id, void * const userdata); void handler_add(xmpp_conn_t * const conn, xmpp_handler handler, const char * const ns, const char * const name, const char * const type, void * const userdata); /* utility functions */ void disconnect_mem_error(xmpp_conn_t * const conn); /* auth functions */ void auth_handle_open(xmpp_conn_t * const conn); void auth_handle_component_open(xmpp_conn_t * const conn); /* replacement snprintf and vsnprintf */ int xmpp_snprintf (char *str, size_t count, const char *fmt, ...); int xmpp_vsnprintf (char *str, size_t count, const char *fmt, va_list arg); #endif /* __LIBSTROPHE_COMMON_H__ */ libstrophe-0.8.8/src/conn.c000066400000000000000000000574231256471717200156210ustar00rootroot00000000000000/* conn.c ** strophe XMPP client library -- connection object functions ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Connection management. */ /** @defgroup Connections Connection management */ #include #include #include #include #include "common.h" #include "util.h" #include "parser.h" #ifndef DEFAULT_SEND_QUEUE_MAX /** @def DEFAULT_SEND_QUEUE_MAX * The default maximum send queue size. This is currently unused. */ #define DEFAULT_SEND_QUEUE_MAX 64 #endif #ifndef DISCONNECT_TIMEOUT /** @def DISCONNECT_TIMEOUT * The time to wait (in milliseconds) for graceful disconnection to * complete before the connection is reset. The default is 2 seconds. */ #define DISCONNECT_TIMEOUT 2000 /* 2 seconds */ #endif #ifndef CONNECT_TIMEOUT /** @def CONNECT_TIMEOUT * The time to wait (in milliseconds) for a connection attempt to succeed * or error. The default is 5 seconds. */ #define CONNECT_TIMEOUT 5000 /* 5 seconds */ #endif static int _disconnect_cleanup(xmpp_conn_t * const conn, void * const userdata); static void _handle_stream_start(char *name, char **attrs, void * const userdata); static void _handle_stream_end(char *name, void * const userdata); static void _handle_stream_stanza(xmpp_stanza_t *stanza, void * const userdata); /** Create a new Strophe connection object. * * @param ctx a Strophe context object * * @return a Strophe connection object or NULL on an error * * @ingroup Connections */ xmpp_conn_t *xmpp_conn_new(xmpp_ctx_t * const ctx) { xmpp_conn_t *conn = NULL; xmpp_connlist_t *tail, *item; if (ctx == NULL) return NULL; conn = xmpp_alloc(ctx, sizeof(xmpp_conn_t)); if (conn != NULL) { conn->ctx = ctx; conn->type = XMPP_UNKNOWN; conn->state = XMPP_STATE_DISCONNECTED; conn->sock = -1; conn->tls = NULL; conn->timeout_stamp = 0; conn->error = 0; conn->stream_error = NULL; /* default send parameters */ conn->blocking_send = 0; conn->send_queue_max = DEFAULT_SEND_QUEUE_MAX; conn->send_queue_len = 0; conn->send_queue_head = NULL; conn->send_queue_tail = NULL; /* default timeouts */ conn->connect_timeout = CONNECT_TIMEOUT; conn->lang = xmpp_strdup(conn->ctx, "en"); if (!conn->lang) { xmpp_free(conn->ctx, conn); return NULL; } conn->domain = NULL; conn->jid = NULL; conn->pass = NULL; conn->stream_id = NULL; conn->bound_jid = NULL; conn->tls_support = 0; conn->tls_disabled = 0; conn->tls_failed = 0; conn->sasl_support = 0; conn->secured = 0; conn->bind_required = 0; conn->session_required = 0; conn->parser = parser_new(conn->ctx, _handle_stream_start, _handle_stream_end, _handle_stream_stanza, conn); conn->reset_parser = 0; conn_prepare_reset(conn, auth_handle_open); conn->authenticated = 0; conn->conn_handler = NULL; conn->userdata = NULL; conn->timed_handlers = NULL; /* we own (and will free) the hash values */ conn->id_handlers = hash_new(conn->ctx, 32, NULL); conn->handlers = NULL; /* give the caller a reference to connection */ conn->ref = 1; /* add connection to ctx->connlist */ tail = conn->ctx->connlist; while (tail && tail->next) tail = tail->next; item = xmpp_alloc(conn->ctx, sizeof(xmpp_connlist_t)); if (!item) { xmpp_error(conn->ctx, "xmpp", "failed to allocate memory"); xmpp_free(conn->ctx, conn->lang); parser_free(conn->parser); xmpp_free(conn->ctx, conn); conn = NULL; } else { item->conn = conn; item->next = NULL; if (tail) tail->next = item; else conn->ctx->connlist = item; } } return conn; } /** Clone a Strophe connection object. * * @param conn a Strophe connection object * * @return the same conn object passed in with its reference count * incremented by 1 * * @ingroup Connections */ xmpp_conn_t *xmpp_conn_clone(xmpp_conn_t * const conn) { conn->ref++; return conn; } /** Release a Strophe connection object. * Decrement the reference count by one for a connection, freeing the * connection object if the count reaches 0. * * @param conn a Strophe connection object * * @return TRUE if the connection object was freed and FALSE otherwise * * @ingroup Connections */ int xmpp_conn_release(xmpp_conn_t * const conn) { xmpp_ctx_t *ctx; xmpp_connlist_t *item, *prev; xmpp_handlist_t *hlitem, *thli; hash_iterator_t *iter; const char *key; int released = 0; if (conn->ref > 1) conn->ref--; else { ctx = conn->ctx; /* remove connection from context's connlist */ if (ctx->connlist->conn == conn) { item = ctx->connlist; ctx->connlist = item->next; xmpp_free(ctx, item); } else { prev = NULL; item = ctx->connlist; while (item && item->conn != conn) { prev = item; item = item->next; } if (!item) { xmpp_error(ctx, "xmpp", "Connection not in context's list\n"); } else { prev->next = item->next; xmpp_free(ctx, item); } } /* free handler stuff * note that userdata is the responsibility of the client * and the handler pointers don't need to be freed since they * are pointers to functions */ hlitem = conn->timed_handlers; while (hlitem) { thli = hlitem; hlitem = hlitem->next; xmpp_free(ctx, thli); } /* id handlers * we have to traverse the hash table freeing list elements * then release the hash table */ iter = hash_iter_new(conn->id_handlers); while ((key = hash_iter_next(iter))) { hlitem = (xmpp_handlist_t *)hash_get(conn->id_handlers, key); while (hlitem) { thli = hlitem; hlitem = hlitem->next; xmpp_free(conn->ctx, thli->id); xmpp_free(conn->ctx, thli); } } hash_iter_release(iter); hash_release(conn->id_handlers); hlitem = conn->handlers; while (hlitem) { thli = hlitem; hlitem = hlitem->next; if (thli->ns) xmpp_free(ctx, thli->ns); if (thli->name) xmpp_free(ctx, thli->name); if (thli->type) xmpp_free(ctx, thli->type); xmpp_free(ctx, thli); } if (conn->stream_error) { xmpp_stanza_release(conn->stream_error->stanza); if (conn->stream_error->text) xmpp_free(ctx, conn->stream_error->text); xmpp_free(ctx, conn->stream_error); } parser_free(conn->parser); if (conn->domain) xmpp_free(ctx, conn->domain); if (conn->jid) xmpp_free(ctx, conn->jid); if (conn->bound_jid) xmpp_free(ctx, conn->bound_jid); if (conn->pass) xmpp_free(ctx, conn->pass); if (conn->stream_id) xmpp_free(ctx, conn->stream_id); if (conn->lang) xmpp_free(ctx, conn->lang); xmpp_free(ctx, conn); released = 1; } return released; } /** Get the JID which is or will be bound to the connection. * * @param conn a Strophe connection object * * @return a string containing the full JID or NULL if it has not been set * * @ingroup Connections */ const char *xmpp_conn_get_jid(const xmpp_conn_t * const conn) { return conn->jid; } /** * Get the JID discovered during binding time. * * This JID will contain the resource used by the current connection. * This is useful in the case where a resource was not specified for * binding. * * @param conn a Strophe connection object. * * @return a string containing the full JID or NULL if it's not been discovered * * @ingroup Connections */ const char *xmpp_conn_get_bound_jid(const xmpp_conn_t * const conn) { return conn->bound_jid; } /** Set the JID of the user that will be bound to the connection. * If any JID was previously set, it will be discarded. This should not be * be used after a connection is created. The function will make a copy of * the JID string. If the supllied JID is missing the node, SASL * ANONYMOUS authentication will be used. * * @param conn a Strophe connection object * @param jid a full or bare JID * * @ingroup Connections */ void xmpp_conn_set_jid(xmpp_conn_t * const conn, const char * const jid) { if (conn->jid) xmpp_free(conn->ctx, conn->jid); conn->jid = xmpp_strdup(conn->ctx, jid); } /** Get the password used for authentication of a connection. * * @param conn a Strophe connection object * * @return a string containing the password or NULL if it has not been set * * @ingroup Connections */ const char *xmpp_conn_get_pass(const xmpp_conn_t * const conn) { return conn->pass; } /** Set the password used to authenticate the connection. * If any password was previously set, it will be discarded. The function * will make a copy of the password string. * * @param conn a Strophe connection object * @param pass the password * * @ingroup Connections */ void xmpp_conn_set_pass(xmpp_conn_t * const conn, const char * const pass) { if (conn->pass) xmpp_free(conn->ctx, conn->pass); conn->pass = xmpp_strdup(conn->ctx, pass); } /** Get the strophe context that the connection is associated with. * @param conn a Strophe connection object * * @return a Strophe context * * @ingroup Connections */ xmpp_ctx_t* xmpp_conn_get_context(xmpp_conn_t * const conn) { return conn->ctx; } /** Initiate a connection to the XMPP server. * This function returns immediately after starting the connection * process to the XMPP server, and notifiations of connection state changes * will be sent to the callback function. The domain and port to connect to * are usually determined by an SRV lookup for the xmpp-client service at * the domain specified in the JID. If SRV lookup fails, altdomain and * altport will be used instead if specified. * * @param conn a Strophe connection object * @param altdomain a string with domain to use if SRV lookup fails. If this * is NULL, the domain from the JID will be used. * @param altport an integer port number to use if SRV lookup fails. If this * is 0, the default port (5222) will be assumed. * @param callback a xmpp_conn_handler callback function that will receive * notifications of connection status * @param userdata an opaque data pointer that will be passed to the callback * * @return 0 on success and -1 on an error * * @ingroup Connections */ int xmpp_connect_client(xmpp_conn_t * const conn, const char * const altdomain, unsigned short altport, xmpp_conn_handler callback, void * const userdata) { char connectdomain[2048]; int connectport; const char * domain; conn->type = XMPP_CLIENT; conn->domain = xmpp_jid_domain(conn->ctx, conn->jid); if (!conn->domain) return -1; if (altdomain) { xmpp_debug(conn->ctx, "xmpp", "Connecting via altdomain."); strcpy(connectdomain, altdomain); connectport = altport ? altport : 5222; } else if (!sock_srv_lookup("xmpp-client", "tcp", conn->domain, connectdomain, 2048, &connectport)) { xmpp_debug(conn->ctx, "xmpp", "SRV lookup failed."); if (!altdomain) domain = conn->domain; else domain = altdomain; xmpp_debug(conn->ctx, "xmpp", "Using alternate domain %s, port %d", altdomain, altport); strcpy(connectdomain, domain); connectport = altport ? altport : 5222; } conn->sock = sock_connect(connectdomain, connectport); xmpp_debug(conn->ctx, "xmpp", "sock_connect to %s:%d returned %d", connectdomain, connectport, conn->sock); if (conn->sock == -1) return -1; /* setup handler */ conn->conn_handler = callback; conn->userdata = userdata; /* FIXME: it could happen that the connect returns immediately as * successful, though this is pretty unlikely. This would be a little * hard to fix, since we'd have to detect and fire off the callback * from within the event loop */ conn->state = XMPP_STATE_CONNECTING; conn->timeout_stamp = time_stamp(); xmpp_debug(conn->ctx, "xmpp", "attempting to connect to %s", connectdomain); return 0; } /** Initiate a component connection to server. * This function returns immediately after starting the connection * process to the XMPP server, and notifiations of connection state changes * will be sent to the internal callback function that will set up handler * for the component handshake as defined in XEP-0114. * The domain and port to connect to must be provided in this case as the JID * provided to the call serves as component identifier to the server and is * not subject to DNS resolution. * * @param conn a Strophe connection object * @param server a string with domain to use directly as the domain can't be * extracted from the component name/JID. If this is not set, the call * will fail. * @param port an integer port number to use to connect to server expecting * an external component. If this is 0, the port 5347 will be assumed. * @param callback a xmpp_conn_handler callback function that will receive * notifications of connection status * @param userdata an opaque data pointer that will be passed to the callback * * @return 0 on success and -1 on an error * * @ingroup Connections */ int xmpp_connect_component(xmpp_conn_t * const conn, const char * const server, unsigned short port, xmpp_conn_handler callback, void * const userdata) { int connectport; conn->type = XMPP_COMPONENT; /* JID serves as an identificator here and will be used as "to" attribute of the stream */ conn->domain = xmpp_strdup(conn->ctx, conn->jid); /* The server domain, jid and password MUST be specified. */ if (!(server && conn->jid && conn->pass)) return -1; connectport = port ? port : 5347; xmpp_debug(conn->ctx, "xmpp", "Connecting via %s", server); conn->sock = sock_connect(server, connectport); xmpp_debug(conn->ctx, "xmpp", "sock_connect to %s:%d returned %d", server, connectport, conn->sock); if (conn->sock == -1) return -1; /* XEP-0114 does not support TLS */ conn->tls_disabled = 1; /* setup handler */ conn->conn_handler = callback; conn->userdata = userdata; conn_prepare_reset(conn, auth_handle_component_open); /* FIXME: it could happen that the connect returns immediately as * successful, though this is pretty unlikely. This would be a little * hard to fix, since we'd have to detect and fire off the callback * from within the event loop */ conn->state = XMPP_STATE_CONNECTING; conn->timeout_stamp = time_stamp(); xmpp_debug(conn->ctx, "xmpp", "attempting to connect to %s", server); return 0; } /** Cleanly disconnect the connection. * This function is only called by the stream parser when * is received, and it not intended to be called by code outside of Strophe. * * @param conn a Strophe connection object */ void conn_disconnect_clean(xmpp_conn_t * const conn) { /* remove the timed handler */ xmpp_timed_handler_delete(conn, _disconnect_cleanup); conn_disconnect(conn); } /** Disconnect from the XMPP server. * This function immediately disconnects from the XMPP server, and should * not be used outside of the Strophe library. * * @param conn a Strophe connection object */ void conn_disconnect(xmpp_conn_t * const conn) { xmpp_debug(conn->ctx, "xmpp", "Closing socket."); conn->state = XMPP_STATE_DISCONNECTED; if (conn->tls) { tls_stop(conn->tls); tls_free(conn->tls); conn->tls = NULL; } sock_close(conn->sock); /* fire off connection handler */ conn->conn_handler(conn, XMPP_CONN_DISCONNECT, conn->error, conn->stream_error, conn->userdata); } /* prepares a parser reset. this is called from handlers. we can't * reset the parser immediately as it is not re-entrant. */ void conn_prepare_reset(xmpp_conn_t * const conn, xmpp_open_handler handler) { conn->reset_parser = 1; conn->open_handler = handler; } /* reset the parser */ void conn_parser_reset(xmpp_conn_t * const conn) { conn->reset_parser = 0; parser_reset(conn->parser); } /* timed handler for cleanup if normal disconnect procedure takes too long */ static int _disconnect_cleanup(xmpp_conn_t * const conn, void * const userdata) { xmpp_debug(conn->ctx, "xmpp", "disconnection forced by cleanup timeout"); conn_disconnect(conn); return 0; } /** Initiate termination of the connection to the XMPP server. * This function starts the disconnection sequence by sending * to the XMPP server. This function will do nothing * if the connection state is CONNECTING or CONNECTED. * * @param conn a Strophe connection object * * @ingroup Connections */ void xmpp_disconnect(xmpp_conn_t * const conn) { if (conn->state != XMPP_STATE_CONNECTING && conn->state != XMPP_STATE_CONNECTED) return; /* close the stream */ xmpp_send_raw_string(conn, ""); /* setup timed handler in case disconnect takes too long */ handler_add_timed(conn, _disconnect_cleanup, DISCONNECT_TIMEOUT, NULL); } /** Send a raw string to the XMPP server. * This function is a convenience function to send raw string data to the * XMPP server. It is used by Strophe to send short messages instead of * building up an XML stanza with DOM methods. This should be used with care * as it does not validate the data; invalid data may result in immediate * stream termination by the XMPP server. * * @param conn a Strophe connection object * @param fmt a printf-style format string followed by a variable list of * arguments to format */ void xmpp_send_raw_string(xmpp_conn_t * const conn, const char * const fmt, ...) { va_list ap; size_t len; char buf[1024]; /* small buffer for common case */ char *bigbuf; va_start(ap, fmt); len = xmpp_vsnprintf(buf, 1024, fmt, ap); va_end(ap); if (len >= 1024) { /* we need more space for this data, so we allocate a big * enough buffer and print to that */ len++; /* account for trailing \0 */ bigbuf = xmpp_alloc(conn->ctx, len); if (!bigbuf) { xmpp_debug(conn->ctx, "xmpp", "Could not allocate memory for send_raw_string"); return; } va_start(ap, fmt); xmpp_vsnprintf(bigbuf, len, fmt, ap); va_end(ap); xmpp_debug(conn->ctx, "conn", "SENT: %s", bigbuf); /* len - 1 so we don't send trailing \0 */ xmpp_send_raw(conn, bigbuf, len - 1); xmpp_free(conn->ctx, bigbuf); } else { xmpp_debug(conn->ctx, "conn", "SENT: %s", buf); xmpp_send_raw(conn, buf, len); } } /** Send raw bytes to the XMPP server. * This function is a convenience function to send raw bytes to the * XMPP server. It is usedly primarly by xmpp_send_raw_string. This * function should be used with care as it does not validate the bytes and * invalid data may result in stream termination by the XMPP server. * * @param conn a Strophe connection object * @param data a buffer of raw bytes * @param len the length of the data in the buffer */ void xmpp_send_raw(xmpp_conn_t * const conn, const char * const data, const size_t len) { xmpp_send_queue_t *item; if (conn->state != XMPP_STATE_CONNECTED) return; /* create send queue item for queue */ item = xmpp_alloc(conn->ctx, sizeof(xmpp_send_queue_t)); if (!item) return; item->data = xmpp_alloc(conn->ctx, len); if (!item->data) { xmpp_free(conn->ctx, item); return; } memcpy(item->data, data, len); item->len = len; item->next = NULL; item->written = 0; /* add item to the send queue */ if (!conn->send_queue_tail) { /* first item, set head and tail */ conn->send_queue_head = item; conn->send_queue_tail = item; } else { /* add to the tail */ conn->send_queue_tail->next = item; conn->send_queue_tail = item; } conn->send_queue_len++; } /** Send an XML stanza to the XMPP server. * This is the main way to send data to the XMPP server. The function will * terminate without action if the connection state is not CONNECTED. * * @param conn a Strophe connection object * @param stanza a Strophe stanza object * * @ingroup Connections */ void xmpp_send(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza) { char *buf; size_t len; int ret; if (conn->state == XMPP_STATE_CONNECTED) { if ((ret = xmpp_stanza_to_text(stanza, &buf, &len)) == 0) { xmpp_send_raw(conn, buf, len); xmpp_debug(conn->ctx, "conn", "SENT: %s", buf); xmpp_free(conn->ctx, buf); } } } /** Send the opening <stream:stream> tag to the server. * This function is used by Strophe to begin an XMPP stream. It should * not be used outside of the library. * * @param conn a Strophe connection object */ void conn_open_stream(xmpp_conn_t * const conn) { xmpp_send_raw_string(conn, "" \ "", conn->domain, conn->lang, conn->type == XMPP_CLIENT ? XMPP_NS_CLIENT : XMPP_NS_COMPONENT, XMPP_NS_STREAMS); } /** Disable TLS for this connection, called by users of the library. * Occasionally a server will be misconfigured to send the starttls * feature, but wil not support the handshake. * * @param conn a Strophe connection object */ void xmpp_conn_disable_tls(xmpp_conn_t * const conn) { conn->tls_disabled = 1; } static void _log_open_tag(xmpp_conn_t *conn, char **attrs) { char buf[4096]; size_t pos; int len; int i; char *attr; if (!attrs) return; pos = 0; len = xmpp_snprintf(buf, 4096, "ctx, attrs[i]); len = xmpp_snprintf(&buf[pos], 4096 - pos, " %s='%s'", attr, attrs[i+1]); xmpp_free(conn->ctx, attr); if (len < 0) return; pos += len; } len = xmpp_snprintf(&buf[pos], 4096 - pos, ">"); if (len < 0) return; xmpp_debug(conn->ctx, "xmpp", "RECV: %s", buf); } static char *_get_stream_attribute(char **attrs, char *name) { int i; if (!attrs) return NULL; for (i = 0; attrs[i]; i += 2) if (strcmp(name, attrs[i]) == 0) return attrs[i+1]; return NULL; } static void _handle_stream_start(char *name, char **attrs, void * const userdata) { xmpp_conn_t *conn = (xmpp_conn_t *)userdata; char *id; if (strcmp(name, "stream")) { printf("name = %s\n", name); xmpp_error(conn->ctx, "conn", "Server did not open valid stream."); conn_disconnect(conn); } else { _log_open_tag(conn, attrs); if (conn->stream_id) xmpp_free(conn->ctx, conn->stream_id); id = _get_stream_attribute(attrs, "id"); if (id) conn->stream_id = xmpp_strdup(conn->ctx, id); if (!conn->stream_id) { xmpp_error(conn->ctx, "conn", "Memory allocation failed."); conn_disconnect(conn); } } /* call stream open handler */ conn->open_handler(conn); } static void _handle_stream_end(char *name, void * const userdata) { xmpp_conn_t *conn = (xmpp_conn_t *)userdata; /* stream is over */ xmpp_debug(conn->ctx, "xmpp", "RECV: "); conn_disconnect_clean(conn); } static void _handle_stream_stanza(xmpp_stanza_t *stanza, void * const userdata) { xmpp_conn_t *conn = (xmpp_conn_t *)userdata; char *buf; size_t len; if (xmpp_stanza_to_text(stanza, &buf, &len) == 0) { xmpp_debug(conn->ctx, "xmpp", "RECV: %s", buf); xmpp_free(conn->ctx, buf); } handler_fire_stanza(conn, stanza); } libstrophe-0.8.8/src/ctx.c000066400000000000000000000300241256471717200154460ustar00rootroot00000000000000/* ctx.c ** strophe XMPP client library -- run-time context implementation ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Runtime contexts, library initialization and shutdown, and versioning. */ /** @defgroup Context Context objects * These functions create and manipulate Strophe context objects. * * In order to support usage in a variety of environments, the * Strophe library uses a runtime context object. This object * contains the information on how to do memory allocation and * logging. This allows the user to control how memory is allocated * and what do to with log messages. * * These issues do not affect programs in the common case, but many * environments require special treatment. Abstracting these into a runtime * context object makes it easy to use Strophe on embedded platforms. * * Objects in Strophe are reference counted to ease memory management issues, * but the context objects are not. */ /** @defgroup Init Initialization, shutdown, and versioning * These functions initialize and shutdown the library, and also allow * for API version checking. Failure to properly call these functions may * result in strange (and platform dependent) behavior. * * Specifically, the socket library on Win32 platforms must be initialized * before use (although this is not the case on POSIX systems). The TLS * subsystem must also seed the random number generator. */ #include #include #include #include #include "strophe.h" #include "common.h" #include "util.h" /** Initialize the Strophe library. * This function initializes subcomponents of the Strophe library and must * be called for Strophe to operate correctly. * * @ingroup Init */ void xmpp_initialize(void) { sock_initialize(); tls_initialize(); } /** Shutdown the Strophe library. * * @ingroup Init */ void xmpp_shutdown(void) { tls_shutdown(); sock_shutdown(); } /* version information */ #ifndef LIBXMPP_VERSION_MAJOR /** @def LIBXMPP_VERSION_MAJOR * The major version number of Strophe. */ #define LIBXMPP_VERSION_MAJOR (0) #endif #ifndef LIBXMPP_VERSION_MINOR /** @def LIBXMPP_VERSION_MINOR * The minor version number of Strophe. */ #define LIBXMPP_VERSION_MINOR (0) #endif /** Check that Strophe supports a specific API version. * * @param major the major version number * @param minor the minor version number * * @return TRUE if the version is supported and FALSE if unsupported * * @ingroup Init */ int xmpp_version_check(int major, int minor) { return (major == LIBXMPP_VERSION_MAJOR) && (minor >= LIBXMPP_VERSION_MINOR); } /* We define the global default allocator, logger, and context here. */ /* Wrap stdlib routines malloc, free, and realloc for default memory * management. */ static void *_malloc(const size_t size, void * const userdata) { return malloc(size); } static void _free(void *p, void * const userdata) { free(p); } static void *_realloc(void *p, const size_t size, void * const userdata) { return realloc(p, size); } /* default memory function map */ static xmpp_mem_t xmpp_default_mem = { _malloc, /* use the thinly wrapped stdlib routines by default */ _free, _realloc, NULL }; /* log levels and names */ static const char * const _xmpp_log_level_name[4] = {"DEBUG", "INFO", "WARN", "ERROR"}; static const xmpp_log_level_t _xmpp_default_logger_levels[] = {XMPP_LEVEL_DEBUG, XMPP_LEVEL_INFO, XMPP_LEVEL_WARN, XMPP_LEVEL_ERROR}; /** Log a message. * The default logger writes to stderr. * * @param userdata the opaque data used by the default logger. This contains * the filter level in the default logger. * @param level the level to log at * @param area the area the log message is for * @param msg the log message */ void xmpp_default_logger(void * const userdata, const xmpp_log_level_t level, const char * const area, const char * const msg) { xmpp_log_level_t filter_level = * (xmpp_log_level_t*)userdata; if (level >= filter_level) fprintf(stderr, "%s %s %s\n", area, _xmpp_log_level_name[level], msg); } static const xmpp_log_t _xmpp_default_loggers[] = { {&xmpp_default_logger, (void*)&_xmpp_default_logger_levels[XMPP_LEVEL_DEBUG]}, {&xmpp_default_logger, (void*)&_xmpp_default_logger_levels[XMPP_LEVEL_INFO]}, {&xmpp_default_logger, (void*)&_xmpp_default_logger_levels[XMPP_LEVEL_WARN]}, {&xmpp_default_logger, (void*)&_xmpp_default_logger_levels[XMPP_LEVEL_ERROR]} }; /** Get a default logger with filtering. * The default logger provides a basic logging setup which writes log * messages to stderr. Only messages where level is greater than or * equal to the filter level will be logged. * * @param level the highest level the logger will log at * * @return the log structure for the given level * * @ingroup Context */ xmpp_log_t *xmpp_get_default_logger(xmpp_log_level_t level) { /* clamp to the known range */ if (level > XMPP_LEVEL_ERROR) level = XMPP_LEVEL_ERROR; if (level < XMPP_LEVEL_DEBUG) level = XMPP_LEVEL_DEBUG; return (xmpp_log_t*)&_xmpp_default_loggers[level]; } static xmpp_log_t xmpp_default_log = { NULL, NULL }; /* convenience functions for accessing the context */ /** Allocate memory in a Strophe context. * All Strophe functions will use this to allocate memory. * * @param ctx a Strophe context object * @param size the number of bytes to allocate * * @return a pointer to the allocated memory or NULL on an error */ void *xmpp_alloc(const xmpp_ctx_t * const ctx, const size_t size) { return ctx->mem->alloc(size, ctx->mem->userdata); } /** Free memory in a Strophe context. * All Strophe functions will use this to free allocated memory. * * @param ctx a Strophe context object * @param p a pointer referencing memory to be freed */ void xmpp_free(const xmpp_ctx_t * const ctx, void *p) { ctx->mem->free(p, ctx->mem->userdata); } /** Reallocate memory in a Strophe context. * All Strophe functions will use this to reallocate memory. * * @param ctx a Strophe context object * @param p a pointer to previously allocated memory * @param size the new size in bytes to allocate * * @return a pointer to the reallocated memory or NULL on an error */ void *xmpp_realloc(const xmpp_ctx_t * const ctx, void *p, const size_t size) { return ctx->mem->realloc(p, size, ctx->mem->userdata); } /** Write a log message to the logger. * Write a log message to the logger for the context for the specified * level and area. This function takes a printf-style format string and a * variable argument list (in va_list) format. This function is not meant * to be called directly, but is used via xmpp_error, xmpp_warn, xmpp_info, * and xmpp_debug. * * @param ctx a Strophe context object * @param level the level at which to log * @param area the area to log for * @param fmt a printf-style format string for the message * @param ap variable argument list supplied for the format string */ void xmpp_log(const xmpp_ctx_t * const ctx, const xmpp_log_level_t level, const char * const area, const char * const fmt, va_list ap) { int oldret, ret; char smbuf[1024]; char *buf; va_list copy; va_copy(copy, ap); ret = xmpp_vsnprintf(smbuf, sizeof(smbuf), fmt, ap); if (ret >= (int)sizeof(smbuf)) { buf = (char *)xmpp_alloc(ctx, ret + 1); if (!buf) { buf = NULL; xmpp_error(ctx, "log", "Failed allocating memory for log message."); va_end(copy); return; } oldret = ret; ret = xmpp_vsnprintf(buf, ret + 1, fmt, copy); if (ret > oldret) { xmpp_error(ctx, "log", "Unexpected error"); xmpp_free(ctx, buf); va_end(copy); return; } } else { buf = smbuf; } va_end(copy); if (ctx->log->handler) ctx->log->handler(ctx->log->userdata, level, area, buf); if (buf != smbuf) xmpp_free(ctx, buf); } /** Write to the log at the ERROR level. * This is a convenience function for writing to the log at the * ERROR level. It takes a printf-style format string followed by a * variable list of arguments for formatting. * * @param ctx a Strophe context object * @param area the area to log for * @param fmt a printf-style format string followed by a variable list of * arguments to format */ void xmpp_error(const xmpp_ctx_t * const ctx, const char * const area, const char * const fmt, ...) { va_list ap; va_start(ap, fmt); xmpp_log(ctx, XMPP_LEVEL_ERROR, area, fmt, ap); va_end(ap); } /** Write to the log at the WARN level. * This is a convenience function for writing to the log at the WARN level. * It takes a printf-style format string followed by a variable list of * arguments for formatting. * * @param ctx a Strophe context object * @param area the area to log for * @param fmt a printf-style format string followed by a variable list of * arguments to format */ void xmpp_warn(const xmpp_ctx_t * const ctx, const char * const area, const char * const fmt, ...) { va_list ap; va_start(ap, fmt); xmpp_log(ctx, XMPP_LEVEL_WARN, area, fmt, ap); va_end(ap); } /** Write to the log at the INFO level. * This is a convenience function for writing to the log at the INFO level. * It takes a printf-style format string followed by a variable list of * arguments for formatting. * * @param ctx a Strophe context object * @param area the area to log for * @param fmt a printf-style format string followed by a variable list of * arguments to format */ void xmpp_info(const xmpp_ctx_t * const ctx, const char * const area, const char * const fmt, ...) { va_list ap; va_start(ap, fmt); xmpp_log(ctx, XMPP_LEVEL_INFO, area, fmt, ap); va_end(ap); } /** Write to the log at the DEBUG level. * This is a convenience function for writing to the log at the DEBUG level. * It takes a printf-style format string followed by a variable list of * arguments for formatting. * * @param ctx a Strophe context object * @param area the area to log for * @param fmt a printf-style format string followed by a variable list of * arguments to format */ void xmpp_debug(const xmpp_ctx_t * const ctx, const char * const area, const char * const fmt, ...) { va_list ap; va_start(ap, fmt); xmpp_log(ctx, XMPP_LEVEL_DEBUG, area, fmt, ap); va_end(ap); } /** Create and initialize a Strophe context object. * If mem is NULL, a default allocation setup will be used which * wraps malloc(), free(), and realloc() from the standard library. * If log is NULL, a default logger will be used which does no * logging. Basic filtered logging to stderr can be done with the * xmpp_get_default_logger() convenience function. * * @param mem a pointer to an xmpp_mem_t structure or NULL * @param log a pointer to an xmpp_log_t structure or NULL * * @return the allocated Strophe context object or NULL on an error * * @ingroup Context */ xmpp_ctx_t *xmpp_ctx_new(const xmpp_mem_t * const mem, const xmpp_log_t * const log) { xmpp_ctx_t *ctx = NULL; if (mem == NULL) ctx = xmpp_default_mem.alloc(sizeof(xmpp_ctx_t), NULL); else ctx = mem->alloc(sizeof(xmpp_ctx_t), mem->userdata); if (ctx != NULL) { if (mem != NULL) ctx->mem = mem; else ctx->mem = &xmpp_default_mem; if (log == NULL) ctx->log = &xmpp_default_log; else ctx->log = log; ctx->connlist = NULL; ctx->loop_status = XMPP_LOOP_NOTSTARTED; } return ctx; } /** Free a Strophe context object that is no longer in use. * * @param ctx a Strophe context object * * @ingroup Context */ void xmpp_ctx_free(xmpp_ctx_t * const ctx) { /* mem and log are owned by their suppliers */ xmpp_free(ctx, ctx); /* pull the hole in after us */ } libstrophe-0.8.8/src/event.c000066400000000000000000000221301256471717200157700ustar00rootroot00000000000000/* event.c ** strophe XMPP client library -- event loop and management ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Event loop and management. */ /** @defgroup EventLoop Event loop * These functions manage the Strophe event loop. * * Simple tools can use xmpp_run() and xmpp_stop() to manage the life * cycle of the program. A common idiom is to set up a few initial * event handers, call xmpp_run(), and then respond and react to * events as they come in. At some point, one of the handlers will * call xmpp_stop() to quit the event loop which leads to the program * terminating. * * More complex programs will have their own event loops, and should * ensure that xmpp_run_once() is called regularly from there. For * example, a GUI program will already include an event loop to * process UI events from users, and xmpp_run_once() would be called * from an idle function. */ #include #include #include #ifndef _WIN32 #include #include #include #define _sleep(x) usleep(x*1000) #else #include #define ETIMEDOUT WSAETIMEDOUT #define ECONNRESET WSAECONNRESET #define ECONNABORTED WSAECONNABORTED #define _sleep(x) Sleep(x) #endif #include #include "common.h" #include "parser.h" #ifndef DEFAULT_TIMEOUT /** @def DEFAULT_TIMEOUT * The default timeout in milliseconds for the event loop. * This is set to 1 millisecond. */ #define DEFAULT_TIMEOUT 1 #endif /** Run the event loop once. * This function will run send any data that has been queued by * xmpp_send and related functions and run through the Strophe even * loop a single time, and will not wait more than timeout * milliseconds for events. This is provided to support integration * with event loops outside the library, and if used, should be * called regularly to achieve low latency event handling. * * @param ctx a Strophe context object * @param timeout time to wait for events in milliseconds * * @ingroup EventLoop */ void xmpp_run_once(xmpp_ctx_t *ctx, const unsigned long timeout) { xmpp_connlist_t *connitem; xmpp_conn_t *conn; fd_set rfds, wfds; sock_t max = 0; int ret; struct timeval tv; xmpp_send_queue_t *sq, *tsq; int towrite; char buf[4096]; uint64_t next; long usec; int tls_read_bytes = 0; if (ctx->loop_status == XMPP_LOOP_QUIT) return; ctx->loop_status = XMPP_LOOP_RUNNING; /* send queued data */ connitem = ctx->connlist; while (connitem) { conn = connitem->conn; if (conn->state != XMPP_STATE_CONNECTED) { connitem = connitem->next; continue; } /* if we're running tls, there may be some remaining data waiting to * be sent, so push that out */ if (conn->tls) { ret = tls_clear_pending_write(conn->tls); if (ret < 0 && !tls_is_recoverable(tls_error(conn->tls))) { /* an error occured */ xmpp_debug(ctx, "xmpp", "Send error occured, disconnecting."); conn->error = ECONNABORTED; conn_disconnect(conn); } } /* write all data from the send queue to the socket */ sq = conn->send_queue_head; while (sq) { towrite = sq->len - sq->written; if (conn->tls) { ret = tls_write(conn->tls, &sq->data[sq->written], towrite); if (ret < 0 && !tls_is_recoverable(tls_error(conn->tls))) { /* an error occured */ conn->error = tls_error(conn->tls); break; } else if (ret < towrite) { /* not all data could be sent now */ if (ret >= 0) sq->written += ret; break; } } else { ret = sock_write(conn->sock, &sq->data[sq->written], towrite); if (ret < 0 && !sock_is_recoverable(sock_error())) { /* an error occured */ conn->error = sock_error(); break; } else if (ret < towrite) { /* not all data could be sent now */ if (ret >= 0) sq->written += ret; break; } } /* all data for this queue item written, delete and move on */ xmpp_free(ctx, sq->data); tsq = sq; sq = sq->next; xmpp_free(ctx, tsq); /* pop the top item */ conn->send_queue_head = sq; /* if we've sent everything update the tail */ if (!sq) conn->send_queue_tail = NULL; } /* tear down connection on error */ if (conn->error) { /* FIXME: need to tear down send queues and random other things * maybe this should be abstracted */ xmpp_debug(ctx, "xmpp", "Send error occured, disconnecting."); conn->error = ECONNABORTED; conn_disconnect(conn); } connitem = connitem->next; } /* reset parsers if needed */ for (connitem = ctx->connlist; connitem; connitem = connitem->next) { if (connitem->conn->reset_parser) conn_parser_reset(connitem->conn); } /* fire any ready timed handlers, then make sure we don't wait past the time when timed handlers need to be called */ next = handler_fire_timed(ctx); usec = ((next < timeout) ? next : timeout) * 1000; tv.tv_sec = usec / 1000000; tv.tv_usec = usec % 1000000; FD_ZERO(&rfds); FD_ZERO(&wfds); /* find events to watch */ connitem = ctx->connlist; while (connitem) { conn = connitem->conn; switch (conn->state) { case XMPP_STATE_CONNECTING: /* connect has been called and we're waiting for it to complete */ /* connection will give us write or error events */ /* make sure the timeout hasn't expired */ if (time_elapsed(conn->timeout_stamp, time_stamp()) <= conn->connect_timeout) FD_SET(conn->sock, &wfds); else { conn->error = ETIMEDOUT; xmpp_info(ctx, "xmpp", "Connection attempt timed out."); conn_disconnect(conn); } break; case XMPP_STATE_CONNECTED: FD_SET(conn->sock, &rfds); break; case XMPP_STATE_DISCONNECTED: /* do nothing */ default: break; } /* Check if there is something in the SSL buffer. */ if (conn->tls) { tls_read_bytes += tls_pending(conn->tls); } if (conn->state != XMPP_STATE_DISCONNECTED && conn->sock > max) max = conn->sock; connitem = connitem->next; } /* check for events */ if (max > 0) ret = select(max + 1, &rfds, &wfds, NULL, &tv); else { if (timeout > 0) _sleep(timeout); return; } /* select errored */ if (ret < 0) { if (!sock_is_recoverable(sock_error())) xmpp_error(ctx, "xmpp", "event watcher internal error %d", sock_error()); return; } /* no events happened */ if (ret == 0 && tls_read_bytes == 0) return; /* process events */ connitem = ctx->connlist; while (connitem) { conn = connitem->conn; switch (conn->state) { case XMPP_STATE_CONNECTING: if (FD_ISSET(conn->sock, &wfds)) { /* connection complete */ /* check for error */ if (sock_connect_error(conn->sock) != 0) { /* connection failed */ xmpp_debug(ctx, "xmpp", "connection failed"); conn_disconnect(conn); break; } conn->state = XMPP_STATE_CONNECTED; xmpp_debug(ctx, "xmpp", "connection successful"); /* send stream init */ conn_open_stream(conn); } break; case XMPP_STATE_CONNECTED: if (FD_ISSET(conn->sock, &rfds) || (conn->tls && tls_pending(conn->tls))) { if (conn->tls) { ret = tls_read(conn->tls, buf, 4096); } else { ret = sock_read(conn->sock, buf, 4096); } if (ret > 0) { ret = parser_feed(conn->parser, buf, ret); if (!ret) { /* parse error, we need to shut down */ /* FIXME */ xmpp_debug(ctx, "xmpp", "parse error, disconnecting"); conn_disconnect(conn); } } else { if (conn->tls) { if (!tls_is_recoverable(tls_error(conn->tls))) { xmpp_debug(ctx, "xmpp", "Unrecoverable TLS error, %d.", tls_error(conn->tls)); conn->error = tls_error(conn->tls); conn_disconnect(conn); } } else { /* return of 0 means socket closed by server */ xmpp_debug(ctx, "xmpp", "Socket closed by remote host."); conn->error = ECONNRESET; conn_disconnect(conn); } } } break; case XMPP_STATE_DISCONNECTED: /* do nothing */ default: break; } connitem = connitem->next; } /* fire any ready handlers */ handler_fire_timed(ctx); } /** Start the event loop. * This function continuously calls xmpp_run_once and does not return * until xmpp_stop has been called. * * @param ctx a Strophe context object * * @ingroup EventLoop */ void xmpp_run(xmpp_ctx_t *ctx) { if (ctx->loop_status != XMPP_LOOP_NOTSTARTED) return; ctx->loop_status = XMPP_LOOP_RUNNING; while (ctx->loop_status == XMPP_LOOP_RUNNING) { xmpp_run_once(ctx, DEFAULT_TIMEOUT); } xmpp_debug(ctx, "event", "Event loop completed."); } /** Stop the event loop. * This will stop the event loop after the current iteration and cause * xmpp_run to exit. * * @param ctx a Strophe context object * * @ingroup EventLoop */ void xmpp_stop(xmpp_ctx_t *ctx) { xmpp_debug(ctx, "event", "Stopping event loop."); if (ctx->loop_status == XMPP_LOOP_RUNNING) ctx->loop_status = XMPP_LOOP_QUIT; } libstrophe-0.8.8/src/handler.c000066400000000000000000000372431256471717200162770ustar00rootroot00000000000000/* handler.c ** strophe XMPP client library -- event handler management ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Event handler management. */ /** @defgroup Handlers Stanza and timed event handlers */ #include #include #include #include "strophe.h" #include "common.h" #include "ostypes.h" /** Fire off all stanza handlers that match. * This function is called internally by the event loop whenever stanzas * are received from the XMPP server. * * @param conn a Strophe connection object * @param stanza a Strophe stanza object */ void handler_fire_stanza(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza) { xmpp_handlist_t *item, *prev; char *id, *ns, *name, *type; /* call id handlers */ id = xmpp_stanza_get_id(stanza); if (id) { prev = NULL; item = (xmpp_handlist_t *)hash_get(conn->id_handlers, id); while (item) { xmpp_handlist_t *next = item->next; if (item->user_handler && !conn->authenticated) { item = next; continue; } if (!((xmpp_handler)(item->handler))(conn, stanza, item->userdata)) { /* handler is one-shot, so delete it */ if (prev) prev->next = next; else { hash_drop(conn->id_handlers, id); hash_add(conn->id_handlers, id, next); } xmpp_free(conn->ctx, item->id); xmpp_free(conn->ctx, item); item = NULL; } if (item) prev = item; item = next; } } /* call handlers */ ns = xmpp_stanza_get_ns(stanza); name = xmpp_stanza_get_name(stanza); type = xmpp_stanza_get_type(stanza); /* enable all added handlers */ for (item = conn->handlers; item; item = item->next) item->enabled = 1; prev = NULL; item = conn->handlers; while (item) { /* skip newly added handlers */ if (!item->enabled) { prev = item; item = item->next; continue; } /* don't call user handlers until authentication succeeds */ if (item->user_handler && !conn->authenticated) { prev = item; item = item->next; continue; } if ((!item->ns || (ns && strcmp(ns, item->ns) == 0) || xmpp_stanza_get_child_by_ns(stanza, item->ns)) && (!item->name || (name && strcmp(name, item->name) == 0)) && (!item->type || (type && strcmp(type, item->type) == 0))) if (!((xmpp_handler)(item->handler))(conn, stanza, item->userdata)) { /* handler is one-shot, so delete it */ if (prev) prev->next = item->next; else conn->handlers = item->next; if (item->ns) xmpp_free(conn->ctx, item->ns); if (item->name) xmpp_free(conn->ctx, item->name); if (item->type) xmpp_free(conn->ctx, item->type); xmpp_free(conn->ctx, item); item = NULL; } if (item) { prev = item; item = item->next; } else if (prev) item = prev->next; else item = conn->handlers; } } /** Fire off all timed handlers that are ready. * This function is called internally by the event loop. * * @param ctx a Strophe context object * * @return the time in milliseconds until the next handler will be ready */ uint64_t handler_fire_timed(xmpp_ctx_t * const ctx) { xmpp_connlist_t *connitem; xmpp_handlist_t *handitem, *temp; int ret, fired; uint64_t elapsed, min; min = (uint64_t)(-1); connitem = ctx->connlist; while (connitem) { if (connitem->conn->state != XMPP_STATE_CONNECTED) { connitem = connitem->next; continue; } /* enable all handlers that were added */ for (handitem = connitem->conn->timed_handlers; handitem; handitem = handitem->next) handitem->enabled = 1; handitem = connitem->conn->timed_handlers; while (handitem) { /* skip newly added handlers */ if (!handitem->enabled) { handitem = handitem->next; continue; } /* only fire user handlers after authentication */ if (handitem->user_handler && !connitem->conn->authenticated) { handitem = handitem->next; continue; } fired = 0; elapsed = time_elapsed(handitem->last_stamp, time_stamp()); if (elapsed >= handitem->period) { /* fire! */ fired = 1; handitem->last_stamp = time_stamp(); ret = ((xmpp_timed_handler)handitem->handler)(connitem->conn, handitem->userdata); } else if (min > (handitem->period - elapsed)) min = handitem->period - elapsed; temp = handitem; handitem = handitem->next; /* delete handler if it returned false */ if (fired && !ret) xmpp_timed_handler_delete(connitem->conn, temp->handler); } connitem = connitem->next; } return min; } /** Reset all timed handlers. * This function is called internally when a connection is successful. * * @param conn a Strophe connection object * @param user_only whether to reset all handlers or only user ones */ void handler_reset_timed(xmpp_conn_t *conn, int user_only) { xmpp_handlist_t *handitem; handitem = conn->timed_handlers; while (handitem) { if ((user_only && handitem->user_handler) || !user_only) handitem->last_stamp = time_stamp(); handitem = handitem->next; } } static void _timed_handler_add(xmpp_conn_t * const conn, xmpp_timed_handler handler, const unsigned long period, void * const userdata, const int user_handler) { xmpp_handlist_t *item, *tail; /* check if handler is already in the list */ for (item = conn->timed_handlers; item; item = item->next) { if (item->handler == (void *)handler) break; } if (item) return; /* build new item */ item = xmpp_alloc(conn->ctx, sizeof(xmpp_handlist_t)); if (!item) return; item->user_handler = user_handler; item->handler = (void *)handler; item->userdata = userdata; item->enabled = 0; item->next = NULL; item->period = period; item->last_stamp = time_stamp(); /* append item to list */ if (!conn->timed_handlers) conn->timed_handlers = item; else { tail = conn->timed_handlers; while (tail->next) tail = tail->next; tail->next = item; } } /** Delete a timed handler. * * @param conn a Strophe connection object * @param handler function pointer to the handler * * @ingroup Handlers */ void xmpp_timed_handler_delete(xmpp_conn_t * const conn, xmpp_timed_handler handler) { xmpp_handlist_t *item, *prev; if (!conn->timed_handlers) return; prev = NULL; item = conn->timed_handlers; while (item) { if (item->handler == (void *)handler) break; prev = item; item = item->next; } if (item) { if (prev) prev->next = item->next; else conn->timed_handlers = item->next; xmpp_free(conn->ctx, item); } } static void _id_handler_add(xmpp_conn_t * const conn, xmpp_handler handler, const char * const id, void * const userdata, int user_handler) { xmpp_handlist_t *item, *tail; /* check if handler is already in the list */ item = (xmpp_handlist_t *)hash_get(conn->id_handlers, id); while (item) { if (item->handler == (void *)handler) break; item = item->next; } if (item) return; /* build new item */ item = xmpp_alloc(conn->ctx, sizeof(xmpp_handlist_t)); if (!item) return; item->user_handler = user_handler; item->handler = (void *)handler; item->userdata = userdata; item->enabled = 0; item->next = NULL; item->id = xmpp_strdup(conn->ctx, id); if (!item->id) { xmpp_free(conn->ctx, item); return; } /* put on list in hash table */ tail = (xmpp_handlist_t *)hash_get(conn->id_handlers, id); if (!tail) hash_add(conn->id_handlers, id, item); else { while (tail->next) tail = tail->next; tail->next = item; } } /** Delete an id based stanza handler. * * @param conn a Strophe connection object * @param handler a function pointer to a stanza handler * @param id a string containing the id the handler is for * * @ingroup Handlers */ void xmpp_id_handler_delete(xmpp_conn_t * const conn, xmpp_handler handler, const char * const id) { xmpp_handlist_t *item, *prev; prev = NULL; item = (xmpp_handlist_t *)hash_get(conn->id_handlers, id); if (!item) return; while (item) { if (item->handler == (void *)handler) break; prev = item; item = item->next; } if (item) { if (prev) prev->next = item->next; else { hash_drop(conn->id_handlers, id); hash_add(conn->id_handlers, id, item->next); } xmpp_free(conn->ctx, item->id); xmpp_free(conn->ctx, item); } } /* add a stanza handler */ static void _handler_add(xmpp_conn_t * const conn, xmpp_handler handler, const char * const ns, const char * const name, const char * const type, void * const userdata, int user_handler) { xmpp_handlist_t *item, *tail; /* check if handler already in list */ for (item = conn->handlers; item; item = item->next) { if (item->handler == (void *)handler) break; } if (item) return; /* build new item */ item = (xmpp_handlist_t *)xmpp_alloc(conn->ctx, sizeof(xmpp_handlist_t)); if (!item) return; item->user_handler = user_handler; item->handler = (void *)handler; item->userdata = userdata; item->enabled = 0; item->next = NULL; if (ns) { item->ns = xmpp_strdup(conn->ctx, ns); if (!item->ns) { xmpp_free(conn->ctx, item); return; } } else item->ns = NULL; if (name) { item->name = xmpp_strdup(conn->ctx, name); if (!item->name) { if (item->ns) xmpp_free(conn->ctx, item->ns); xmpp_free(conn->ctx, item); return; } } else item->name = NULL; if (type) { item->type = xmpp_strdup(conn->ctx, type); if (!item->type) { if (item->ns) xmpp_free(conn->ctx, item->ns); if (item->name) xmpp_free(conn->ctx, item->name); xmpp_free(conn->ctx, item); } } else item->type = NULL; /* append to list */ if (!conn->handlers) conn->handlers = item; else { tail = conn->handlers; while (tail->next) tail = tail->next; tail->next = item; } } /** Delete a stanza handler. * * @param conn a Strophe connection object * @param handler a function pointer to a stanza handler * * @ingroup Handlers */ void xmpp_handler_delete(xmpp_conn_t * const conn, xmpp_handler handler) { xmpp_handlist_t *prev, *item; if (!conn->handlers) return; prev = NULL; item = conn->handlers; while (item) { if (item->handler == (void *)handler) break; prev = item; item = item->next; } if (item) { if (prev) prev->next = item->next; else conn->handlers = item->next; if (item->ns) xmpp_free(conn->ctx, item->ns); if (item->name) xmpp_free(conn->ctx, item->name); if (item->type) xmpp_free(conn->ctx, item->type); xmpp_free(conn->ctx, item); } } /** Add a timed handler. * The handler will fire for the first time once the period has elapsed, * and continue firing regularly after that. Strophe will try its best * to fire handlers as close to the period times as it can, but accuracy * will vary depending on the resolution of the event loop. * * If the handler function returns true, it will be kept, and if it * returns false, it will be deleted from the list of handlers. * * @param conn a Strophe connection object * @param handler a function pointer to a timed handler * @param period the time in milliseconds between firings * @param userdata an opaque data pointer that will be passed to the handler * * @ingroup Handlers */ void xmpp_timed_handler_add(xmpp_conn_t * const conn, xmpp_timed_handler handler, const unsigned long period, void * const userdata) { _timed_handler_add(conn, handler, period, userdata, 1); } /** Add a timed system handler. * This function is used to add internal timed handlers and should not be * used outside of the library. * * @param conn a Strophe connection object * @param handler a function pointer to a timed handler * @param period the time in milliseconds between firings * @param userdata an opaque data pointer that will be passed to the handler */ void handler_add_timed(xmpp_conn_t * const conn, xmpp_timed_handler handler, const unsigned long period, void * const userdata) { _timed_handler_add(conn, handler, period, userdata, 0); } /** Add an id based stanza handler. * This function adds a stanza handler for an <iq/> stanza of * type 'result' or 'error' with a specific id attribute. This can * be used to handle responses to specific <iq/>s. * * If the handler function returns true, it will be kept, and if it * returns false, it will be deleted from the list of handlers. * * @param conn a Strophe connection object * @param handler a function pointer to a stanza handler * @param id a string with the id * @param userdata an opaque data pointer that will be passed to the handler * * @ingroup Handlers */ void xmpp_id_handler_add(xmpp_conn_t * const conn, xmpp_handler handler, const char * const id, void * const userdata) { _id_handler_add(conn, handler, id, userdata, 1); } /** Add an id based system stanza handler. * This function is used to add internal id based stanza handlers and should * not be used outside of the library. * * @param conn a Strophe connection object * @param handler a function pointer to a stanza handler * @param id a string with the id * @param userdata an opaque data pointer that will be passed to the handler */ void handler_add_id(xmpp_conn_t * const conn, xmpp_handler handler, const char * const id, void * const userdata) { _id_handler_add(conn, handler, id, userdata, 0); } /** Add a stanza handler. * This function is used to add a stanza handler to a connection. * The handler will be called when the any of the filters match. The * name filter matches to the top level stanza name. The type filter * matches the 'type' attribute of the top level stanza. The ns * filter matches the namespace ('xmlns' attribute) of either the top * level stanza or any of it's immediate children (this allows you do * handle specific <iq/> stanzas based on the <query/> * child namespace. * * If the handler function returns true, it will be kept, and if it * returns false, it will be deleted from the list of handlers. * * @param conn a Strophe connection object * @param handler a function pointer to a stanza handler * @param ns a string with the namespace to match * @param name a string with the stanza name to match * @param type a string with the 'type' attribute to match * @param userdata an opaque data pointer that will be passed to the handler * * @ingroup Handlers */ void xmpp_handler_add(xmpp_conn_t * const conn, xmpp_handler handler, const char * const ns, const char * const name, const char * const type, void * const userdata) { _handler_add(conn, handler, ns, name, type, userdata, 1); } /** Add a system stanza handler. * This function is used to add internal stanza handlers and should * not be used outside of the library. * * @param conn a Strophe connection object * @param handler a function pointer to a stanza handler * @param ns a string with the namespace to match * @param name a string with the stanza name to match * @param type a string with the 'type' attribute value to match * @param userdata an opaque data pointer that will be passed to the handler */ void handler_add(xmpp_conn_t * const conn, xmpp_handler handler, const char * const ns, const char * const name, const char * const type, void * const userdata) { _handler_add(conn, handler, ns, name, type, userdata, 0); } libstrophe-0.8.8/src/hash.c000066400000000000000000000133511256471717200155770ustar00rootroot00000000000000/* hash.c ** strophe XMPP client library -- hash table implementation ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Hash tables. */ #include #include #include "strophe.h" #include "common.h" #include "hash.h" /* private types */ typedef struct _hashentry_t hashentry_t; struct _hashentry_t { hashentry_t *next; char *key; void *value; }; struct _hash_t { unsigned int ref; xmpp_ctx_t *ctx; hash_free_func free; int length; int num_keys; hashentry_t **entries; }; struct _hash_iterator_t { unsigned int ref; hash_t *table; hashentry_t *entry; int index; }; /** allocate and initialize a new hash table */ hash_t *hash_new(xmpp_ctx_t * const ctx, const int size, hash_free_func free) { hash_t *result = NULL; result = xmpp_alloc(ctx, sizeof(hash_t)); if (result != NULL) { result->entries = xmpp_alloc(ctx, size * sizeof(hashentry_t *)); if (result->entries == NULL) { xmpp_free(ctx, result); return NULL; } memset(result->entries, 0, size * sizeof(hashentry_t *)); result->length = size; result->ctx = ctx; result->free = free; result->num_keys = 0; /* give the caller a reference */ result->ref = 1; } return result; } /** obtain a new reference to an existing hash table */ hash_t *hash_clone(hash_t * const table) { table->ref++; return table; } /** release a hash table that is no longer needed */ void hash_release(hash_t * const table) { xmpp_ctx_t *ctx = table->ctx; hashentry_t *entry, *next; int i; if (table->ref > 1) table->ref--; else { for (i = 0; i < table->length; i++) { entry = table->entries[i]; while (entry != NULL) { next = entry->next; xmpp_free(ctx, entry->key); if (table->free) table->free(ctx, entry->value); xmpp_free(ctx, entry); entry = next; } } xmpp_free(ctx, table->entries); xmpp_free(ctx, table); } } /** hash a key for our table lookup */ static int _hash_key(hash_t *table, const char *key) { int hash = 0; int shift = 0; const char *c = key; while (*c != '\0') { /* assume 32 bit ints */ hash ^= ((int)*c++ << shift); shift += 8; if (shift > 24) shift = 0; } return hash % table->length; } /** add a key, value pair to a hash table. * each key can appear only once; the value of any * identical key will be replaced */ int hash_add(hash_t *table, const char * const key, void *data) { xmpp_ctx_t *ctx = table->ctx; hashentry_t *entry = NULL; int index = _hash_key(table, key); /* drop existing entry, if any */ hash_drop(table, key); /* allocate and fill a new entry */ entry = xmpp_alloc(ctx, sizeof(hashentry_t)); if (!entry) return -1; entry->key = xmpp_strdup(ctx, key); if (!entry->key) { xmpp_free(ctx, entry); return -1; } entry->value = data; /* insert ourselves in the linked list */ /* TODO: this leaks duplicate keys */ entry->next = table->entries[index]; table->entries[index] = entry; table->num_keys++; return 0; } /** look up a key in a hash table */ void *hash_get(hash_t *table, const char *key) { hashentry_t *entry; int index = _hash_key(table, key); void *result = NULL; /* look up the hash entry */ entry = table->entries[index]; while (entry != NULL) { /* traverse the linked list looking for the key */ if (!strcmp(key, entry->key)) { /* match */ result = entry->value; return result; } entry = entry->next; } /* no match */ return result; } /** delete a key from a hash table */ int hash_drop(hash_t *table, const char *key) { xmpp_ctx_t *ctx = table->ctx; hashentry_t *entry, *prev; int index = _hash_key(table, key); /* look up the hash entry */ entry = table->entries[index]; prev = NULL; while (entry != NULL) { /* traverse the linked list looking for the key */ if (!strcmp(key, entry->key)) { /* match, remove the entry */ xmpp_free(ctx, entry->key); if (table->free) table->free(ctx, entry->value); if (prev == NULL) { table->entries[index] = entry->next; } else { prev->next = entry->next; } xmpp_free(ctx, entry); table->num_keys--; return 0; } prev = entry; entry = entry->next; } /* no match */ return -1; } int hash_num_keys(hash_t *table) { return table->num_keys; } /** allocate and initialize a new iterator */ hash_iterator_t *hash_iter_new(hash_t *table) { xmpp_ctx_t *ctx = table->ctx; hash_iterator_t *iter; iter = xmpp_alloc(ctx, sizeof(*iter)); if (iter != NULL) { iter->ref = 1; iter->table = hash_clone(table); iter->entry = NULL; iter->index = -1; } return iter; } /** release an iterator that is no longer needed */ void hash_iter_release(hash_iterator_t *iter) { xmpp_ctx_t *ctx = iter->table->ctx; iter->ref--; if (iter->ref <= 0) { hash_release(iter->table); xmpp_free(ctx, iter); } } /** return the next hash table key from the iterator. the returned key should not be freed */ const char * hash_iter_next(hash_iterator_t *iter) { hash_t *table = iter->table; hashentry_t *entry = iter->entry; int i; /* advance until we find the next entry */ if (entry != NULL) entry = entry->next; if (entry == NULL) { /* we're off the end of list, search for a new entry */ i = iter->index + 1; while (i < iter->table->length) { entry = table->entries[i]; if (entry != NULL) { iter->index = i; break; } i++; } } if (entry == NULL) { /* no more keys! */ return NULL; } /* remember our current match */ iter->entry = entry; return entry->key; } libstrophe-0.8.8/src/hash.h000066400000000000000000000032601256471717200156020ustar00rootroot00000000000000/* hash.h ** strophe XMPP client library -- hash table interface ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Hash table API. */ #ifndef __LIBSTROPHE_HASH_H__ #define __LIBSTROPHE_HASH_H__ typedef struct _hash_t hash_t; typedef void (*hash_free_func)(const xmpp_ctx_t * const ctx, void *p); /** allocate and initialize a new hash table */ hash_t *hash_new(xmpp_ctx_t * const ctx, const int size, hash_free_func free); /** allocate a new reference to an existing hash table */ hash_t *hash_clone(hash_t * const table); /** release a hash table when no longer needed */ void hash_release(hash_t * const table); /** add a key, value pair to a hash table. * each key can appear only once; the value of any * identical key will be replaced */ int hash_add(hash_t *table, const char * const key, void *data); /** look up a key in a hash table */ void *hash_get(hash_t *table, const char *key); /** delete a key from a hash table */ int hash_drop(hash_t *table, const char *key); /** return the number of keys in a hash */ int hash_num_keys(hash_t *table); /** hash key iterator functions */ typedef struct _hash_iterator_t hash_iterator_t; /** allocate and initialize a new iterator */ hash_iterator_t *hash_iter_new(hash_t *table); /** release an iterator that is no longer needed */ void hash_iter_release(hash_iterator_t *iter); /** return the next hash table key from the iterator. the returned key should not be freed */ const char * hash_iter_next(hash_iterator_t *iter); #endif /* __LIBXMPPP_HASH_H__ */ libstrophe-0.8.8/src/jid.c000066400000000000000000000073731256471717200154310ustar00rootroot00000000000000/* jid.c ** strophe XMPP client library -- helper functions for parsing JIDs ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * JID creation and parsing. */ #include #include "strophe.h" #include "common.h" /** Create a JID string from component parts node, domain, and resource. * * @param ctx the Strophe context object * @param node a string representing the node * @param domain a string representing the domain. Required. * @param resource a string representing the resource * * @return an allocated string with the full JID or NULL if no domain * is specified */ char *xmpp_jid_new(xmpp_ctx_t *ctx, const char *node, const char *domain, const char *resource) { char *result; int len,nlen,dlen,rlen; /* jid must at least have a domain */ if (domain == NULL) return NULL; /* accumulate lengths */ dlen = strlen(domain); nlen = (node) ? strlen(node) + 1 : 0; rlen = (resource) ? strlen(resource) + 1 : 0; len = nlen + dlen + rlen; /* concat components */ result = xmpp_alloc(ctx, len + 1); if (result != NULL) { if (node != NULL) { memcpy(result, node, nlen - 1); result[nlen-1] = '@'; } memcpy(result + nlen, domain, dlen); if (resource != NULL) { result[nlen+dlen] = '/'; memcpy(result+nlen+dlen+1, resource, rlen - 1); } result[nlen+dlen+rlen] = '\0'; } return result; } /** Create a bare JID from a JID. * * @param ctx the Strophe context object * @param jid the JID * * @return an allocated string with the bare JID or NULL on an error */ char *xmpp_jid_bare(xmpp_ctx_t *ctx, const char *jid) { char *result; const char *c; c = strchr(jid, '/'); if (c == NULL) return xmpp_strdup(ctx, jid); result = xmpp_alloc(ctx, c-jid+1); if (result != NULL) { memcpy(result, jid, c-jid); result[c-jid] = '\0'; } return result; } /** Create a node string from a JID. * * @param ctx a Strophe context object * @param jid the JID * * @return an allocated string with the node or NULL if no node is found * or an error occurs */ char *xmpp_jid_node(xmpp_ctx_t *ctx, const char *jid) { char *result = NULL; const char *c; c = strchr(jid, '@'); if (c != NULL) { result = xmpp_alloc(ctx, (c-jid) + 1); if (result != NULL) { memcpy(result, jid, (c-jid)); result[c-jid] = '\0'; } } return result; } /** Create a domain string from a JID. * * @param ctx the Strophe context object * @param jid the JID * * @return an allocated string with the domain or NULL on an error */ char *xmpp_jid_domain(xmpp_ctx_t *ctx, const char *jid) { char *result = NULL; const char *c,*s; c = strchr(jid, '@'); if (c == NULL) { /* no node, assume domain */ c = jid; } else { /* advance past the separator */ c++; } s = strchr(c, '/'); if (s == NULL) { /* no resource */ s = c + strlen(c); } result = xmpp_alloc(ctx, (s-c) + 1); if (result != NULL) { memcpy(result, c, (s-c)); result[s-c] = '\0'; } return result; } /** Create a resource string from a JID. * * @param ctx a Strophe context object * @param jid the JID * * @return an allocated string with the resource or NULL if no resource * is found or an error occurs */ char *xmpp_jid_resource(xmpp_ctx_t *ctx, const char *jid) { char *result = NULL; const char *c; int len; c = strchr(jid, '/'); if (c != NULL) { c++; len = strlen(c); result = xmpp_alloc(ctx, len + 1); if (result != NULL) { memcpy(result, c, len); result[len] = '\0'; } } return result; } libstrophe-0.8.8/src/md5.c000066400000000000000000000216001256471717200153350ustar00rootroot00000000000000/* md5.c ** MD5 hash function implemention, adapted for local use ** ** This code is in the Public Domain */ /* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ /** @file * MD5 hash. */ #include /* memcpy(), memset() */ #include "md5.h" /* little-endian word access macros */ #define GET_32BIT_LSB_FIRST(cp) \ (((uint32_t)(unsigned char)(cp)[0]) | \ ((uint32_t)(unsigned char)(cp)[1] << 8 ) | \ ((uint32_t)(unsigned char)(cp)[2] << 16) | \ ((uint32_t)(unsigned char)(cp)[3] << 24)) #define PUT_32BIT_LSB_FIRST(cp, value) \ do { \ (cp)[0] = (value) & 0xFF; \ (cp)[1] = ((value) >> 8) & 0xFF; \ (cp)[2] = ((value) >> 16) & 0xFF; \ (cp)[3] = ((value) >> 24) & 0xFF; \ } while(0) static void MD5Transform(uint32_t buf[4], const unsigned char inext[64], struct MD5Context *ctx); /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(struct MD5Context *ctx) { ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; memset(ctx->in, 0, 64); } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(struct MD5Context *ctx, unsigned char const *buf, uint32_t len) { uint32_t t; /* Update bitcount */ t = ctx->bits[0]; if ((ctx->bits[0] = (t + ((uint32_t)len << 3)) & 0xffffffff) < t) ctx->bits[1]++; /* Carry from low to high */ ctx->bits[1] += len >> 29; t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ /* Handle any leading odd-sized chunks */ if (t) { unsigned char *p = ctx->in + t; t = 64 - t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); MD5Transform(ctx->buf, ctx->in, ctx); buf += t; len -= t; } /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); MD5Transform(ctx->buf, ctx->in, ctx); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ void MD5Final(unsigned char digest[16], struct MD5Context *ctx) { unsigned count; unsigned char *p; /* Compute number of bytes mod 64 */ count = (ctx->bits[0] >> 3) & 0x3F; /* Set the first char of padding to 0x80. This is safe since there is always at least one byte free */ p = ctx->in + count; *p++ = 0x80; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count; /* Pad out to 56 mod 64 */ if (count < 8) { /* Two lots of padding: Pad the first block to 64 bytes */ memset(p, 0, count); MD5Transform(ctx->buf, ctx->in, ctx); /* Now fill the next block with 56 bytes */ memset(ctx->in, 0, 56); } else { /* Pad block to 56 bytes */ memset(p, 0, count - 8); } /* Append length in bits and transform */ PUT_32BIT_LSB_FIRST(ctx->in + 56, ctx->bits[0]); PUT_32BIT_LSB_FIRST(ctx->in + 60, ctx->bits[1]); MD5Transform(ctx->buf, ctx->in, ctx); PUT_32BIT_LSB_FIRST(digest, ctx->buf[0]); PUT_32BIT_LSB_FIRST(digest + 4, ctx->buf[1]); PUT_32BIT_LSB_FIRST(digest + 8, ctx->buf[2]); PUT_32BIT_LSB_FIRST(digest + 12, ctx->buf[3]); memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */ } #ifndef ASM_MD5 /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ /* debugging version: */ /* #define MD5STEP(f, w, x, y, z, data, s) \ printf("MD5STEP: w: %x x: %x y: %x z: %x data: %x s: %x\n", \ w, x, y, z, data, s); \ printf("f(x,y,z) = %x\n", f(x,y,z)+data); \ ( w += f(x, y, z) + data, printf(" - w: %x ", w), \ w = w<>(32-s), printf(" - w: %x\n", w), w += x ) */ #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ static void MD5Transform(uint32_t buf[4], const unsigned char inext[64], struct MD5Context *ctx) { register uint32_t a, b, c, d, i; uint32_t in[16]; for (i = 0; i < 16; i++) in[i] = GET_32BIT_LSB_FIRST(inext + 4 * i); a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } #ifdef DEBUG_MD5 #include void MD5DumpBytes(unsigned char *b, int len) { int i; for (i=0; i #include "strophe.h" #include "strophepp.h" XMPP::Context::Context() { m_mem.alloc = callAlloc; m_mem.realloc = callRealloc; m_mem.free = callFree; m_mem.userdata = (void *)this; m_log.handler = callLog; m_log.userdata = (void *)this; m_ctx = ::xmpp_ctx_new(&m_mem, &m_log); } XMPP::Context::~Context() { ::xmpp_ctx_free(m_ctx); } void *XMPP::Context::alloc(const size_t size) { return ::malloc(size); } void *XMPP::Context::realloc(void *p, const size_t size) { return ::realloc(p, size); } void XMPP::Context::free(void *p) { ::free(p); } void XMPP::Context::log(const xmpp_log_level_t level, const char * const area, const char * const msg) { /* do nothing by default */ } xmpp_ctx_t *XMPP::Context::getContext() { return m_ctx; } void *XMPP::Context::callAlloc(const size_t size, void * const userdata) { return reinterpret_cast(userdata)->alloc(size); } void *XMPP::Context::callRealloc(void *p, const size_t size, void * const userdata) { return reinterpret_cast(userdata)->realloc(p, size); } void XMPP::Context::callFree(void *p, void * const userdata) { reinterpret_cast(userdata)->free(p); } void XMPP::Context::callLog(void * const userdata, const xmpp_log_level_t level, const char * const area, const char * const msg) { reinterpret_cast(userdata)->log(level, area, msg); } libstrophe-0.8.8/src/oostanza.cpp000066400000000000000000000030711256471717200170500ustar00rootroot00000000000000/* oostanza.cpp ** strophe XMPP client library -- C++ context implementation ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include "strophe.h" #include "strophepp.h" using namespace XMPP; void *Stanza::operator new(size_t size, Context *ctx) { void *p; /* we must allocate extra room for the Context object so that the destructor can access it to free the object. C++ does not allow us to access normal members in the destructor, so we have to hide it. This must be prepended as well, since C++ will add stuff to the end in subclasses. */ p = ctx->alloc(size + sizeof(Context *)); if (!p) return p; *reinterpret_cast(p) = ctx; p = reinterpret_cast(reinterpret_cast(p) + sizeof(Context *)); return p; } void Stanza::operator delete(void *p) { Context *ctx; ctx = *reinterpret_cast(reinterpret_cast(p) - 4); ctx->free(reinterpret_cast(p) - 4); } Stanza::Stanza(Context *ctx) { m_ctx = ctx; m_stanza = ::xmpp_stanza_new(ctx->getContext()); // TODO: check for errors } Stanza::~Stanza() { } Stanza *Stanza::create(Context *ctx) { return new (ctx) Stanza(ctx); } void Stanza::release() { if (::xmpp_stanza_release(m_stanza)) delete this; } Stanza *Stanza::clone() { ::xmpp_stanza_clone(m_stanza); return this; } Stanza *Stanza::copy() { // TODO return NULL; } libstrophe-0.8.8/src/ostypes.h000066400000000000000000000014361256471717200163700ustar00rootroot00000000000000/* ostypes.h ** strophe XMPP client library -- type definitions for platforms ** without stdint.h ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Type definitions for platforms without stdint.h. */ #ifndef __LIBSTROPHE_OSTYPES_H__ #define __LIBSTROPHE_OSTYPES_H__ #if defined (_MSC_VER) && _MSC_VER < 1600 typedef signed char int8_t; typedef short int int16_t; typedef int int32_t; typedef __int64 int64_t; typedef unsigned char uint8_t; typedef unsigned short int uint16_t; typedef unsigned int uint32_t; typedef unsigned __int64 uint64_t; #else #include #endif #endif /* __LIBSTROPHE_OSTYPES_H__ */ libstrophe-0.8.8/src/parser.h000066400000000000000000000024161256471717200161550ustar00rootroot00000000000000/* parser.h ** strophe XMPP client library -- parser structures and functions ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express or ** implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Internally used functions and structures. */ #ifndef __LIBSTROPHE_PARSER_H__ #define __LIBSTROPHE_PARSER_H__ #include "strophe.h" typedef struct _parser_t parser_t; typedef void (*parser_start_callback)(char *name, char **attrs, void * const userdata); typedef void (*parser_end_callback)(char *name, void * const userdata); typedef void (*parser_stanza_callback)(xmpp_stanza_t *stanza, void * const userdata); parser_t *parser_new(xmpp_ctx_t *ctx, parser_start_callback startcb, parser_end_callback endcb, parser_stanza_callback stanzacb, void *userdata); void parser_free(parser_t * const parser); char* parser_attr_name(xmpp_ctx_t *ctx, char *nsname); int parser_reset(parser_t *parser); int parser_feed(parser_t *parser, char *chunk, int len); #endif /* __LIBSTROPHE_PARSER_H__ */ libstrophe-0.8.8/src/parser_expat.c000066400000000000000000000146751256471717200173630ustar00rootroot00000000000000/* parser.c ** strophe XMPP client library -- xml parser handlers and utility functions ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * XML parser handlers. */ #include #include #include #include #include #include "common.h" #include "parser.h" /* ASCII FF is invalid UTF-8 and should never be present in well-formed XML */ #define NAMESPACE_SEP ('\xFF') struct _parser_t { xmpp_ctx_t *ctx; XML_Parser expat; parser_start_callback startcb; parser_end_callback endcb; parser_stanza_callback stanzacb; void *userdata; int depth; xmpp_stanza_t *stanza; }; /* return allocated string with the name from a delimited * namespace/name string */ static char *_xml_name(xmpp_ctx_t *ctx, const char *nsname) { char *result = NULL; const char *c; int len; c = strchr(nsname, NAMESPACE_SEP); if (c == NULL) return xmpp_strdup(ctx, nsname); c++; len = strlen(c); result = xmpp_alloc(ctx, len + 1); if (result != NULL) { memcpy(result, c, len); result[len] = '\0'; } return result; } /* return allocated string with the namespace from a delimited string */ static char *_xml_namespace(xmpp_ctx_t *ctx, const char *nsname) { char *result = NULL; const char *c; c = strchr(nsname, NAMESPACE_SEP); if (c != NULL) { result = xmpp_alloc(ctx, (c-nsname) + 1); if (result != NULL) { memcpy(result, nsname, (c-nsname)); result[c-nsname] = '\0'; } } return result; } static void _set_attributes(xmpp_stanza_t *stanza, const XML_Char **attrs) { char *attr; int i; if (!attrs) return; for (i = 0; attrs[i]; i += 2) { /* namespaced attributes aren't used in xmpp, discard namespace */ attr = _xml_name(stanza->ctx, attrs[i]); xmpp_stanza_set_attribute(stanza, attr, attrs[i+1]); xmpp_free(stanza->ctx, attr); } } static void _start_element(void *userdata, const XML_Char *nsname, const XML_Char **attrs) { parser_t *parser = (parser_t *)userdata; xmpp_stanza_t *child; char *ns, *name; ns = _xml_namespace(parser->ctx, nsname); name = _xml_name(parser->ctx, nsname); if (parser->depth == 0) { /* notify the owner */ if (parser->startcb) parser->startcb((char *)name, (char **)attrs, parser->userdata); } else { /* build stanzas at depth 1 */ if (!parser->stanza && parser->depth != 1) { /* something terrible happened */ /* FIXME: shutdown disconnect */ xmpp_error(parser->ctx, "parser", "oops, where did our stanza go?"); } else if (!parser->stanza) { /* starting a new toplevel stanza */ parser->stanza = xmpp_stanza_new(parser->ctx); if (!parser->stanza) { /* FIXME: can't allocate, disconnect */ } xmpp_stanza_set_name(parser->stanza, name); _set_attributes(parser->stanza, attrs); if (ns) xmpp_stanza_set_ns(parser->stanza, ns); } else { /* starting a child of parser->stanza */ child = xmpp_stanza_new(parser->ctx); if (!child) { /* FIXME: can't allocate, disconnect */ } xmpp_stanza_set_name(child, name); _set_attributes(child, attrs); if (ns) xmpp_stanza_set_ns(child, ns); /* add child to parent */ xmpp_stanza_add_child(parser->stanza, child); /* the child is owned by the toplevel stanza now */ xmpp_stanza_release(child); /* make child the current stanza */ parser->stanza = child; } } if (ns) xmpp_free(parser->ctx, ns); if (name) xmpp_free(parser->ctx, name); parser->depth++; } static void _end_element(void *userdata, const XML_Char *name) { parser_t *parser = (parser_t *)userdata; parser->depth--; if (parser->depth == 0) { /* notify the owner */ if (parser->endcb) parser->endcb((char *)name, parser->userdata); } else { if (parser->stanza->parent) { /* we're finishing a child stanza, so set current to the parent */ parser->stanza = parser->stanza->parent; } else { if (parser->stanzacb) parser->stanzacb(parser->stanza, parser->userdata); xmpp_stanza_release(parser->stanza); parser->stanza = NULL; } } } static void _characters(void *userdata, const XML_Char *s, int len) { parser_t *parser = (parser_t *)userdata; xmpp_stanza_t *stanza; if (parser->depth < 2) return; /* create and populate stanza */ stanza = xmpp_stanza_new(parser->ctx); if (!stanza) { /* FIXME: allocation error, disconnect */ return; } xmpp_stanza_set_text_with_size(stanza, s, len); xmpp_stanza_add_child(parser->stanza, stanza); xmpp_stanza_release(stanza); } parser_t *parser_new(xmpp_ctx_t *ctx, parser_start_callback startcb, parser_end_callback endcb, parser_stanza_callback stanzacb, void *userdata) { parser_t *parser; parser = xmpp_alloc(ctx, sizeof(parser_t)); if (parser != NULL) { parser->ctx = ctx; parser->expat = NULL; parser->startcb = startcb; parser->endcb = endcb; parser->stanzacb = stanzacb; parser->userdata = userdata; parser->depth = 0; parser->stanza = NULL; parser_reset(parser); } return parser; } char* parser_attr_name(xmpp_ctx_t *ctx, char *nsname) { return _xml_name(ctx, nsname); } /* free a parser */ void parser_free(parser_t *parser) { if (parser->expat) XML_ParserFree(parser->expat); xmpp_free(parser->ctx, parser); } /* shuts down and restarts XML parser. true on success */ int parser_reset(parser_t *parser) { if (parser->expat) XML_ParserFree(parser->expat); if (parser->stanza) xmpp_stanza_release(parser->stanza); parser->expat = XML_ParserCreateNS(NULL, NAMESPACE_SEP); if (!parser->expat) return 0; parser->depth = 0; parser->stanza = NULL; XML_SetUserData(parser->expat, parser); XML_SetElementHandler(parser->expat, _start_element, _end_element); XML_SetCharacterDataHandler(parser->expat, _characters); return 1; } int parser_feed(parser_t *parser, char *chunk, int len) { return XML_Parse(parser->expat, chunk, len, 0); } libstrophe-0.8.8/src/parser_libxml2.c000066400000000000000000000170431256471717200176030ustar00rootroot00000000000000/* parser.c ** strophe XMPP client library -- xml parser handlers and utility functions ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * XML parser handlers. */ #include #include #include #include #include #include #include "common.h" #include "parser.h" struct _parser_t { xmpp_ctx_t *ctx; xmlParserCtxtPtr xmlctx; xmlSAXHandler handlers; parser_start_callback startcb; parser_end_callback endcb; parser_stanza_callback stanzacb; void *userdata; int depth; xmpp_stanza_t *stanza; }; static void _set_attributes(xmpp_stanza_t *stanza, int nattrs, const xmlChar **attrs) { int i, len; char *value; if (!attrs) return; /* SAX2 uses array of localname/prefix/uri/value_begin/value_end */ for (i = 0; i < nattrs*5; i += 5) { len = attrs[i+4] - attrs[i+3]; value = xmpp_alloc(stanza->ctx, len + 1); if (value) { memcpy(value, attrs[i+3], len); value[len] = '\0'; xmpp_stanza_set_attribute(stanza, (const char *)attrs[i], value); xmpp_free(stanza->ctx, value); } } } /* SAX2 gives us the attrs in an incredibly inconvenient array, * convert it to what the start callback is expecting */ static char **_convert_attrs(parser_t *parser, int nattrs, const xmlChar **attrs) { int c, i, o, len; char *value; char **ret; if (!attrs) return NULL; ret = xmpp_alloc(parser->ctx, (nattrs+1)*2*sizeof(char*)); if (!ret) return NULL; memset(ret, 0, (nattrs+1)*2*sizeof(char*)); for (c = 0; c < nattrs; c++) { i = c * 5; o = c * 2; len = attrs[i+4] - attrs[i+3]; value = xmpp_alloc(parser->ctx, len + 1); if (value) { memcpy(value, attrs[i+3], len); value[len] = '\0'; ret[o] = xmpp_strdup(parser->ctx, (char*)attrs[i]); ret[o+1] = value; } } return ret; } static void _free_cbattrs(parser_t *parser, char **attrs) { int i; if (!attrs) return; for (i = 0; attrs[i]; i += 2) { if (attrs[i]) xmpp_free(parser->ctx, attrs[i]); if (attrs[i+1]) xmpp_free(parser->ctx, attrs[i+1]); } xmpp_free(parser->ctx, attrs); } static void _start_element(void *userdata, const xmlChar *name, const xmlChar *prefix, const xmlChar *uri, int nnamespaces, const xmlChar **namespaces, int nattrs, int ndefaulted, const xmlChar **attrs) { parser_t *parser = (parser_t *)userdata; xmpp_stanza_t *child; char **cbattrs; if (parser->depth == 0) { /* notify the owner */ if (parser->startcb) cbattrs = _convert_attrs(parser, nattrs, attrs); parser->startcb((char *)name, cbattrs, parser->userdata); _free_cbattrs(parser, cbattrs); } else { /* build stanzas at depth 1 */ if (!parser->stanza && parser->depth != 1) { /* something terrible happened */ /* FIXME: we should probably trigger a disconnect */ xmpp_error(parser->ctx, "parser", "oops, where did our stanza go?"); } else if (!parser->stanza) { /* starting a new toplevel stanza */ parser->stanza = xmpp_stanza_new(parser->ctx); if (!parser->stanza) { /* FIXME: can't allocate, disconnect */ } xmpp_stanza_set_name(parser->stanza, (char *)name); _set_attributes(parser->stanza, nattrs, attrs); if (uri) xmpp_stanza_set_ns(parser->stanza, (char *)uri); } else { /* starting a child of conn->stanza */ child = xmpp_stanza_new(parser->ctx); if (!child) { /* FIXME: can't allocate, disconnect */ } xmpp_stanza_set_name(child, (char *)name); _set_attributes(child, nattrs, attrs); if (uri) xmpp_stanza_set_ns(child, (char *)uri); /* add child to parent */ xmpp_stanza_add_child(parser->stanza, child); /* the child is owned by the toplevel stanza now */ xmpp_stanza_release(child); /* make child the current stanza */ parser->stanza = child; } } parser->depth++; } static void _end_element(void *userdata, const xmlChar *name, const xmlChar *prefix, const xmlChar *uri) { parser_t *parser = (parser_t *)userdata; parser->depth--; if (parser->depth == 0) { /* notify owner */ if (parser->endcb) parser->endcb((char *)name, parser->userdata); } else { if (parser->stanza->parent) { /* we're finishing a child stanza, so set current to the parent */ parser->stanza = parser->stanza->parent; } else { if (parser->stanzacb) parser->stanzacb(parser->stanza, parser->userdata); xmpp_stanza_release(parser->stanza); parser->stanza = NULL; } } } static void _characters(void *userdata, const xmlChar *chr, int len) { parser_t *parser = (parser_t *)userdata; xmpp_stanza_t *stanza; /* skip unimportant whitespace, etc */ if (parser->depth < 2) return; /* create and populate stanza */ stanza = xmpp_stanza_new(parser->ctx); if (!stanza) { /* FIXME: allocation error, disconnect */ return; } xmpp_stanza_set_text_with_size(stanza, (char *)chr, len); xmpp_stanza_add_child(parser->stanza, stanza); xmpp_stanza_release(stanza); } /* create a new parser */ parser_t *parser_new(xmpp_ctx_t *ctx, parser_start_callback startcb, parser_end_callback endcb, parser_stanza_callback stanzacb, void *userdata) { parser_t *parser; parser = xmpp_alloc(ctx, sizeof(parser_t)); if (parser != NULL) { parser->ctx = ctx; parser->xmlctx = NULL; memset(&parser->handlers, 0, sizeof(xmlSAXHandler)); parser->handlers.initialized = XML_SAX2_MAGIC; parser->handlers.startElementNs = _start_element; parser->handlers.endElementNs = _end_element; parser->handlers.characters = _characters; parser->startcb = startcb; parser->endcb = endcb; parser->stanzacb = stanzacb; parser->userdata = userdata; parser->depth = 0; parser->stanza = NULL; parser_reset(parser); } return parser; } char* parser_attr_name(xmpp_ctx_t *ctx, char *nsname) { return xmpp_strdup(ctx, nsname); } /* free a parser */ void parser_free(parser_t *parser) { if (parser->xmlctx) xmlFreeParserCtxt(parser->xmlctx); xmpp_free(parser->ctx, parser); } /* shuts down and restarts XML parser. true on success */ int parser_reset(parser_t *parser) { if (parser->xmlctx) xmlFreeParserCtxt(parser->xmlctx); if (parser->stanza) xmpp_stanza_release(parser->stanza); parser->xmlctx = xmlCreatePushParserCtxt(&parser->handlers, parser, NULL, 0, NULL); if (!parser->xmlctx) return 0; parser->depth = 0; parser->stanza = NULL; return 1; } /* feed a chunk of data to the parser */ int parser_feed(parser_t *parser, char *chunk, int len) { /* xmlParseChunk API returns 0 on success which is opposite logic to the status returned by parser_feed */ if(!xmlParseChunk(parser->xmlctx, chunk, len, 0)) { return 1; } else { return 0; } } libstrophe-0.8.8/src/sasl.c000066400000000000000000000470271256471717200156250ustar00rootroot00000000000000/* sasl.c ** strophe XMPP client library -- SASL authentication helpers ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * SASL authentication. */ #include #include #include "strophe.h" #include "common.h" #include "ostypes.h" #include "sasl.h" #include "md5.h" #include "sha1.h" #include "scram.h" #ifdef _WIN32 #define strtok_r strtok_s #endif /** generate authentication string for the SASL PLAIN mechanism */ char *sasl_plain(xmpp_ctx_t *ctx, const char *authid, const char *password) { int idlen, passlen; char *result = NULL; char *msg; /* our message is Base64(authzid,\0,authid,\0,password) if there is no authzid, that field is left empty */ idlen = strlen(authid); passlen = strlen(password); msg = xmpp_alloc(ctx, 2 + idlen + passlen); if (msg != NULL) { msg[0] = '\0'; memcpy(msg+1, authid, idlen); msg[1+idlen] = '\0'; memcpy(msg+1+idlen+1, password, passlen); result = base64_encode(ctx, (unsigned char *)msg, 2 + idlen + passlen); xmpp_free(ctx, msg); } return result; } /** helpers for digest auth */ /* create a new, null-terminated string from a substring */ static char *_make_string(xmpp_ctx_t *ctx, const char *s, const unsigned len) { char *result; result = xmpp_alloc(ctx, len + 1); if (result != NULL) { memcpy(result, s, len); result[len] = '\0'; } return result; } /* create a new, null-terminated string quoting another string */ static char *_make_quoted(xmpp_ctx_t *ctx, const char *s) { char *result; int len = strlen(s); result = xmpp_alloc(ctx, len + 3); if (result != NULL) { result[0] = '"'; memcpy(result+1, s, len); result[len+1] = '"'; result[len+2] = '\0'; } return result; } /* split key, value pairs into a hash */ static hash_t *_parse_digest_challenge(xmpp_ctx_t *ctx, const char *msg) { hash_t *result; unsigned char *text; char *key, *value; unsigned char *s, *t; text = base64_decode(ctx, msg, strlen(msg)); if (text == NULL) { xmpp_error(ctx, "SASL", "couldn't Base64 decode challenge!"); return NULL; } result = hash_new(ctx, 10, xmpp_free); if (result != NULL) { s = text; while (*s != '\0') { /* skip any leading commas and spaces */ while ((*s == ',') || (*s == ' ')) s++; /* accumulate a key ending at '=' */ t = s; while ((*t != '=') && (*t != '\0')) t++; if (*t == '\0') break; /* bad string */ key = _make_string(ctx, (char *)s, (t-s)); if (key == NULL) break; /* advance our start pointer past the key */ s = t + 1; t = s; /* if we see quotes, grab the string in between */ if ((*s == '\'') || (*s == '"')) { t++; while ((*t != *s) && (*t != '\0')) t++; value = _make_string(ctx, (char *)s+1, (t-s-1)); if (*t == *s) { s = t + 1; } else { s = t; } /* otherwise, accumulate a value ending in ',' or '\0' */ } else { while ((*t != ',') && (*t != '\0')) t++; value = _make_string(ctx, (char *)s, (t-s)); s = t; } if (value == NULL) { xmpp_free(ctx, key); break; } /* TODO: check for collisions per spec */ hash_add(result, key, value); /* hash table now owns the value, free the key */ xmpp_free(ctx, key); } } xmpp_free(ctx, text); return result; } /** expand a 16 byte MD5 digest to a 32 byte hex representation */ static void _digest_to_hex(const char *digest, char *hex) { int i; const char hexdigit[] = "0123456789abcdef"; for (i = 0; i < 16; i++) { *hex++ = hexdigit[ (digest[i] >> 4) & 0x0F ]; *hex++ = hexdigit[ digest[i] & 0x0F ]; } } /** append 'key="value"' to a buffer, growing as necessary */ static char *_add_key(xmpp_ctx_t *ctx, hash_t *table, const char *key, char *buf, int *len, int quote) { int olen,nlen; int keylen, valuelen; const char *value, *qvalue; char *c; /* allocate a zero-length string if necessary */ if (buf == NULL) { buf = xmpp_alloc(ctx, 1); buf[0] = '\0'; } if (buf == NULL) return NULL; /* get current string length */ olen = strlen(buf); value = hash_get(table, key); if (value == NULL) { xmpp_error(ctx, "SASL", "couldn't retrieve value for '%s'", key); value = ""; } if (quote) { qvalue = _make_quoted(ctx, value); } else { qvalue = value; } /* added length is key + '=' + value */ /* (+ ',' if we're not the first entry */ keylen = strlen(key); valuelen = strlen(qvalue); nlen = (olen ? 1 : 0) + keylen + 1 + valuelen + 1; buf = xmpp_realloc(ctx, buf, olen+nlen); if (buf != NULL) { c = buf + olen; if (olen) *c++ = ','; memcpy(c, key, keylen); c += keylen; *c++ = '='; memcpy(c, qvalue, valuelen); c += valuelen; *c++ = '\0'; } if (quote) xmpp_free(ctx, (char *)qvalue); return buf; } /** generate auth response string for the SASL DIGEST-MD5 mechanism */ char *sasl_digest_md5(xmpp_ctx_t *ctx, const char *challenge, const char *jid, const char *password) { hash_t *table; char *result = NULL; char *node, *domain, *realm; char *value; char *response; int rlen; struct MD5Context MD5; unsigned char digest[16], HA1[16], HA2[16]; char hex[32]; /* our digest response is Hex( KD( HEX(MD5(A1)), nonce ':' nc ':' cnonce ':' qop ':' HEX(MD5(A2)) )) where KD(k, s) = MD5(k ':' s), A1 = MD5( node ':' realm ':' password ) ':' nonce ':' cnonce A2 = "AUTHENTICATE" ':' "xmpp/" domain If there is an authzid it is ':'-appended to A1 */ /* parse the challenge */ table = _parse_digest_challenge(ctx, challenge); if (table == NULL) { xmpp_error(ctx, "SASL", "couldn't parse digest challenge"); return NULL; } node = xmpp_jid_node(ctx, jid); domain = xmpp_jid_domain(ctx, jid); /* generate default realm of domain if one didn't come from the server */ realm = hash_get(table, "realm"); if (realm == NULL || strlen(realm) == 0) { hash_add(table, "realm", xmpp_strdup(ctx, domain)); realm = hash_get(table, "realm"); } /* add our response fields */ hash_add(table, "username", xmpp_strdup(ctx, node)); /* TODO: generate a random cnonce */ hash_add(table, "cnonce", xmpp_strdup(ctx, "00DEADBEEF00")); hash_add(table, "nc", xmpp_strdup(ctx, "00000001")); hash_add(table, "qop", xmpp_strdup(ctx, "auth")); value = xmpp_alloc(ctx, 5 + strlen(domain) + 1); memcpy(value, "xmpp/", 5); memcpy(value+5, domain, strlen(domain)); value[5+strlen(domain)] = '\0'; hash_add(table, "digest-uri", value); /* generate response */ /* construct MD5(node : realm : password) */ MD5Init(&MD5); MD5Update(&MD5, (unsigned char *)node, strlen(node)); MD5Update(&MD5, (unsigned char *)":", 1); MD5Update(&MD5, (unsigned char *)realm, strlen(realm)); MD5Update(&MD5, (unsigned char *)":", 1); MD5Update(&MD5, (unsigned char *)password, strlen(password)); MD5Final(digest, &MD5); /* digest now contains the first field of A1 */ MD5Init(&MD5); MD5Update(&MD5, digest, 16); MD5Update(&MD5, (unsigned char *)":", 1); value = hash_get(table, "nonce"); MD5Update(&MD5, (unsigned char *)value, strlen(value)); MD5Update(&MD5, (unsigned char *)":", 1); value = hash_get(table, "cnonce"); MD5Update(&MD5, (unsigned char *)value, strlen(value)); MD5Final(digest, &MD5); /* now digest is MD5(A1) */ memcpy(HA1, digest, 16); /* construct MD5(A2) */ MD5Init(&MD5); MD5Update(&MD5, (unsigned char *)"AUTHENTICATE:", 13); value = hash_get(table, "digest-uri"); MD5Update(&MD5, (unsigned char *)value, strlen(value)); if (strcmp(hash_get(table, "qop"), "auth") != 0) { MD5Update(&MD5, (unsigned char *)":00000000000000000000000000000000", 33); } MD5Final(digest, &MD5); memcpy(HA2, digest, 16); /* construct response */ MD5Init(&MD5); _digest_to_hex((char *)HA1, hex); MD5Update(&MD5, (unsigned char *)hex, 32); MD5Update(&MD5, (unsigned char *)":", 1); value = hash_get(table, "nonce"); MD5Update(&MD5, (unsigned char *)value, strlen(value)); MD5Update(&MD5, (unsigned char *)":", 1); value = hash_get(table, "nc"); MD5Update(&MD5, (unsigned char *)value, strlen(value)); MD5Update(&MD5, (unsigned char *)":", 1); value = hash_get(table, "cnonce"); MD5Update(&MD5, (unsigned char *)value, strlen(value)); MD5Update(&MD5, (unsigned char *)":", 1); value = hash_get(table, "qop"); MD5Update(&MD5, (unsigned char *)value, strlen(value)); MD5Update(&MD5, (unsigned char *)":", 1); _digest_to_hex((char *)HA2, hex); MD5Update(&MD5, (unsigned char *)hex, 32); MD5Final(digest, &MD5); response = xmpp_alloc(ctx, 32+1); _digest_to_hex((char *)digest, hex); memcpy(response, hex, 32); response[32] = '\0'; hash_add(table, "response", response); /* construct reply */ result = NULL; rlen = 0; result = _add_key(ctx, table, "username", result, &rlen, 1); result = _add_key(ctx, table, "realm", result, &rlen, 1); result = _add_key(ctx, table, "nonce", result, &rlen, 1); result = _add_key(ctx, table, "cnonce", result, &rlen, 1); result = _add_key(ctx, table, "nc", result, &rlen, 0); result = _add_key(ctx, table, "qop", result, &rlen, 0); result = _add_key(ctx, table, "digest-uri", result, &rlen, 1); result = _add_key(ctx, table, "response", result, &rlen, 0); result = _add_key(ctx, table, "charset", result, &rlen, 0); xmpp_free(ctx, node); xmpp_free(ctx, domain); hash_release(table); /* also frees value strings */ /* reuse response for the base64 encode of our result */ response = base64_encode(ctx, (unsigned char *)result, strlen(result)); xmpp_free(ctx, result); return response; } /** generate auth response string for the SASL SCRAM-SHA-1 mechanism */ char *sasl_scram_sha1(xmpp_ctx_t *ctx, const char *challenge, const char *first_bare, const char *jid, const char *password) { uint8_t key[SHA1_DIGEST_SIZE]; uint8_t sign[SHA1_DIGEST_SIZE]; char *r = NULL; char *s = NULL; char *i = NULL; char *sval; size_t sval_len; long ival; char *tmp; char *ptr; char *saveptr = NULL; char *response; char *auth; char *response_b64; char *sign_b64; char *result = NULL; size_t response_len; size_t auth_len; int j; tmp = xmpp_strdup(ctx, challenge); if (!tmp) { return NULL; } ptr = strtok_r(tmp, ",", &saveptr); while (ptr) { if (strncmp(ptr, "r=", 2) == 0) { r = ptr; } else if (strncmp(ptr, "s=", 2) == 0) { s = ptr + 2; } else if (strncmp(ptr, "i=", 2) == 0) { i = ptr + 2; } ptr = strtok_r(NULL, ",", &saveptr); } if (!r || !s || !i) { goto out; } sval = (char *)base64_decode(ctx, s, strlen(s)); if (!sval) { goto out; } sval_len = base64_decoded_len(ctx, s, strlen(s)); ival = strtol(i, &saveptr, 10); auth_len = 10 + strlen(r) + strlen(first_bare) + strlen(challenge); auth = xmpp_alloc(ctx, auth_len); if (!auth) { goto out_sval; } response_len = 39 + strlen(r); response = xmpp_alloc(ctx, response_len); if (!response) { goto out_auth; } xmpp_snprintf(response, response_len, "c=biws,%s", r); xmpp_snprintf(auth, auth_len, "%s,%s,%s", first_bare + 3, challenge, response); SCRAM_SHA1_ClientKey((uint8_t *)password, strlen(password), (uint8_t *)sval, sval_len, (uint32_t)ival, key); SCRAM_SHA1_ClientSignature(key, (uint8_t *)auth, strlen(auth), sign); for (j = 0; j < SHA1_DIGEST_SIZE; j++) { sign[j] ^= key[j]; } sign_b64 = base64_encode(ctx, sign, sizeof(sign)); if (!sign_b64) { goto out_response; } if (strlen(response) + strlen(sign_b64) + 3 + 1 > response_len) { xmpp_free(ctx, sign_b64); goto out_response; } strcat(response, ",p="); strcat(response, sign_b64); xmpp_free(ctx, sign_b64); response_b64 = base64_encode(ctx, (unsigned char *)response, strlen(response)); if (!response_b64) { goto out_response; } result = response_b64; out_response: xmpp_free(ctx, response); out_auth: xmpp_free(ctx, auth); out_sval: xmpp_free(ctx, sval); out: xmpp_free(ctx, tmp); return result; } /** Base64 encoding routines. Implemented according to RFC 3548 */ /** map of all byte values to the base64 values, or to '65' which indicates an invalid character. '=' is '64' */ static const char _base64_invcharmap[256] = { 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,62, 65,65,65,63, 52,53,54,55, 56,57,58,59, 60,61,65,65, 65,64,65,65, 65, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, 15,16,17,18, 19,20,21,22, 23,24,25,65, 65,65,65,65, 65,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, 41,42,43,44, 45,46,47,48, 49,50,51,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65, 65,65,65,65 }; /** map of all 6-bit values to their corresponding byte in the base64 alphabet. Padding char is the value '64' */ static const char _base64_charmap[65] = { 'A','B','C','D', 'E','F','G','H', 'I','J','K','L', 'M','N','O','P', 'Q','R','S','T', 'U','V','W','X', 'Y','Z','a','b', 'c','d','e','f', 'g','h','i','j', 'k','l','m','n', 'o','p','q','r', 's','t','u','v', 'w','x','y','z', '0','1','2','3', '4','5','6','7', '8','9','+','/', '=' }; int base64_encoded_len(xmpp_ctx_t *ctx, const unsigned len) { /* encoded steam is 4 bytes for every three, rounded up */ return ((len + 2)/3) << 2; } char *base64_encode(xmpp_ctx_t *ctx, const unsigned char * const buffer, const unsigned len) { int clen; char *cbuf, *c; uint32_t word, hextet; int i; clen = base64_encoded_len(ctx, len); cbuf = xmpp_alloc(ctx, clen + 1); if (cbuf != NULL) { c = cbuf; /* loop over data, turning every 3 bytes into 4 characters */ for (i = 0; i < len - 2; i += 3) { word = buffer[i] << 16 | buffer[i+1] << 8 | buffer[i+2]; hextet = (word & 0x00FC0000) >> 18; *c++ = _base64_charmap[hextet]; hextet = (word & 0x0003F000) >> 12; *c++ = _base64_charmap[hextet]; hextet = (word & 0x00000FC0) >> 6; *c++ = _base64_charmap[hextet]; hextet = (word & 0x000003F); *c++ = _base64_charmap[hextet]; } /* zero, one or two bytes left */ switch (len - i) { case 0: break; case 1: hextet = (buffer[len-1] & 0xFC) >> 2; *c++ = _base64_charmap[hextet]; hextet = (buffer[len-1] & 0x03) << 4; *c++ = _base64_charmap[hextet]; *c++ = _base64_charmap[64]; /* pad */ *c++ = _base64_charmap[64]; /* pad */ break; case 2: hextet = (buffer[len-2] & 0xFC) >> 2; *c++ = _base64_charmap[hextet]; hextet = ((buffer[len-2] & 0x03) << 4) | ((buffer[len-1] & 0xF0) >> 4); *c++ = _base64_charmap[hextet]; hextet = (buffer[len-1] & 0x0F) << 2; *c++ = _base64_charmap[hextet]; *c++ = _base64_charmap[64]; /* pad */ break; } /* add a terminal null */ *c = '\0'; } return cbuf; } int base64_decoded_len(xmpp_ctx_t *ctx, const char * const buffer, const unsigned len) { int nudge; int c; /* count the padding characters for the remainder */ nudge = -1; c = _base64_invcharmap[(int)buffer[len-1]]; if (c < 64) nudge = 0; else if (c == 64) { c = _base64_invcharmap[(int)buffer[len-2]]; if (c < 64) nudge = 1; else if (c == 64) { c = _base64_invcharmap[(int)buffer[len-3]]; if (c < 64) nudge = 2; } } if (nudge < 0) return 0; /* reject bad coding */ /* decoded steam is 3 bytes for every four */ return 3 * (len >> 2) - nudge; } unsigned char *base64_decode(xmpp_ctx_t *ctx, const char * const buffer, const unsigned len) { int dlen; unsigned char *dbuf, *d; uint32_t word, hextet; int i; /* len must be a multiple of 4 */ if (len & 0x03) return NULL; dlen = base64_decoded_len(ctx, buffer, len); dbuf = xmpp_alloc(ctx, dlen + 1); if (dbuf != NULL) { d = dbuf; /* loop over each set of 4 characters, decoding 3 bytes */ for (i = 0; i < len - 3; i += 4) { hextet = _base64_invcharmap[(int)buffer[i]]; if (hextet & 0xC0) break; word = hextet << 18; hextet = _base64_invcharmap[(int)buffer[i+1]]; if (hextet & 0xC0) break; word |= hextet << 12; hextet = _base64_invcharmap[(int)buffer[i+2]]; if (hextet & 0xC0) break; word |= hextet << 6; hextet = _base64_invcharmap[(int)buffer[i+3]]; if (hextet & 0xC0) break; word |= hextet; *d++ = (word & 0x00FF0000) >> 16; *d++ = (word & 0x0000FF00) >> 8; *d++ = (word & 0x000000FF); } if (hextet > 64) goto _base64_decode_error; /* handle the remainder */ switch (dlen % 3) { case 0: /* nothing to do */ break; case 1: /* redo the last quartet, checking for correctness */ hextet = _base64_invcharmap[(int)buffer[len-4]]; if (hextet & 0xC0) goto _base64_decode_error; word = hextet << 2; hextet = _base64_invcharmap[(int)buffer[len-3]]; if (hextet & 0xC0) goto _base64_decode_error; word |= hextet >> 4; *d++ = word & 0xFF; hextet = _base64_invcharmap[(int)buffer[len-2]]; if (hextet != 64) goto _base64_decode_error; hextet = _base64_invcharmap[(int)buffer[len-1]]; if (hextet != 64) goto _base64_decode_error; break; case 2: /* redo the last quartet, checking for correctness */ hextet = _base64_invcharmap[(int)buffer[len-4]]; if (hextet & 0xC0) goto _base64_decode_error; word = hextet << 10; hextet = _base64_invcharmap[(int)buffer[len-3]]; if (hextet & 0xC0) goto _base64_decode_error; word |= hextet << 4; hextet = _base64_invcharmap[(int)buffer[len-2]]; if (hextet & 0xC0) goto _base64_decode_error; word |= hextet >> 2; *d++ = (word & 0xFF00) >> 8; *d++ = (word & 0x00FF); hextet = _base64_invcharmap[(int)buffer[len-1]]; if (hextet != 64) goto _base64_decode_error; break; } *d = '\0'; } return dbuf; _base64_decode_error: /* invalid character; abort decoding! */ xmpp_free(ctx, dbuf); return NULL; } /*** self tests ***/ #ifdef TEST #include int test_charmap_identity(void) { int i, v, u; for (i = 0; i < 65; i++) { v = _base64_charmap[i]; if (v > 255) return 1; u = _base64_invcharmap[v]; /* printf("map: %d -> %d -> %d\n", i, v, u); */ if (u != i) return 1; } return 0; } int test_charmap_range(void) { int i, v; for (i = 64; i < 256; i++) { v = _base64_invcharmap[i]; if (i < 64) return 1; } return 0; } int main(int argc, char *argv[]) { int ret = 0; printf("testing charmap identity..."); ret = test_charmap_identity(); if (ret) return ret; printf(" ok.\n"); printf("testing charmap range..."); ret = test_charmap_range(); if (ret) return ret; printf(" ok.\n"); printf("no error\n"); return 0; } #endif /* TEST */ libstrophe-0.8.8/src/sasl.h000066400000000000000000000023641256471717200156250ustar00rootroot00000000000000/* sasl.h ** strophe XMPP client library -- SASL authentication helpers ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * SASL authentication helpers. */ #ifndef __LIBSTROPHE_SASL_H__ #define __LIBSTROPHE_SASL_H__ #include "strophe.h" /** low-level sasl routines */ char *sasl_plain(xmpp_ctx_t *ctx, const char *authid, const char *password); char *sasl_digest_md5(xmpp_ctx_t *ctx, const char *challenge, const char *jid, const char *password); char *sasl_scram_sha1(xmpp_ctx_t *ctx, const char *challenge, const char *first_bare, const char *jid, const char *password); /** Base64 encoding routines. Implemented according to RFC 3548 */ int base64_encoded_len(xmpp_ctx_t *ctx, const unsigned len); char *base64_encode(xmpp_ctx_t *ctx, const unsigned char * const buffer, const unsigned len); int base64_decoded_len(xmpp_ctx_t *ctx, const char * const buffer, const unsigned len); unsigned char *base64_decode(xmpp_ctx_t *ctx, const char * const buffer, const unsigned len); #endif /* _LIBXMPP_SASL_H__ */ libstrophe-0.8.8/src/scram.c000066400000000000000000000075751256471717200157740ustar00rootroot00000000000000/* scram.c * strophe XMPP client library * * SCRAM-SHA1 helper functions according to RFC5802 * HMAC-SHA1 implementation according to RFC2104 * * Copyright (C) 2013 Dmitry Podgorny * * This software is provided AS-IS with no warranty, either express * or implied. * * This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * SCRAM-SHA1 helper functions. */ #include #include #include "sha1.h" #include "ostypes.h" #include "scram.h" /* block size for HMAC */ #define BLOCK_SIZE 64 #if BLOCK_SIZE < SHA1_DIGEST_SIZE #error BLOCK_SIZE must not be less than SHA1_DIGEST_SIZE #endif static const uint8_t ipad = 0x36; static const uint8_t opad = 0x5C; static void SHA1(const uint8_t* data, size_t len, uint8_t digest[SHA1_DIGEST_SIZE]) { SHA1_CTX ctx; SHA1_Init(&ctx); SHA1_Update(&ctx, data, len); SHA1_Final(&ctx, digest); } static void HMAC_SHA1(const uint8_t *key, size_t key_len, const uint8_t *text, size_t len, uint8_t digest[SHA1_DIGEST_SIZE]) { uint8_t key_pad[BLOCK_SIZE]; uint8_t key_ipad[BLOCK_SIZE]; uint8_t key_opad[BLOCK_SIZE]; uint8_t sha_digest[SHA1_DIGEST_SIZE]; int i; SHA1_CTX ctx; memset(key_pad, 0, sizeof(key_pad)); if (key_len <= BLOCK_SIZE) { memcpy(key_pad, key, key_len); } else { /* according to RFC2104 */ SHA1(key, key_len, key_pad); } for (i = 0; i < BLOCK_SIZE; i++) { key_ipad[i] = key_pad[i] ^ ipad; key_opad[i] = key_pad[i] ^ opad; } SHA1_Init(&ctx); SHA1_Update(&ctx, key_ipad, BLOCK_SIZE); SHA1_Update(&ctx, text, len); SHA1_Final(&ctx, sha_digest); SHA1_Init(&ctx); SHA1_Update(&ctx, key_opad, BLOCK_SIZE); SHA1_Update(&ctx, sha_digest, SHA1_DIGEST_SIZE); SHA1_Final(&ctx, digest); } static void SCRAM_SHA1_Hi(const uint8_t *text, size_t len, const uint8_t *salt, size_t salt_len, uint32_t i, uint8_t digest[SHA1_DIGEST_SIZE]) { int j, k; uint8_t tmp[128]; static uint8_t int1[] = {0x0, 0x0, 0x0, 0x1}; /* assume salt + INT(1) isn't longer than sizeof(tmp) */ assert(salt_len <= sizeof(tmp) - sizeof(int1)); memset(digest, 0, SHA1_DIGEST_SIZE); if (i == 0) { return; } memcpy(tmp, salt, salt_len); memcpy(&tmp[salt_len], int1, sizeof(int1)); /* 'text' for Hi is a 'key' for HMAC */ HMAC_SHA1(text, len, tmp, salt_len + sizeof(int1), digest); memcpy(tmp, digest, SHA1_DIGEST_SIZE); for (j = 1; j < i; j++) { HMAC_SHA1(text, len, tmp, SHA1_DIGEST_SIZE, tmp); for (k = 0; k < SHA1_DIGEST_SIZE; k++) { digest[k] ^= tmp[k]; } } } void SCRAM_SHA1_ClientKey(const uint8_t *password, size_t len, const uint8_t *salt, size_t salt_len, uint32_t i, uint8_t key[SHA1_DIGEST_SIZE]) { uint8_t salted[SHA1_DIGEST_SIZE]; /* XXX: Normalize(password) is omitted */ SCRAM_SHA1_Hi(password, len, salt, salt_len, i, salted); HMAC_SHA1(salted, SHA1_DIGEST_SIZE, (uint8_t *)"Client Key", strlen("Client Key"), key); } void SCRAM_SHA1_ClientSignature(const uint8_t ClientKey[SHA1_DIGEST_SIZE], const uint8_t *AuthMessage, size_t len, uint8_t sign[SHA1_DIGEST_SIZE]) { uint8_t stored[SHA1_DIGEST_SIZE]; SHA1(ClientKey, SHA1_DIGEST_SIZE, stored); HMAC_SHA1(stored, SHA1_DIGEST_SIZE, AuthMessage, len, sign); } void SCRAM_SHA1_ClientProof(const uint8_t ClientKey[SHA1_DIGEST_SIZE], const uint8_t ClientSignature[SHA1_DIGEST_SIZE], uint8_t proof[SHA1_DIGEST_SIZE]) { int i; for (i = 0; i < SHA1_DIGEST_SIZE; i++) { proof[i] = ClientKey[i] ^ ClientSignature[i]; } } libstrophe-0.8.8/src/scram.h000066400000000000000000000022061256471717200157630ustar00rootroot00000000000000/* scram.h * strophe XMPP client library -- SCRAM-SHA1 helper functions * * Copyright (C) 2013 Dmitry Podgorny * * This software is provided AS-IS with no warranty, either express * or implied. * * This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * SCRAM-SHA1 helper functions. */ #ifndef __LIBSTROPHE_SCRAM_H__ #define __LIBSTROPHE_SCRAM_H__ /* make sure the stdint.h types are available */ #include "ostypes.h" #include "sha1.h" void SCRAM_SHA1_ClientKey(const uint8_t *password, size_t len, const uint8_t *salt, size_t salt_len, uint32_t i, uint8_t key[SHA1_DIGEST_SIZE]); void SCRAM_SHA1_ClientSignature(const uint8_t ClientKey[SHA1_DIGEST_SIZE], const uint8_t *AuthMessage, size_t len, uint8_t sign[SHA1_DIGEST_SIZE]); void SCRAM_SHA1_ClientProof(const uint8_t ClientKey[SHA1_DIGEST_SIZE], const uint8_t ClientSignature[SHA1_DIGEST_SIZE], uint8_t proof[SHA1_DIGEST_SIZE]); #endif /* __LIBSTROPHE_SCRAM_H__ */ libstrophe-0.8.8/src/sha1.c000066400000000000000000000277421256471717200155210ustar00rootroot00000000000000/** @file * SHA-1 hash. */ /* SHA-1 in C By Steve Reid 100% Public Domain ----------------- Modified 7/98 By James H. Brown Still 100% Public Domain Corrected a problem which generated improper hash values on 16 bit machines Routine SHA1Update changed from void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int len) to void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned long len) The 'len' parameter was declared an int which works fine on 32 bit machines. However, on 16 bit machines an int is too small for the shifts being done against it. This caused the hash function to generate incorrect values if len was greater than 8191 (8K - 1) due to the 'len << 3' on line 3 of SHA1Update(). Since the file IO in main() reads 16K at a time, any file 8K or larger would be guaranteed to generate the wrong hash (e.g. Test Vector #3, a million "a"s). I also changed the declaration of variables i & j in SHA1Update to unsigned long from unsigned int for the same reason. These changes should make no difference to any 32 bit implementations since an int and a long are the same size in those environments. -- I also corrected a few compiler warnings generated by Borland C. 1. Added #include for exit() prototype 2. Removed unused variable 'j' in SHA1Final 3. Changed exit(0) to return(0) at end of main. ALL changes I made can be located by searching for comments containing 'JHB' ----------------- Modified 8/98 By Steve Reid Still 100% public domain 1- Removed #include and used return() instead of exit() 2- Fixed overwriting of finalcount in SHA1Final() (discovered by Chris Hall) 3- Changed email address from steve@edmweb.com to sreid@sea-to-sky.net ----------------- Modified 4/01 By Saul Kravitz Still 100% PD Modified to run on Compaq Alpha hardware. ----------------- Modified 07/2002 By Ralph Giles Still 100% public domain modified for use with stdint types, autoconf code cleanup, removed attribution comments switched SHA1Final() argument order for consistency use SHA1_ prefix for public api move public api to sha1.h */ /* Test Vectors (from FIPS PUB 180-1) "abc" A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1 A million repetitions of "a" 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F */ /* #define SHA1HANDSOFF */ #include #include /* make sure the stdint.h types are available */ #include "ostypes.h" #include "sha1.h" static uint32_t host_to_be(uint32_t i); static void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64]); #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) /* blk0() and blk() perform the initial expand. */ /* I got the idea of expanding during the round function from SSLeay */ #define blk0(i) (block->l[i] = host_to_be(block->l[i])) #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ ^block->l[(i+2)&15]^block->l[i&15],1)) /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); #ifdef VERBOSE /* SAK */ void SHAPrintContext(SHA1_CTX *context, char *msg){ printf("%s (%d,%d) %x %x %x %x %x\n", msg, context->count[0], context->count[1], context->state[0], context->state[1], context->state[2], context->state[3], context->state[4]); } #endif /* VERBOSE */ static uint32_t host_to_be(uint32_t i) { #define le_to_be(i) ((rol((i),24) & 0xFF00FF00) | (rol((i),8) & 0x00FF00FF)) #if defined(__BIG_ENDIAN__) || \ (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) return i; #elif defined(__LITTLE_ENDIAN__) || \ (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) return le_to_be(i); #else /* fallback to run-time check */ static const union { uint32_t u; unsigned char c; } check = {1}; return check.c ? le_to_be(i) : i; #endif } /* Hash a single 512-bit block. This is the core of the algorithm. */ static void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64]) { uint32_t a, b, c, d, e; typedef union { uint8_t c[64]; uint32_t l[16]; } CHAR64LONG16; CHAR64LONG16* block; #ifdef SHA1HANDSOFF static uint8_t workspace[64]; block = (CHAR64LONG16*)workspace; memcpy(block, buffer, 64); #else block = (CHAR64LONG16*)buffer; #endif /* Copy context->state[] to working vars */ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; /* 4 rounds of 20 operations each. Loop unrolled. */ R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Wipe variables */ a = b = c = d = e = 0; } /* SHA1Init - Initialize new context */ void SHA1_Init(SHA1_CTX* context) { /* SHA1 initialization constants */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } /* Run your data through this. */ void SHA1_Update(SHA1_CTX* context, const uint8_t* data, const size_t len) { size_t i, j; #ifdef VERBOSE SHAPrintContext(context, "before"); #endif j = (context->count[0] >> 3) & 63; if ((context->count[0] += len << 3) < (len << 3)) context->count[1]++; context->count[1] += (len >> 29); if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64-j)); SHA1_Transform(context->state, context->buffer); for ( ; i + 63 < len; i += 64) { SHA1_Transform(context->state, data + i); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); #ifdef VERBOSE SHAPrintContext(context, "after "); #endif } /* Add padding and return the message digest. */ void SHA1_Final(SHA1_CTX* context, uint8_t digest[SHA1_DIGEST_SIZE]) { uint32_t i; uint8_t finalcount[8]; for (i = 0; i < 8; i++) { finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ } SHA1_Update(context, (uint8_t *)"\200", 1); while ((context->count[0] & 504) != 448) { SHA1_Update(context, (uint8_t *)"\0", 1); } SHA1_Update(context, finalcount, 8); /* Should cause a SHA1_Transform() */ for (i = 0; i < SHA1_DIGEST_SIZE; i++) { digest[i] = (uint8_t) ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); } /* Wipe variables */ i = 0; memset(context->buffer, 0, 64); memset(context->state, 0, 20); memset(context->count, 0, 8); memset(finalcount, 0, 8); /* SWR */ #ifdef SHA1HANDSOFF /* make SHA1Transform overwrite its own static vars */ SHA1_Transform(context->state, context->buffer); #endif } /*************************************************************/ #if 0 int main(int argc, char** argv) { int i, j; SHA1_CTX context; unsigned char digest[SHA1_DIGEST_SIZE], buffer[16384]; FILE* file; if (argc > 2) { puts("Public domain SHA-1 implementation - by Steve Reid "); puts("Modified for 16 bit environments 7/98 - by James H. Brown "); /* JHB */ puts("Produces the SHA-1 hash of a file, or stdin if no file is specified."); return(0); } if (argc < 2) { file = stdin; } else { if (!(file = fopen(argv[1], "rb"))) { fputs("Unable to open file.", stderr); return(-1); } } SHA1_Init(&context); while (!feof(file)) { /* note: what if ferror(file) */ i = fread(buffer, 1, 16384, file); SHA1_Update(&context, buffer, i); } SHA1_Final(&context, digest); fclose(file); for (i = 0; i < SHA1_DIGEST_SIZE/4; i++) { for (j = 0; j < 4; j++) { printf("%02X", digest[i*4+j]); } putchar(' '); } putchar('\n'); return(0); /* JHB */ } #endif /* self test */ #ifdef TEST static char *test_data[] = { "abc", "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", "A million repetitions of 'a'"}; static char *test_results[] = { "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D", "84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1", "34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F"}; void digest_to_hex(const uint8_t digest[SHA1_DIGEST_SIZE], char *output) { int i,j; char *c = output; for (i = 0; i < SHA1_DIGEST_SIZE/4; i++) { for (j = 0; j < 4; j++) { sprintf(c,"%02X", digest[i*4+j]); c += 2; } sprintf(c, " "); c += 1; } *(c - 1) = '\0'; } int main(int argc, char** argv) { int k; SHA1_CTX context; uint8_t digest[20]; char output[80]; fprintf(stdout, "verifying SHA-1 implementation... "); for (k = 0; k < 2; k++){ SHA1_Init(&context); SHA1_Update(&context, (uint8_t*)test_data[k], strlen(test_data[k])); SHA1_Final(&context, digest); digest_to_hex(digest, output); if (strcmp(output, test_results[k])) { fprintf(stdout, "FAIL\n"); fprintf(stderr,"* hash of \"%s\" incorrect:\n", test_data[k]); fprintf(stderr,"\t%s returned\n", output); fprintf(stderr,"\t%s is correct\n", test_results[k]); return (1); } } /* million 'a' vector we feed separately */ SHA1_Init(&context); for (k = 0; k < 1000000; k++) SHA1_Update(&context, (uint8_t*)"a", 1); SHA1_Final(&context, digest); digest_to_hex(digest, output); if (strcmp(output, test_results[2])) { fprintf(stdout, "FAIL\n"); fprintf(stderr,"* hash of \"%s\" incorrect:\n", test_data[2]); fprintf(stderr,"\t%s returned\n", output); fprintf(stderr,"\t%s is correct\n", test_results[2]); return (1); } /* success */ fprintf(stdout, "ok\n"); return(0); } #endif /* TEST */ libstrophe-0.8.8/src/sha1.h000066400000000000000000000012161256471717200155120ustar00rootroot00000000000000/* public api for steve reid's public domain SHA-1 implementation */ /* this file is in the public domain */ /** @file * SHA-1 hash API. */ #ifndef __SHA1_H #define __SHA1_H #ifdef __cplusplus extern "C" { #endif /* make sure the stdint.h types are available */ #include "ostypes.h" typedef struct { uint32_t state[5]; uint32_t count[2]; uint8_t buffer[64]; } SHA1_CTX; #define SHA1_DIGEST_SIZE 20 void SHA1_Init(SHA1_CTX* context); void SHA1_Update(SHA1_CTX* context, const uint8_t* data, const size_t len); void SHA1_Final(SHA1_CTX* context, uint8_t digest[SHA1_DIGEST_SIZE]); #ifdef __cplusplus } #endif #endif /* __SHA1_H */ libstrophe-0.8.8/src/snprintf.c000066400000000000000000000457221256471717200165260ustar00rootroot00000000000000/* * Copyright Patrick Powell 1995 * This code is based on code written by Patrick Powell (papowell@astart.com) * It may be used for any purpose as long as this notice remains intact * on all source code distributions */ /************************************************************** * Original: * Patrick Powell Tue Apr 11 09:48:21 PDT 1995 * A bombproof version of doprnt (dopr) included. * Sigh. This sort of thing is always nasty do deal with. Note that * the version here does not include floating point... * * snprintf() is used instead of sprintf() as it does limit checks * for string length. This covers a nasty loophole. * * The other functions are there to prevent NULL pointers from * causing nast effects. * * More Recently: * Brandon Long 9/15/96 for mutt 0.43 * This was ugly. It is still ugly. I opted out of floating point * numbers, but the formatter understands just about everything * from the normal C string format, at least as far as I can tell from * the Solaris 2.5 printf(3S) man page. * * Brandon Long 10/22/97 for mutt 0.87.1 * Ok, added some minimal floating point support, which means this * probably requires libm on most operating systems. Don't yet * support the exponent (e,E) and sigfig (g,G). Also, fmtint() * was pretty badly broken, it just wasn't being exercised in ways * which showed it, so that's been fixed. Also, formated the code * to mutt conventions, and removed dead code left over from the * original. Also, there is now a builtin-test, just compile with: * gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm * and run snprintf for results. * * Thomas Roessler 01/27/98 for mutt 0.89i * The PGP code was using unsigned hexadecimal formats. * Unfortunately, unsigned formats simply didn't work. * * Michael Elkins 03/05/98 for mutt 0.90.8 * The original code assumed that both snprintf() and vsnprintf() were * missing. Some systems only have snprintf() but not vsnprintf(), so * the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF. * * Andrew Tridgell (tridge@samba.org) Oct 1998 * fixed handling of %.0f * added test for HAVE_LONG_DOUBLE * * Russ Allbery 2000-08-26 * fixed return value to comply with C99 * fixed handling of snprintf(NULL, ...) * **************************************************************/ /** @file * A snprintf implementation. */ /* JAM: we don't need this - #include "config.h" */ /* JAM: changed declarations to xmpp_snprintf and xmpp_vsnprintf to avoid namespace collision. */ #if !defined(HAVE_SNPRINTF) || !defined(HAVE_VSNPRINTF) #include #include #include /* Define this as a fall through, HAVE_STDARG_H is probably already set */ #define HAVE_VARARGS_H #define HAVE_STDARG_H /* JAM: set always */ /* varargs declarations: */ #if defined(HAVE_STDARG_H) # include # define HAVE_STDARGS /* let's hope that works everywhere (mj) */ # define VA_LOCAL_DECL va_list ap # define VA_START(f) va_start(ap, f) # define VA_SHIFT(v,t) ; /* no-op for ANSI */ # define VA_END va_end(ap) #else # if defined(HAVE_VARARGS_H) # include # undef HAVE_STDARGS # define VA_LOCAL_DECL va_list ap # define VA_START(f) va_start(ap) /* f is ignored! */ # define VA_SHIFT(v,t) v = va_arg(ap,t) # define VA_END va_end(ap) # else /*XX ** NO VARARGS ** XX*/ # endif #endif #ifdef HAVE_LONG_DOUBLE #define LDOUBLE long double #else #define LDOUBLE double #endif int xmpp_snprintf (char *str, size_t count, const char *fmt, ...); int xmpp_vsnprintf (char *str, size_t count, const char *fmt, va_list arg); static int dopr (char *buffer, size_t maxlen, const char *format, va_list args); static int fmtstr (char *buffer, size_t *currlen, size_t maxlen, char *value, int flags, int min, int max); static int fmtint (char *buffer, size_t *currlen, size_t maxlen, long value, int base, int min, int max, int flags); static int fmtfp (char *buffer, size_t *currlen, size_t maxlen, LDOUBLE fvalue, int min, int max, int flags); static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c ); /* * dopr(): poor man's version of doprintf */ /* format read states */ #define DP_S_DEFAULT 0 #define DP_S_FLAGS 1 #define DP_S_MIN 2 #define DP_S_DOT 3 #define DP_S_MAX 4 #define DP_S_MOD 5 #define DP_S_CONV 6 #define DP_S_DONE 7 /* format flags - Bits */ #define DP_F_MINUS (1 << 0) #define DP_F_PLUS (1 << 1) #define DP_F_SPACE (1 << 2) #define DP_F_NUM (1 << 3) #define DP_F_ZERO (1 << 4) #define DP_F_UP (1 << 5) #define DP_F_UNSIGNED (1 << 6) /* Conversion Flags */ #define DP_C_SHORT 1 #define DP_C_LONG 2 #define DP_C_LDOUBLE 3 #define char_to_int(p) (p - '0') #define MAX(p,q) ((p >= q) ? p : q) #define MIN(p,q) ((p <= q) ? p : q) static int dopr (char *buffer, size_t maxlen, const char *format, va_list args) { char ch; long value; LDOUBLE fvalue; char *strvalue; int min; int max; int state; int flags; int cflags; int total; size_t currlen; state = DP_S_DEFAULT; currlen = flags = cflags = min = 0; max = -1; ch = *format++; total = 0; while (state != DP_S_DONE) { if (ch == '\0') state = DP_S_DONE; switch(state) { case DP_S_DEFAULT: if (ch == '%') state = DP_S_FLAGS; else total += dopr_outch (buffer, &currlen, maxlen, ch); ch = *format++; break; case DP_S_FLAGS: switch (ch) { case '-': flags |= DP_F_MINUS; ch = *format++; break; case '+': flags |= DP_F_PLUS; ch = *format++; break; case ' ': flags |= DP_F_SPACE; ch = *format++; break; case '#': flags |= DP_F_NUM; ch = *format++; break; case '0': flags |= DP_F_ZERO; ch = *format++; break; default: state = DP_S_MIN; break; } break; case DP_S_MIN: if (isdigit(ch)) { min = 10*min + char_to_int (ch); ch = *format++; } else if (ch == '*') { min = va_arg (args, int); ch = *format++; state = DP_S_DOT; } else state = DP_S_DOT; break; case DP_S_DOT: if (ch == '.') { state = DP_S_MAX; ch = *format++; } else state = DP_S_MOD; break; case DP_S_MAX: if (isdigit(ch)) { if (max < 0) max = 0; max = 10*max + char_to_int (ch); ch = *format++; } else if (ch == '*') { max = va_arg (args, int); ch = *format++; state = DP_S_MOD; } else state = DP_S_MOD; break; case DP_S_MOD: /* Currently, we don't support Long Long, bummer */ switch (ch) { case 'h': cflags = DP_C_SHORT; ch = *format++; break; case 'l': cflags = DP_C_LONG; ch = *format++; break; case 'L': cflags = DP_C_LDOUBLE; ch = *format++; break; default: break; } state = DP_S_CONV; break; case DP_S_CONV: switch (ch) { case 'd': case 'i': if (cflags == DP_C_SHORT) value = va_arg (args, int); else if (cflags == DP_C_LONG) value = va_arg (args, long int); else value = va_arg (args, int); total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags); break; case 'o': flags |= DP_F_UNSIGNED; if (cflags == DP_C_SHORT) value = va_arg (args, int); else if (cflags == DP_C_LONG) value = va_arg (args, unsigned long int); else value = va_arg (args, unsigned int); total += fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags); break; case 'u': flags |= DP_F_UNSIGNED; if (cflags == DP_C_SHORT) value = va_arg (args, int); else if (cflags == DP_C_LONG) value = va_arg (args, unsigned long int); else value = va_arg (args, unsigned int); total += fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags); break; case 'X': flags |= DP_F_UP; case 'x': flags |= DP_F_UNSIGNED; if (cflags == DP_C_SHORT) value = va_arg (args, int); else if (cflags == DP_C_LONG) value = va_arg (args, unsigned long int); else value = va_arg (args, unsigned int); total += fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags); break; case 'f': if (cflags == DP_C_LDOUBLE) fvalue = va_arg (args, LDOUBLE); else fvalue = va_arg (args, double); /* um, floating point? */ total += fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags); break; case 'E': flags |= DP_F_UP; case 'e': if (cflags == DP_C_LDOUBLE) fvalue = va_arg (args, LDOUBLE); else fvalue = va_arg (args, double); break; case 'G': flags |= DP_F_UP; case 'g': if (cflags == DP_C_LDOUBLE) fvalue = va_arg (args, LDOUBLE); else fvalue = va_arg (args, double); break; case 'c': total += dopr_outch (buffer, &currlen, maxlen, va_arg (args, int)); break; case 's': strvalue = va_arg (args, char *); total += fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max); break; case 'p': strvalue = va_arg (args, void *); total += fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min, max, flags); break; case 'n': if (cflags == DP_C_SHORT) { short int *num; num = va_arg (args, short int *); *num = currlen; } else if (cflags == DP_C_LONG) { long int *num; num = va_arg (args, long int *); *num = currlen; } else { int *num; num = va_arg (args, int *); *num = currlen; } break; case '%': total += dopr_outch (buffer, &currlen, maxlen, ch); break; case 'w': /* not supported yet, treat as next char */ ch = *format++; break; default: /* Unknown, skip */ break; } ch = *format++; state = DP_S_DEFAULT; flags = cflags = min = 0; max = -1; break; case DP_S_DONE: break; default: /* hmm? */ break; /* some picky compilers need this */ } } if (buffer != NULL) { if (currlen < maxlen - 1) buffer[currlen] = '\0'; else buffer[maxlen - 1] = '\0'; } return total; } static int fmtstr (char *buffer, size_t *currlen, size_t maxlen, char *value, int flags, int min, int max) { int padlen, strln; /* amount to pad */ int cnt = 0; int total = 0; if (value == 0) { value = ""; } for (strln = 0; value[strln]; ++strln); /* strlen */ if (max >= 0 && max < strln) strln = max; padlen = min - strln; if (padlen < 0) padlen = 0; if (flags & DP_F_MINUS) padlen = -padlen; /* Left Justify */ while (padlen > 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); --padlen; } while (*value && ((max < 0) || (cnt < max))) { total += dopr_outch (buffer, currlen, maxlen, *value++); ++cnt; } while (padlen < 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); ++padlen; } return total; } /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */ static int fmtint (char *buffer, size_t *currlen, size_t maxlen, long value, int base, int min, int max, int flags) { int signvalue = 0; unsigned long uvalue; char convert[20]; int place = 0; int spadlen = 0; /* amount to space pad */ int zpadlen = 0; /* amount to zero pad */ int caps = 0; int total = 0; if (max < 0) max = 0; uvalue = value; if(!(flags & DP_F_UNSIGNED)) { if( value < 0 ) { signvalue = '-'; uvalue = -value; } else if (flags & DP_F_PLUS) /* Do a sign (+/i) */ signvalue = '+'; else if (flags & DP_F_SPACE) signvalue = ' '; } if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */ do { convert[place++] = (caps? "0123456789ABCDEF":"0123456789abcdef") [uvalue % (unsigned)base ]; uvalue = (uvalue / (unsigned)base ); } while(uvalue && (place < 20)); if (place == 20) place--; convert[place] = 0; zpadlen = max - place; spadlen = min - MAX (max, place) - (signvalue ? 1 : 0); if (zpadlen < 0) zpadlen = 0; if (spadlen < 0) spadlen = 0; if (flags & DP_F_ZERO) { zpadlen = MAX(zpadlen, spadlen); spadlen = 0; } if (flags & DP_F_MINUS) spadlen = -spadlen; /* Left Justifty */ #ifdef DEBUG_SNPRINTF dprint (1, (debugfile, "zpad: %d, spad: %d, min: %d, max: %d, place: %d\n", zpadlen, spadlen, min, max, place)); #endif /* Spaces */ while (spadlen > 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); --spadlen; } /* Sign */ if (signvalue) total += dopr_outch (buffer, currlen, maxlen, signvalue); /* Zeros */ if (zpadlen > 0) { while (zpadlen > 0) { total += dopr_outch (buffer, currlen, maxlen, '0'); --zpadlen; } } /* Digits */ while (place > 0) total += dopr_outch (buffer, currlen, maxlen, convert[--place]); /* Left Justified spaces */ while (spadlen < 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); ++spadlen; } return total; } static LDOUBLE abs_val (LDOUBLE value) { LDOUBLE result = value; if (value < 0) result = -value; return result; } static LDOUBLE _snp_pow10 (int exp) { LDOUBLE result = 1; while (exp) { result *= 10; exp--; } return result; } static long _snp_round (LDOUBLE value) { long intpart; intpart = value; value = value - intpart; if (value >= 0.5) intpart++; return intpart; } static int fmtfp (char *buffer, size_t *currlen, size_t maxlen, LDOUBLE fvalue, int min, int max, int flags) { int signvalue = 0; LDOUBLE ufvalue; char iconvert[20]; char fconvert[20]; int iplace = 0; int fplace = 0; int padlen = 0; /* amount to pad */ int zpadlen = 0; int caps = 0; int total = 0; long intpart; long fracpart; /* * AIX manpage says the default is 0, but Solaris says the default * is 6, and sprintf on AIX defaults to 6 */ if (max < 0) max = 6; ufvalue = abs_val (fvalue); if (fvalue < 0) signvalue = '-'; else if (flags & DP_F_PLUS) /* Do a sign (+/i) */ signvalue = '+'; else if (flags & DP_F_SPACE) signvalue = ' '; #if 0 if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */ #endif intpart = ufvalue; /* * Sorry, we only support 9 digits past the decimal because of our * conversion method */ if (max > 9) max = 9; /* We "cheat" by converting the fractional part to integer by * multiplying by a factor of 10 */ fracpart = _snp_round ((_snp_pow10 (max)) * (ufvalue - intpart)); if (fracpart >= _snp_pow10 (max)) { intpart++; fracpart -= _snp_pow10 (max); } #ifdef DEBUG_SNPRINTF dprint (1, (debugfile, "fmtfp: %f =? %d.%d\n", fvalue, intpart, fracpart)); #endif /* Convert integer part */ do { iconvert[iplace++] = (caps? "0123456789ABCDEF":"0123456789abcdef")[intpart % 10]; intpart = (intpart / 10); } while(intpart && (iplace < 20)); if (iplace == 20) iplace--; iconvert[iplace] = 0; /* Convert fractional part */ do { fconvert[fplace++] = (caps? "0123456789ABCDEF":"0123456789abcdef")[fracpart % 10]; fracpart = (fracpart / 10); } while(fracpart && (fplace < 20)); if (fplace == 20) fplace--; fconvert[fplace] = 0; /* -1 for decimal point, another -1 if we are printing a sign */ padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0); zpadlen = max - fplace; if (zpadlen < 0) zpadlen = 0; if (padlen < 0) padlen = 0; if (flags & DP_F_MINUS) padlen = -padlen; /* Left Justifty */ if ((flags & DP_F_ZERO) && (padlen > 0)) { if (signvalue) { total += dopr_outch (buffer, currlen, maxlen, signvalue); --padlen; signvalue = 0; } while (padlen > 0) { total += dopr_outch (buffer, currlen, maxlen, '0'); --padlen; } } while (padlen > 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); --padlen; } if (signvalue) total += dopr_outch (buffer, currlen, maxlen, signvalue); while (iplace > 0) total += dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]); /* * Decimal point. This should probably use locale to find the correct * char to print out. */ if (max > 0) { total += dopr_outch (buffer, currlen, maxlen, '.'); while (fplace > 0) total += dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]); } while (zpadlen > 0) { total += dopr_outch (buffer, currlen, maxlen, '0'); --zpadlen; } while (padlen < 0) { total += dopr_outch (buffer, currlen, maxlen, ' '); ++padlen; } return total; } static int dopr_outch (char *buffer, size_t *currlen, size_t maxlen, char c) { if (*currlen + 1 < maxlen) buffer[(*currlen)++] = c; return 1; } #ifndef HAVE_VSNPRINTF int xmpp_vsnprintf (char *str, size_t count, const char *fmt, va_list args) { if (str != NULL) str[0] = 0; return dopr(str, count, fmt, args); } #endif /* !HAVE_VSNPRINTF */ #ifndef HAVE_SNPRINTF /* VARARGS3 */ #ifdef HAVE_STDARGS int xmpp_snprintf (char *str,size_t count,const char *fmt,...) #else int xmpp_snprintf (va_alist) va_dcl #endif { #ifndef HAVE_STDARGS char *str; size_t count; char *fmt; #endif VA_LOCAL_DECL; int total; VA_START (fmt); VA_SHIFT (str, char *); VA_SHIFT (count, size_t ); VA_SHIFT (fmt, char *); total = xmpp_vsnprintf(str, count, fmt, ap); VA_END; return total; } #endif /* !HAVE_SNPRINTF */ #ifdef TEST_SNPRINTF #ifndef LONG_STRING #define LONG_STRING 1024 #endif int main (void) { char buf1[LONG_STRING]; char buf2[LONG_STRING]; char *fp_fmt[] = { "%-1.5f", "%1.5f", "%123.9f", "%10.5f", "% 10.5f", "%+22.9f", "%+4.9f", "%01.3f", "%4f", "%3.1f", "%3.2f", "%.0f", "%.1f", NULL }; double fp_nums[] = { -1.5, 134.21, 91340.2, 341.1234, 0203.9, 0.96, 0.996, 0.9996, 1.996, 4.136, 0}; char *int_fmt[] = { "%-1.5d", "%1.5d", "%123.9d", "%5.5d", "%10.5d", "% 10.5d", "%+22.33d", "%01.3d", "%4d", NULL }; long int_nums[] = { -1, 134, 91340, 341, 0203, 0}; int x, y; int fail = 0; int num = 0; printf ("Testing xmpp_snprintf format codes against system sprintf...\n"); for (x = 0; fp_fmt[x] != NULL ; x++) for (y = 0; fp_nums[y] != 0 ; y++) { xmpp_snprintf (buf1, sizeof (buf1), fp_fmt[x], fp_nums[y]); sprintf (buf2, fp_fmt[x], fp_nums[y]); if (strcmp (buf1, buf2)) { printf("xmpp_snprintf doesn't match Format: %s\n\txmpp_snprintf = %s\n\tsprintf = %s\n", fp_fmt[x], buf1, buf2); fail++; } num++; } for (x = 0; int_fmt[x] != NULL ; x++) for (y = 0; int_nums[y] != 0 ; y++) { xmpp_snprintf (buf1, sizeof (buf1), int_fmt[x], int_nums[y]); sprintf (buf2, int_fmt[x], int_nums[y]); if (strcmp (buf1, buf2)) { printf("xmpp_snprintf doesn't match Format: %s\n\txmpp_snprintf = %s\n\tsprintf = %s\n", int_fmt[x], buf1, buf2); fail++; } num++; } printf ("%d tests failed out of %d.\n", fail, num); } #endif /* SNPRINTF_TEST */ #endif /* !HAVE_SNPRINTF */ libstrophe-0.8.8/src/sock.c000066400000000000000000000460771256471717200156260ustar00rootroot00000000000000/* sock.c ** strophe XMPP client library -- socket abstraction implementation ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Socket abstraction. */ #include #include #include #include #ifdef _WIN32 #include #include #include #include #define snprintf _snprintf #else #include #include #include #include #include #include #include #ifdef HAVE_ARPA_NAMESER_COMPAT_H #include #endif #include #endif #include "sock.h" void sock_initialize(void) { #ifdef _WIN32 WSADATA wsad; WSAStartup(0x0101, &wsad); #endif } void sock_shutdown(void) { #ifdef _WIN32 WSACleanup(); #endif } int sock_error(void) { #ifdef _WIN32 return WSAGetLastError(); #else return errno; #endif } static int _in_progress(int error) { #ifdef _WIN32 return (error == WSAEWOULDBLOCK || error == WSAEINPROGRESS); #else return (errno == EINPROGRESS); #endif } sock_t sock_connect(const char * const host, const unsigned int port) { sock_t sock; char service[6]; struct addrinfo *res, *ainfo, hints; int err; sock = -1; snprintf(service, 6, "%u", port); memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_INET; hints.ai_protocol = IPPROTO_TCP; hints.ai_socktype = SOCK_STREAM; if ((err = getaddrinfo(host, service, &hints, &res)) != 0) return -1; ainfo = res; while (ainfo) { if ((sock = socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol)) >= 0) { sock_set_nonblocking(sock); err = connect(sock, ainfo->ai_addr, ainfo->ai_addrlen); if ((err == 0) || (err < 0 && _in_progress(sock_error()))) break; } ainfo = ainfo->ai_next; } if (res) freeaddrinfo(res); return sock; } int sock_close(const sock_t sock) { #ifdef _WIN32 return closesocket(sock); #else return close(sock); #endif } int sock_set_blocking(const sock_t sock) { #ifdef _WIN32 u_long block = 0; return ioctlsocket(sock, FIONBIO, &block); #else return fcntl(sock, F_SETFL, 0); #endif } int sock_set_nonblocking(const sock_t sock) { #ifdef _WIN32 u_long nonblock = 1; return ioctlsocket(sock, FIONBIO, &nonblock); #else return fcntl(sock, F_SETFL, O_NONBLOCK); #endif } int sock_read(const sock_t sock, void * const buff, const size_t len) { return recv(sock, buff, len, 0); } int sock_write(const sock_t sock, const void * const buff, const size_t len) { return send(sock, buff, len, 0); } int sock_is_recoverable(const int error) { #ifdef _WIN32 return (error == WSAEINTR || error == WSAEWOULDBLOCK || error == WSAEINPROGRESS); #else return (error == EAGAIN || error == EINTR); #endif } int sock_connect_error(const sock_t sock) { struct sockaddr sa; unsigned len; char temp; sa.sa_family = AF_INET; len = sizeof(sa); /* we don't actually care about the peer name, we're just checking if * we're connected or not */ if (getpeername(sock, &sa, &len) == 0) { return 0; } /* it's possible that the error wasn't ENOTCONN, so if it wasn't, * return that */ #ifdef _WIN32 if (sock_error() != WSAENOTCONN) return sock_error(); #else if (sock_error() != ENOTCONN) return sock_error(); #endif /* load the correct error into errno through error slippage */ recv(sock, &temp, 1, 0); return sock_error(); } struct dnsquery_header { unsigned short id; unsigned char qr; unsigned char opcode; unsigned char aa; unsigned char tc; unsigned char rd; unsigned char ra; unsigned char z; unsigned char rcode; unsigned short qdcount; unsigned short ancount; unsigned short nscount; unsigned short arcount; }; struct dnsquery_question { char qname[1024]; unsigned short qtype; unsigned short qclass; }; struct dnsquery_srvrdata { unsigned short priority; unsigned short weight; unsigned short port; char target[1024]; }; struct dnsquery_resourcerecord { char name[1024]; unsigned short type; unsigned short _class; unsigned int ttl; unsigned short rdlength; struct dnsquery_srvrdata rdata; }; void netbuf_add_32bitnum(unsigned char *buf, int buflen, int *offset, unsigned int num) { unsigned char *start = buf + *offset; unsigned char *p = start; /* assuming big endian */ *p++ = (num >> 24) & 0xff; *p++ = (num >> 16) & 0xff; *p++ = (num >> 8) & 0xff; *p++ = (num) & 0xff; *offset += 4; } void netbuf_get_32bitnum(unsigned char *buf, int buflen, int *offset, unsigned int *num) { unsigned char *start = buf + *offset; unsigned char *p = start; *num = 0; /* assuming big endian */ *num |= (*p++) << 24; *num |= (*p++) << 16; *num |= (*p++) << 8; *num |= (*p++); *offset += 4; } void netbuf_add_16bitnum(unsigned char *buf, int buflen, int *offset, unsigned short num) { unsigned char *start = buf + *offset; unsigned char *p = start; /* assuming big endian */ *p++ = (num >> 8) & 0xff; *p++ = (num) & 0xff; *offset += 2; } void netbuf_get_16bitnum(unsigned char *buf, int buflen, int *offset, unsigned short *num) { unsigned char *start = buf + *offset; unsigned char *p = start; *num = 0; /* assuming big endian */ *num |= (*p++) << 8; *num |= (*p++); *offset += 2; } void netbuf_add_domain_name(unsigned char *buf, int buflen, int *offset, char *name) { unsigned char *start = buf + *offset; unsigned char *p = start; unsigned char *wordstart, *wordend; wordstart = (unsigned char *)name; while (*wordstart) { int len; wordend = wordstart; while (*wordend && *wordend != '.') { wordend++; } len = (int)(wordend - wordstart); if (len > 0x3F) { len = 0x3F; } *p++ = len; while (wordstart != wordend) { *p++ = *wordstart++; } if (*wordstart == '.') { wordstart++; } } *p++ = '\0'; *offset += p - start; } int calc_domain_name_size(unsigned char *buf, int buflen, int offset) { unsigned char *p = buf + offset; int len = 0; while (*p) { if ((*p & 0xC0) == 0xC0) { int newoffset = 0; newoffset |= (*p++ & 0x3F) << 8; newoffset |= *p; p = buf + newoffset; } else { if (len) { len += 1; } len += *p; p += *p + 1; } } return len; } int netbuf_get_domain_name(unsigned char *buf, int buflen, int *offset, char *namebuf, int namebuflen) { unsigned char *start = buf + *offset; unsigned char *p, *p2; int *curroffset = offset; int len = 0; *namebuf = '\0'; /* measure length */ p = start; while (*p) { if ((*p & 0xC0) == 0xC0) { int newoffset = 0; newoffset |= (*p++ & 0x3F) << 8; newoffset |= *p++; p = buf + newoffset; } else { len += *p; p += *p + 1; } } if (namebuflen < len) { return len; } /* actually copy in name */ p = start; p2 = (unsigned char *)namebuf; while (*p) { if ((*p & 0xC0) == 0xC0) { int newoffset = 0; newoffset |= (*p++ & 0x3F) << 8; newoffset |= *p++; if (curroffset) { *curroffset += (int)(p - start); curroffset = NULL; } p = buf + newoffset; } else { int i, partlen; if (*namebuf != '\0') { *p2++ = '.'; } partlen = *p++; for (i=0; i < partlen; i++) { *p2++ = *p++; } } } if (curroffset) { p++; *curroffset += (int)(p - start); curroffset = NULL; } *p2 = '\0'; return 0; } void netbuf_add_dnsquery_header(unsigned char *buf, int buflen, int *offset, struct dnsquery_header *header) { unsigned char *p; netbuf_add_16bitnum(buf, buflen, offset, header->id); p = buf + *offset; *p++ = ((header->qr & 0x01) << 7) | ((header->opcode & 0x0F) << 3) | ((header->aa & 0x01) << 2) | ((header->tc & 0x01) << 1) | ((header->rd & 0x01)); *p++ = ((header->ra & 0x01) << 7) | ((header->z & 0x07) << 4) | ((header->rcode & 0x0F)); *offset += 2; netbuf_add_16bitnum(buf, buflen, offset, header->qdcount); netbuf_add_16bitnum(buf, buflen, offset, header->ancount); netbuf_add_16bitnum(buf, buflen, offset, header->nscount); netbuf_add_16bitnum(buf, buflen, offset, header->arcount); } void netbuf_get_dnsquery_header(unsigned char *buf, int buflen, int *offset, struct dnsquery_header *header) { unsigned char *p; netbuf_get_16bitnum(buf, buflen, offset, &(header->id)); p = buf + *offset; header->qr = (*p >> 7) & 0x01; header->opcode = (*p >> 3) & 0x0F; header->aa = (*p >> 2) & 0x01; header->tc = (*p >> 1) & 0x01; header->rd = (*p) & 0x01; p++; header->ra = (*p >> 7) & 0x01; header->z = (*p >> 4) & 0x07; header->rcode = (*p) & 0x0F; p++; *offset += 2; netbuf_get_16bitnum(buf, buflen, offset, &(header->qdcount)); netbuf_get_16bitnum(buf, buflen, offset, &(header->ancount)); netbuf_get_16bitnum(buf, buflen, offset, &(header->nscount)); netbuf_get_16bitnum(buf, buflen, offset, &(header->arcount)); } void netbuf_add_dnsquery_question(unsigned char *buf, int buflen, int *offset, struct dnsquery_question *question) { netbuf_add_domain_name(buf, buflen, offset, question->qname); netbuf_add_16bitnum(buf, buflen, offset, question->qtype); netbuf_add_16bitnum(buf, buflen, offset, question->qclass); } void netbuf_get_dnsquery_question(unsigned char *buf, int buflen, int *offset, struct dnsquery_question *question) { netbuf_get_domain_name(buf, buflen, offset, question->qname, 1024); netbuf_get_16bitnum(buf, buflen, offset, &(question->qtype)); netbuf_get_16bitnum(buf, buflen, offset, &(question->qclass)); } void netbuf_get_dnsquery_srvrdata(unsigned char *buf, int buflen, int *offset, struct dnsquery_srvrdata *srvrdata) { netbuf_get_16bitnum(buf, buflen, offset, &(srvrdata->priority)); netbuf_get_16bitnum(buf, buflen, offset, &(srvrdata->weight)); netbuf_get_16bitnum(buf, buflen, offset, &(srvrdata->port)); netbuf_get_domain_name(buf, buflen, offset, srvrdata->target, 1024); } void netbuf_get_dnsquery_resourcerecord(unsigned char *buf, int buflen, int *offset, struct dnsquery_resourcerecord *rr) { netbuf_get_domain_name(buf, buflen, offset, rr->name, 1024); netbuf_get_16bitnum(buf, buflen, offset, &(rr->type)); netbuf_get_16bitnum(buf, buflen, offset, &(rr->_class)); netbuf_get_32bitnum(buf, buflen, offset, &(rr->ttl)); netbuf_get_16bitnum(buf, buflen, offset, &(rr->rdlength)); if (rr->type == 33) /* SRV */ { int newoffset = *offset; netbuf_get_dnsquery_srvrdata(buf, buflen, &newoffset, &(rr->rdata)); } *offset += rr->rdlength; } int sock_srv_lookup(const char *service, const char *proto, const char *domain, char *resulttarget, int resulttargetlength, int *resultport) { int set = 0; char fulldomain[2048]; snprintf(fulldomain, 2048, "_%s._%s.%s", service, proto, domain); #ifdef _WIN32 /* try using dnsapi first */ if (!set) { HINSTANCE hdnsapi = NULL; DNS_STATUS (WINAPI * pDnsQuery_A)(PCSTR, WORD, DWORD, PIP4_ARRAY, PDNS_RECORD*, PVOID*); void (WINAPI * pDnsRecordListFree)(PDNS_RECORD, DNS_FREE_TYPE); if (hdnsapi = LoadLibrary("dnsapi.dll")) { pDnsQuery_A = (void *)GetProcAddress(hdnsapi, "DnsQuery_A"); pDnsRecordListFree = (void *)GetProcAddress(hdnsapi, "DnsRecordListFree"); if (pDnsQuery_A && pDnsRecordListFree) { PDNS_RECORD dnsrecords = NULL; DNS_STATUS error; error = pDnsQuery_A(fulldomain, DNS_TYPE_SRV, DNS_QUERY_STANDARD, NULL, &dnsrecords, NULL); if (error == 0) { PDNS_RECORD current = dnsrecords; while (current) { if (current->wType == DNS_TYPE_SRV) { snprintf(resulttarget, resulttargetlength, "%s", current->Data.Srv.pNameTarget); *resultport = current->Data.Srv.wPort; set = 1; current = NULL; } else { current = current->pNext; } } } pDnsRecordListFree(dnsrecords, DnsFreeRecordList); } FreeLibrary(hdnsapi); } } /* if dnsapi didn't work/isn't there, try querying the dns server manually */ if (!set) { unsigned char buf[65536]; struct dnsquery_header header; struct dnsquery_question question; int offset = 0; int addrlen; sock_t sock; struct sockaddr_in dnsaddr; char dnsserverips[16][256]; int numdnsservers = 0; int j; /* Try getting the DNS server ips from GetNetworkParams() in iphlpapi first */ if (!numdnsservers) { HINSTANCE hiphlpapi = NULL; DWORD (WINAPI * pGetNetworkParams)(PFIXED_INFO, PULONG); if (hiphlpapi = LoadLibrary("Iphlpapi.dll")) { pGetNetworkParams = (void *)GetProcAddress(hiphlpapi, "GetNetworkParams"); if (pGetNetworkParams) { FIXED_INFO *fi; ULONG len; DWORD error; char buffer[65535]; len = 65535; fi = buffer; if ((error = pGetNetworkParams(fi, &len)) == ERROR_SUCCESS) { IP_ADDR_STRING *pias = &(fi->DnsServerList); while (pias && numdnsservers < 16) { strcpy(dnsserverips[numdnsservers++], pias->IpAddress.String); pias = pias->Next; } } } } FreeLibrary(hiphlpapi); } /* Next, try getting the DNS server ips from the registry */ if (!numdnsservers) { HKEY search; LONG error; error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters", 0, KEY_READ, &search); if (error != ERROR_SUCCESS) { error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\VxD\\MSTCP", 0, KEY_READ, &search); } if (error == ERROR_SUCCESS) { char name[512]; DWORD len = 512; error = RegQueryValueEx(search, "NameServer", NULL, NULL, (LPBYTE)name, &len); if (error != ERROR_SUCCESS) { error = RegQueryValueEx(search, "DhcpNameServer", NULL, NULL, (LPBYTE)name, &len); } if (error == ERROR_SUCCESS) { char *parse = "0123456789.", *start, *end; start = name; end = name; name[len] = '\0'; while (*start && numdnsservers < 16) { while (strchr(parse, *end)) { end++; } strncpy(dnsserverips[numdnsservers++], start, end - start); while (*end && !strchr(parse, *end)) { end++; } start = end; } } } RegCloseKey(search); } if (!numdnsservers) { HKEY searchlist; LONG error; error = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces", 0, KEY_READ, &searchlist); if (error == ERROR_SUCCESS) { unsigned int i; DWORD numinterfaces = 0; RegQueryInfoKey(searchlist, NULL, NULL, NULL, &numinterfaces, NULL, NULL, NULL, NULL, NULL, NULL, NULL); for (i = 0; i < numinterfaces; i++) { char name[512]; DWORD len = 512; HKEY searchentry; RegEnumKeyEx(searchlist, i, (LPTSTR)name, &len, NULL, NULL, NULL, NULL); if (RegOpenKeyEx(searchlist, name, 0, KEY_READ, &searchentry) == ERROR_SUCCESS) { if (RegQueryValueEx(searchentry, "DhcpNameServer", NULL, NULL, (LPBYTE)name, &len) == ERROR_SUCCESS) { char *parse = "0123456789.", *start, *end; start = name; end = name; name[len] = '\0'; while (*start && numdnsservers < 16) { while (strchr(parse, *end)) { end++; } strncpy(dnsserverips[numdnsservers++], start, end - start); while (*end && !strchr(parse, *end)) { end++; } start = end; } } else if (RegQueryValueEx(searchentry, "NameServer", NULL, NULL, (LPBYTE)name, &len) == ERROR_SUCCESS) { char *parse = "0123456789.", *start, *end; start = name; end = name; name[len] = '\0'; while (*start && numdnsservers < 16) { while (strchr(parse, *end)) { end++; } strncpy(dnsserverips[numdnsservers++], start, end - start); while (*end && !strchr(parse, *end)) { end++; } start = end; } } RegCloseKey(searchentry); } } RegCloseKey(searchlist); } } /* If we have a DNS server, use it */ if (numdnsservers) { ULONG nonblocking = 1; int i; int insize; memset(&header, 0, sizeof(header)); header.id = 12345; /* FIXME: Get a better id here */ header.rd = 1; header.qdcount = 1; netbuf_add_dnsquery_header(buf, 65536, &offset, &header); memset(&question, 0, sizeof(question)); strncpy(question.qname, fulldomain, 1024); question.qtype = 33; /* SRV */ question.qclass = 1; /* INTERNET! */ netbuf_add_dnsquery_question(buf, 65536, &offset, &question); insize = 0; for (i = 0; i < numdnsservers && insize <= 0; i++) { sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); ioctlsocket(sock, FIONBIO, &nonblocking); memset(&dnsaddr, 0, sizeof(dnsaddr)); dnsaddr.sin_family = AF_INET; dnsaddr.sin_port = htons(53); dnsaddr.sin_addr.s_addr = inet_addr(dnsserverips[i]); addrlen = sizeof(dnsaddr); sendto(sock, (char *)buf, offset, 0, (struct sockaddr *)&dnsaddr, addrlen); for (j = 0; j < 50; j++) { insize = recvfrom(sock, (char *)buf, 65536, 0, (struct sockaddr *)&dnsaddr, &addrlen); if (insize == SOCKET_ERROR) { if (sock_error() == WSAEWOULDBLOCK) { Sleep(100); } else { break; } } else { break; } } closesocket(sock); } offset = insize; if (offset > 0) { int len = offset; int i; struct dnsquery_header header; struct dnsquery_question question; struct dnsquery_resourcerecord rr; offset = 0; netbuf_get_dnsquery_header(buf, 65536, &offset, &header); for (i = 0; i < header.qdcount; i++) { netbuf_get_dnsquery_question(buf, 65536, &offset, &question); } for (i = 0; i < header.ancount; i++) { netbuf_get_dnsquery_resourcerecord(buf, 65536, &offset, &rr); if (rr.type == 33) { struct dnsquery_srvrdata *srvrdata = &(rr.rdata); snprintf(resulttarget, resulttargetlength, "%s", srvrdata->target); *resultport = srvrdata->port; set = 1; } } for (i = 0; i < header.ancount; i++) { netbuf_get_dnsquery_resourcerecord(buf, 65536, &offset, &rr); } } } } #else if (!set) { unsigned char buf[65535]; int len; if ((len = res_query(fulldomain, C_IN, T_SRV, buf, 65535)) > 0) { int offset; int i; struct dnsquery_header header; struct dnsquery_question question; struct dnsquery_resourcerecord rr; offset = 0; netbuf_get_dnsquery_header(buf, 65536, &offset, &header); for (i = 0; i < header.qdcount; i++) { netbuf_get_dnsquery_question(buf, 65536, &offset, &question); } for (i = 0; i < header.ancount; i++) { netbuf_get_dnsquery_resourcerecord(buf, 65536, &offset, &rr); if (rr.type == 33) { struct dnsquery_srvrdata *srvrdata = &(rr.rdata); snprintf(resulttarget, resulttargetlength, "%s", srvrdata->target); *resultport = srvrdata->port; set = 1; } } for (i = 0; i < header.ancount; i++) { netbuf_get_dnsquery_resourcerecord(buf, 65536, &offset, &rr); } } } #endif if (!set) { snprintf(resulttarget, resulttargetlength, "%s", domain); *resultport = 5222; return 0; } return 1; } libstrophe-0.8.8/src/sock.h000066400000000000000000000023641256471717200156220ustar00rootroot00000000000000/* sock.h ** strophe XMPP client library -- socket abstraction header ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Socket abstraction API. */ #ifndef __LIBSTROPHE_SOCK_H__ #define __LIBSTROPHE_SOCK_H__ #include #ifndef _WIN32 typedef int sock_t; #else #include typedef SOCKET sock_t; #endif void sock_initialize(void); void sock_shutdown(void); int sock_error(void); sock_t sock_connect(const char * const host, const unsigned int port); int sock_close(const sock_t sock); int sock_set_blocking(const sock_t sock); int sock_set_nonblocking(const sock_t sock); int sock_read(const sock_t sock, void * const buff, const size_t len); int sock_write(const sock_t sock, const void * const buff, const size_t len); int sock_is_recoverable(const int error); /* checks for an error after connect, return 0 if connect successful */ int sock_connect_error(const sock_t sock); int sock_srv_lookup(const char *service, const char *proto, const char *domain, char *resulttarget, int resulttargetlength, int *resultport); #endif /* __LIBSTROPHE_SOCK_H__ */ libstrophe-0.8.8/src/stanza.c000066400000000000000000000577351256471717200161720ustar00rootroot00000000000000/* stanza.c ** strophe XMPP client library -- XMPP stanza object and utilities ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Stanza creation and manipulation. */ /** @defgroup Stanza Stanza creation and manipulation */ #include #include #include "strophe.h" #include "common.h" #include "hash.h" #ifdef _WIN32 #define inline __inline #endif /** Create a stanza object. * This function allocates and initializes and blank stanza object. * The stanza will have a reference count of one, so the caller does not * need to clone it. * * @param ctx a Strophe context object * * @return a stanza object * * @ingroup Stanza */ xmpp_stanza_t *xmpp_stanza_new(xmpp_ctx_t *ctx) { xmpp_stanza_t *stanza; stanza = xmpp_alloc(ctx, sizeof(xmpp_stanza_t)); if (stanza != NULL) { stanza->ref = 1; stanza->ctx = ctx; stanza->type = XMPP_STANZA_UNKNOWN; stanza->prev = NULL; stanza->next = NULL; stanza->children = NULL; stanza->parent = NULL; stanza->data = NULL; stanza->attributes = NULL; } return stanza; } /** Clone a stanza object. * This function increments the reference count of the stanza object. * * @param stanza a Strophe stanza object * * @return the stanza object with it's reference count incremented * * @ingroup Stanza */ xmpp_stanza_t *xmpp_stanza_clone(xmpp_stanza_t * const stanza) { stanza->ref++; return stanza; } /** Copy a stanza and its children. * This function copies a stanza along with all its children and returns * the new stanza and children with a reference count of 1. The returned * stanza will have no parent and no siblings. This function is useful * for extracting a child stanza for inclusion in another tree. * * @param stanza a Strophe stanza object * * @return a new Strophe stanza object * * @ingroup Stanza */ xmpp_stanza_t *xmpp_stanza_copy(const xmpp_stanza_t * const stanza) { xmpp_stanza_t *copy, *child, *copychild, *tail; hash_iterator_t *iter; const char *key; void *val; copy = xmpp_stanza_new(stanza->ctx); if (!copy) goto copy_error; copy->type = stanza->type; if (stanza->data) { copy->data = xmpp_strdup(stanza->ctx, stanza->data); if (!copy->data) goto copy_error; } if (stanza->attributes) { copy->attributes = hash_new(stanza->ctx, 8, xmpp_free); if (!copy->attributes) goto copy_error; iter = hash_iter_new(stanza->attributes); if (!iter) { printf("DEBUG HERE\n"); goto copy_error; } while ((key = hash_iter_next(iter))) { val = xmpp_strdup(stanza->ctx, (char *)hash_get(stanza->attributes, key)); if (!val) goto copy_error; if (hash_add(copy->attributes, key, val)) goto copy_error; } hash_iter_release(iter); } tail = copy->children; for (child = stanza->children; child; child = child->next) { copychild = xmpp_stanza_copy(child); if (!copychild) goto copy_error; copychild->parent = copy; if (tail) { copychild->prev = tail; tail->next = copychild; } else copy->children = copychild; tail = copychild; } return copy; copy_error: /* release all the hitherto allocated memory */ if (copy) xmpp_stanza_release(copy); return NULL; } /** Release a stanza object and all of its children. * This function releases a stanza object and potentially all of its * children, which may cause the object(s) to be freed. * * @param stanza a Strophe stanza object * * @return TRUE if the object was freed and FALSE otherwise * * @ingroup Stanza */ int xmpp_stanza_release(xmpp_stanza_t * const stanza) { int released = 0; xmpp_stanza_t *child, *tchild; /* release stanza */ if (stanza->ref > 1) stanza->ref--; else { /* release all children */ child = stanza->children; while (child) { tchild = child; child = child->next; xmpp_stanza_release(tchild); } if (stanza->attributes) hash_release(stanza->attributes); if (stanza->data) xmpp_free(stanza->ctx, stanza->data); xmpp_free(stanza->ctx, stanza); released = 1; } return released; } /** Determine if a stanza is a text node. * * @param stanza a Strophe stanza object * * @return TRUE if the stanza is a text node, FALSE otherwise * * @ingroup Stanza */ int xmpp_stanza_is_text(xmpp_stanza_t * const stanza) { return (stanza && stanza->type == XMPP_STANZA_TEXT); } /** Determine if a stanza is a tag node. * * @param stanza a Strophe stanza object * * @return TRUE if the stanza is a tag node, FALSE otherwise * * @ingroup Stanza */ int xmpp_stanza_is_tag(xmpp_stanza_t * const stanza) { return (stanza && stanza->type == XMPP_STANZA_TAG); } /* Escape a string with for use in a XML text node or attribute. Assumes that * the input string is encoded in UTF-8. On sucess, returns a pointer to a * buffer with the resulting data which must be xmpp_free()'d by the caller. * On failure, returns NULL. */ static char *_escape_xml(xmpp_ctx_t * const ctx, char *text) { size_t len = 0; char *src; char *dst; char *buf; for (src = text; *src != '\0'; src++) { switch (*src) { case '<': /* "<" */ case '>': /* ">" */ len += 4; break; case '&': /* "&" */ len += 5; break; case '"': len += 6; /*""" */ break; default: len++; } } if ((buf = xmpp_alloc(ctx, (len+1) * sizeof(char))) == NULL) return NULL; /* Error */ dst = buf; for (src = text; *src != '\0'; src++) { switch (*src) { case '<': strcpy(dst, "<"); dst += 4; break; case '>': strcpy(dst, ">"); dst += 4; break; case '&': strcpy(dst, "&"); dst += 5; break; case '"': strcpy(dst, """); dst += 6; break; default: *dst = *src; dst++; } } *dst = '\0'; return buf; } /* small helper function */ static inline void _render_update(int *written, const int length, const int lastwrite, size_t *left, char **ptr) { *written += lastwrite; if (*written > length) { *left = 0; *ptr = NULL; } else { *left -= lastwrite; *ptr = &(*ptr)[lastwrite]; } } /* always returns number of bytes written or that would have been * written if the buffer was large enough * return values < 0 indicate some error occured, * and return values > buflen indicate buffer was not large enough */ static int _render_stanza_recursive(xmpp_stanza_t *stanza, char * const buf, size_t const buflen) { char *ptr = buf; size_t left = buflen; int ret, written; xmpp_stanza_t *child; hash_iterator_t *iter; const char *key; char *tmp; written = 0; if (stanza->type == XMPP_STANZA_UNKNOWN) return XMPP_EINVOP; if (stanza->type == XMPP_STANZA_TEXT) { if (!stanza->data) return XMPP_EINVOP; tmp = _escape_xml(stanza->ctx, stanza->data); if (tmp == NULL) return XMPP_EMEM; ret = xmpp_snprintf(ptr, left, "%s", tmp); xmpp_free(stanza->ctx, tmp); if (ret < 0) return XMPP_EMEM; _render_update(&written, buflen, ret, &left, &ptr); } else { /* stanza->type == XMPP_STANZA_TAG */ if (!stanza->data) return XMPP_EINVOP; /* write begining of tag and attributes */ ret = xmpp_snprintf(ptr, left, "<%s", stanza->data); if (ret < 0) return XMPP_EMEM; _render_update(&written, buflen, ret, &left, &ptr); if (stanza->attributes && hash_num_keys(stanza->attributes) > 0) { iter = hash_iter_new(stanza->attributes); while ((key = hash_iter_next(iter))) { if (!strcmp(key, "xmlns")) { /* don't output namespace if parent stanza is the same */ if (stanza->parent && stanza->parent->attributes && hash_get(stanza->parent->attributes, key) && !strcmp((char*)hash_get(stanza->attributes, key), (char*)hash_get(stanza->parent->attributes, key))) continue; /* or if this is the stream namespace */ if (!stanza->parent && !strcmp((char*)hash_get(stanza->attributes, key), XMPP_NS_CLIENT)) continue; } tmp = _escape_xml(stanza->ctx, (char *)hash_get(stanza->attributes, key)); if (tmp == NULL) return XMPP_EMEM; ret = xmpp_snprintf(ptr, left, " %s=\"%s\"", key, tmp); xmpp_free(stanza->ctx, tmp); if (ret < 0) return XMPP_EMEM; _render_update(&written, buflen, ret, &left, &ptr); } hash_iter_release(iter); } if (!stanza->children) { /* write end if singleton tag */ ret = xmpp_snprintf(ptr, left, "/>"); if (ret < 0) return XMPP_EMEM; _render_update(&written, buflen, ret, &left, &ptr); } else { /* this stanza has child stanzas */ /* write end of start tag */ ret = xmpp_snprintf(ptr, left, ">"); if (ret < 0) return XMPP_EMEM; _render_update(&written, buflen, ret, &left, &ptr); /* iterate and recurse over child stanzas */ child = stanza->children; while (child) { ret = _render_stanza_recursive(child, ptr, left); if (ret < 0) return ret; _render_update(&written, buflen, ret, &left, &ptr); child = child->next; } /* write end tag */ ret = xmpp_snprintf(ptr, left, "", stanza->data); if (ret < 0) return XMPP_EMEM; _render_update(&written, buflen, ret, &left, &ptr); } } return written; } /** Render a stanza object to text. * This function renders a given stanza object, along with its * children, to text. The text is returned in an allocated, * null-terminated buffer. It starts by allocating a 1024 byte buffer * and reallocates more memory if that is not large enough. * * @param stanza a Strophe stanza object * @param buf a reference to a string pointer * @param buflen a reference to a size_t * * @return 0 on success (XMPP_EOK), and a number less than 0 on failure * (XMPP_EMEM, XMPP_EINVOP) * * @ingroup Stanza */ int xmpp_stanza_to_text(xmpp_stanza_t *stanza, char ** const buf, size_t * const buflen) { char *buffer, *tmp; size_t length; int ret; /* allocate a default sized buffer and attempt to render */ length = 1024; buffer = xmpp_alloc(stanza->ctx, length); if (!buffer) { *buf = NULL; *buflen = 0; return XMPP_EMEM; } ret = _render_stanza_recursive(stanza, buffer, length); if (ret < 0) return ret; if (ret > length - 1) { tmp = xmpp_realloc(stanza->ctx, buffer, ret + 1); if (!tmp) { xmpp_free(stanza->ctx, buffer); *buf = NULL; *buflen = 0; return XMPP_EMEM; } length = ret + 1; buffer = tmp; ret = _render_stanza_recursive(stanza, buffer, length); if (ret > length - 1) return XMPP_EMEM; } buffer[length - 1] = 0; *buf = buffer; *buflen = ret; return XMPP_EOK; } /** Set the name of a stanza. * * @param stanza a Strophe stanza object * @param name a string with the name of the stanza * * @return XMPP_EOK on success, a number less than 0 on failure (XMPP_EMEM, * XMPP_EINVOP) * * @ingroup Stanza */ int xmpp_stanza_set_name(xmpp_stanza_t *stanza, const char * const name) { if (stanza->type == XMPP_STANZA_TEXT) return XMPP_EINVOP; if (stanza->data) xmpp_free(stanza->ctx, stanza->data); stanza->type = XMPP_STANZA_TAG; stanza->data = xmpp_strdup(stanza->ctx, name); return XMPP_EOK; } /** Get the stanza name. * This function returns a pointer to the stanza name. If the caller needs * to store this data, it must make a copy. * * @param stanza a Strophe stanza object * * @return a string with the stanza name * * @ingroup Stanza */ char *xmpp_stanza_get_name(xmpp_stanza_t * const stanza) { if (stanza->type == XMPP_STANZA_TEXT) return NULL; return stanza->data; } /** Count the attributes in a stanza object. * * @param stanza a Strophe stanza object * * @return the number of attributes for the stanza object * * @ingroup Stanza */ int xmpp_stanza_get_attribute_count(xmpp_stanza_t * const stanza) { if (stanza->attributes == NULL) { return 0; } return hash_num_keys(stanza->attributes); } /** Get all attributes for a stanza object. * This function populates the array with attributes from the stanza. The * attr array will be in the format: attr[i] = attribute name, * attr[i+1] = attribute value. * * @param stanza a Strophe stanza object * @param attr the string array to populate * @param attrlen the size of the array * * @return the number of slots used in the array, which will be 2 times the * number of attributes in the stanza * * @ingroup Stanza */ int xmpp_stanza_get_attributes(xmpp_stanza_t * const stanza, const char **attr, int attrlen) { hash_iterator_t *iter; const char *key; int num = 0; if (stanza->attributes == NULL) { return 0; } iter = hash_iter_new(stanza->attributes); while ((key = hash_iter_next(iter)) != NULL && attrlen) { attr[num++] = key; attrlen--; if (attrlen == 0) { hash_iter_release(iter); return num; } attr[num++] = hash_get(stanza->attributes, key); attrlen--; if (attrlen == 0) { hash_iter_release(iter); return num; } } hash_iter_release(iter); return num; } /** Set an attribute for a stanza object. * * @param stanza a Strophe stanza object * @param key a string with the attribute name * @param value a string with the attribute value * * @return XMPP_EOK (0) on success or a number less than 0 on failure * * @ingroup Stanza */ int xmpp_stanza_set_attribute(xmpp_stanza_t * const stanza, const char * const key, const char * const value) { char *val; if (stanza->type != XMPP_STANZA_TAG) return XMPP_EINVOP; if (!stanza->attributes) { stanza->attributes = hash_new(stanza->ctx, 8, xmpp_free); if (!stanza->attributes) return XMPP_EMEM; } val = xmpp_strdup(stanza->ctx, value); if (!val) return XMPP_EMEM; hash_add(stanza->attributes, key, val); return XMPP_EOK; } /** Set the stanza namespace. * This is a convenience function equivalent to calling: * xmpp_stanza_set_attribute(stanza, "xmlns", ns); * * @param stanza a Strophe stanza object * @param ns a string with the namespace * * @return XMPP_EOK (0) on success or a number less than 0 on failure * * @ingroup Stanza */ int xmpp_stanza_set_ns(xmpp_stanza_t * const stanza, const char * const ns) { return xmpp_stanza_set_attribute(stanza, "xmlns", ns); } /** Add a child stanza to a stanza object. * This function clones the child and appends it to the stanza object's * children. * * @param stanza a Strophe stanza object * @param child the child stanza object * * @return XMPP_EOK (0) on success or a number less than 0 on failure * * @ingroup Stanza */ int xmpp_stanza_add_child(xmpp_stanza_t *stanza, xmpp_stanza_t *child) { xmpp_stanza_t *s; /* get a reference to the child */ xmpp_stanza_clone(child); child->parent = stanza; if (!stanza->children) stanza->children = child; else { s = stanza->children; while (s->next) s = s->next; s->next = child; child->prev = s; } return XMPP_EOK; } /** Set the text data for a text stanza. * This function copies the text given and sets the stanza object's text to * it. Attempting to use this function on a stanza that has a name will * fail with XMPP_EINVOP. This function takes the text as a null-terminated * string. * * @param stanza a Strophe stanza object * @param text a string with the text * * @return XMPP_EOK (0) on success or a number less than zero on failure * * @ingroup Stanza */ int xmpp_stanza_set_text(xmpp_stanza_t *stanza, const char * const text) { if (stanza->type == XMPP_STANZA_TAG) return XMPP_EINVOP; stanza->type = XMPP_STANZA_TEXT; if (stanza->data) xmpp_free(stanza->ctx, stanza->data); stanza->data = xmpp_strdup(stanza->ctx, text); return XMPP_EOK; } /** Set the text data for a text stanza. * This function copies the text given and sets teh stanza object's text to * it. Attempting to use this function on a stanza that has a name will * fail with XMPP_EINVOP. This function takes the text as buffer and a length * as opposed to a null-terminated string. * * @param stanza a Strophe stanza object * @param text a buffer with the text * @param size the length of the text * * @return XMPP_EOK (0) on success and a number less than 0 on failure * * @ingroup Stanza */ int xmpp_stanza_set_text_with_size(xmpp_stanza_t *stanza, const char * const text, const size_t size) { if (stanza->type == XMPP_STANZA_TAG) return XMPP_EINVOP; stanza->type = XMPP_STANZA_TEXT; if (stanza->data) xmpp_free(stanza->ctx, stanza->data); stanza->data = xmpp_alloc(stanza->ctx, size + 1); if (!stanza->data) return XMPP_EMEM; memcpy(stanza->data, text, size); stanza->data[size] = 0; return XMPP_EOK; } /** Get the 'id' attribute of the stanza object. * This is a convenience function equivalent to: * xmpp_stanza_get_attribute(stanza, "id"); * * @param stanza a Strophe stanza object * * @return a string with the 'id' attribute value * * @ingroup Stanza */ char *xmpp_stanza_get_id(xmpp_stanza_t * const stanza) { if (stanza->type != XMPP_STANZA_TAG) return NULL; if (!stanza->attributes) return NULL; return (char *)hash_get(stanza->attributes, "id"); } /** Get the namespace attribute of the stanza object. * This is a convenience function equivalent to: * xmpp_stanza_get_attribute(stanza, "xmlns"); * * @param stanza a Strophe stanza object * * @return a string with the 'xmlns' attribute value * * @ingroup Stanza */ char *xmpp_stanza_get_ns(xmpp_stanza_t * const stanza) { if (stanza->type != XMPP_STANZA_TAG) return NULL; if (!stanza->attributes) return NULL; return (char *)hash_get(stanza->attributes, "xmlns"); } /** Get the 'type' attribute of the stanza object. * This is a convenience function equivalent to: * xmpp_stanza_get_attribute(stanza, "type"); * * @param stanza a Strophe stanza object * * @return a string with the 'type' attribute value * * @ingroup Stanza */ char *xmpp_stanza_get_type(xmpp_stanza_t * const stanza) { if (stanza->type != XMPP_STANZA_TAG) return NULL; if (!stanza->attributes) return NULL; return (char *)hash_get(stanza->attributes, "type"); } /** Get the first child of stanza with name. * This function searches all the immediate children of stanza for a child * stanza that matches the name. The first matching child is returned. * * @param stanza a Strophe stanza object * @param name a string with the name to match * * @return the matching child stanza object or NULL if no match was found * * @ingroup Stanza */ xmpp_stanza_t *xmpp_stanza_get_child_by_name(xmpp_stanza_t * const stanza, const char * const name) { xmpp_stanza_t *child; for (child = stanza->children; child; child = child->next) { if (child->type == XMPP_STANZA_TAG && (strcmp(name, xmpp_stanza_get_name(child)) == 0)) break; } return child; } /** Get the first child of a stanza with a given namespace. * This function searches all the immediate children of a stanza for a child * stanza that matches the namespace provided. The first matching child * is returned. * * @param stanza a Strophe stanza object * @param ns a string with the namespace to match * * @return the matching child stanza object or NULL if no match was found * * @ingroup Stanza */ xmpp_stanza_t *xmpp_stanza_get_child_by_ns(xmpp_stanza_t * const stanza, const char * const ns) { xmpp_stanza_t *child; for (child = stanza->children; child; child = child->next) { if (xmpp_stanza_get_ns(child) && strcmp(ns, xmpp_stanza_get_ns(child)) == 0) break; } return child; } /** Get the list of children. * This function returns the first child of the stanza object. The rest * of the children can be obtained by calling xmpp_stanza_get_next() to * iterate over the siblings. * * @param stanza a Strophe stanza object * * @return the first child stanza or NULL if there are no children * * @ingroup Stanza */ xmpp_stanza_t *xmpp_stanza_get_children(xmpp_stanza_t * const stanza) { return stanza->children; } /** Get the next sibling of a stanza. * * @param stanza a Strophe stanza object * * @return the next sibling stanza or NULL if there are no more siblings * * @ingroup Stanza */ xmpp_stanza_t *xmpp_stanza_get_next(xmpp_stanza_t * const stanza) { return stanza->next; } /** Get the text data for a text stanza. * This function copies the text data from a stanza and returns the new * allocated string. The caller is responsible for freeing this string * with xmpp_free(). * * @param stanza a Strophe stanza object * * @return an allocated string with the text data * * @ingroup Stanza */ char *xmpp_stanza_get_text(xmpp_stanza_t * const stanza) { size_t len, clen; xmpp_stanza_t *child; char *text; if (stanza->type == XMPP_STANZA_TEXT) { if (stanza->data) return xmpp_strdup(stanza->ctx, stanza->data); else return NULL; } len = 0; for (child = stanza->children; child; child = child->next) if (child->type == XMPP_STANZA_TEXT) len += strlen(child->data); if (len == 0) return NULL; text = (char *)xmpp_alloc(stanza->ctx, len + 1); if (!text) return NULL; len = 0; for (child = stanza->children; child; child = child->next) if (child->type == XMPP_STANZA_TEXT) { clen = strlen(child->data); memcpy(&text[len], child->data, clen); len += clen; } text[len] = 0; return text; } /** Get the text data pointer for a text stanza. * This function copies returns the raw pointer to the text data in the * stanza. This should only be used in very special cases where the * caller needs to translate the datatype as this will save a double * allocation. The caller should not hold onto this pointer, and is * responsible for allocating a copy if it needs one. * * @param stanza a Strophe stanza object * * @return an string pointer to the data or NULL * * @ingroup Stanza */ char *xmpp_stanza_get_text_ptr(xmpp_stanza_t * const stanza) { if (stanza->type == XMPP_STANZA_TEXT) return stanza->data; return NULL; } /** Set the 'id' attribute of a stanza. * * This is a convenience function for: * xmpp_stanza_set_attribute(stanza, 'id', id); * * @param stanza a Strophe stanza object * @param id a string containing the 'id' value * * @return XMPP_EOK (0) on success or a number less than 0 on failure * * @ingroup Stanza */ int xmpp_stanza_set_id(xmpp_stanza_t * const stanza, const char * const id) { return xmpp_stanza_set_attribute(stanza, "id", id); } /** Set the 'type' attribute of a stanza. * This is a convenience function for: * xmpp_stanza_set_attribute(stanza, 'type', type); * * @param stanza a Strophe stanza object * @param type a string containing the 'type' value * * @return XMPP_EOK (0) on success or a number less than 0 on failure * * @ingroup Stanza */ int xmpp_stanza_set_type(xmpp_stanza_t * const stanza, const char * const type) { return xmpp_stanza_set_attribute(stanza, "type", type); } /** Get an attribute from a stanza. * This function returns a pointer to the attribute value. If the caller * wishes to save this value it must make its own copy. * * @param stanza a Strophe stanza object * @param name a string containing attribute name * * @return a string with the attribute value or NULL on an error * * @ingroup Stanza */ char *xmpp_stanza_get_attribute(xmpp_stanza_t * const stanza, const char * const name) { if (stanza->type != XMPP_STANZA_TAG) return NULL; if (!stanza->attributes) return NULL; return hash_get(stanza->attributes, name); } libstrophe-0.8.8/src/thread.c000066400000000000000000000036221256471717200161230ustar00rootroot00000000000000/* thread.c ** strophe XMPP client library -- thread abstraction ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Thread absraction. */ #include #include #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include #else #include #endif #include "strophe.h" #include "common.h" #include "thread.h" struct _mutex_t { const xmpp_ctx_t *ctx; #ifdef _WIN32 HANDLE mutex; #else pthread_mutex_t *mutex; #endif }; /* mutex functions */ mutex_t *mutex_create(const xmpp_ctx_t * ctx) { mutex_t *mutex; mutex = xmpp_alloc(ctx, sizeof(mutex_t)); if (mutex) { mutex->ctx = ctx; #ifdef _WIN32 mutex->mutex = CreateMutex(NULL, FALSE, NULL); #else mutex->mutex = xmpp_alloc(ctx, sizeof(pthread_mutex_t)); if (mutex->mutex) if (pthread_mutex_init(mutex->mutex, NULL) != 0) { xmpp_free(ctx, mutex->mutex); mutex->mutex = NULL; } #endif if (!mutex->mutex) { xmpp_free(ctx, mutex); mutex = NULL; } } return mutex; } int mutex_destroy(mutex_t *mutex) { int ret = 1; const xmpp_ctx_t *ctx; #ifdef _WIN32 if (mutex->mutex) ret = CloseHandle(mutex->mutex); #else if (mutex->mutex) ret = pthread_mutex_destroy(mutex->mutex) == 0; #endif ctx = mutex->ctx; xmpp_free(ctx, mutex); return ret; } int mutex_lock(mutex_t *mutex) { int ret; #ifdef _WIN32 ret = WaitForSingleObject(mutex->mutex, INFINITE) == 0; #else ret = pthread_mutex_lock(mutex->mutex) == 0; #endif return ret; } int mutex_trylock(mutex_t *mutex) { /* TODO */ return 0; } int mutex_unlock(mutex_t *mutex) { int ret; #ifdef _WIN32 ret = ReleaseMutex(mutex->mutex); #else ret = pthread_mutex_unlock(mutex->mutex) == 0; #endif return ret; } libstrophe-0.8.8/src/thread.h000066400000000000000000000014411256471717200161250ustar00rootroot00000000000000/* thread.h ** strophe XMPP client library -- thread abstraction header ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Threading abstraction API. */ #ifndef __LIBSTROPHE_THREAD_H__ #define __LIBSTROPHE_THREAD_H__ #include #include #ifdef _WIN32 #include #else #include #endif #include "strophe.h" typedef struct _mutex_t mutex_t; /* mutex functions */ mutex_t *mutex_create(const xmpp_ctx_t *ctx); int mutex_destroy(mutex_t *mutex); int mutex_lock(mutex_t *mutex); int mutex_trylock(mutex_t *mutex); int mutex_unlock(mutex_t *mutex); #endif /* __LIBSTROPHE_THREAD_H__ */ libstrophe-0.8.8/src/tls.h000066400000000000000000000017321256471717200154630ustar00rootroot00000000000000/* tls.h ** strophe XMPP client library -- TLS abstraction header ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * TLS abstraction API. */ #ifndef __LIBSTROPHE_TLS_H__ #define __LIBSTROPHE_TLS_H__ #include "common.h" #include "sock.h" typedef struct _tls tls_t; void tls_initialize(void); void tls_shutdown(void); tls_t *tls_new(xmpp_ctx_t *ctx, sock_t sock); void tls_free(tls_t *tls); int tls_set_credentials(tls_t *tls, const char *cafilename); int tls_start(tls_t *tls); int tls_stop(tls_t *tls); int tls_error(tls_t *tls); int tls_pending(tls_t *tls); int tls_read(tls_t *tls, void * const buff, const size_t len); int tls_write(tls_t *tls, const void * const buff, const size_t len); int tls_clear_pending_write(tls_t *tls); int tls_is_recoverable(int error); #endif /* __LIBSTROPHE_TLS_H__ */ libstrophe-0.8.8/src/tls_dummy.c000066400000000000000000000024421256471717200166700ustar00rootroot00000000000000/* tls_dummy.c ** strophe XMPP client library -- TLS abstraction dummy impl. ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * TLS dummy implementation. */ #include "common.h" #include "tls.h" #include "sock.h" struct _tls { xmpp_ctx_t *ctx; /* do we need this? */ sock_t sock; /* we don't implement anything */ }; void tls_initialize(void) { return; } void tls_shutdown(void) { return; } tls_t *tls_new(xmpp_ctx_t *ctx, sock_t sock) { /* always fail */ return NULL; } void tls_free(tls_t *tls) { return; } int tls_set_credentials(tls_t *tls, const char *cafilename) { return -1; } int tls_start(tls_t *tls) { return -1; } int tls_stop(tls_t *tls) { return -1; } int tls_error(tls_t *tls) { /* todo: some kind of error polling/dump */ return 0; } int tls_pending(tls_t *tls) { return 0; } int tls_read(tls_t *tls, void * const buff, const size_t len) { return -1; } int tls_write(tls_t *tls, const void * const buff, const size_t len) { return -1; } int tls_clear_pending_write(tls_t *tls) { return -1; } int tls_is_recoverable(int error) { return 0; } libstrophe-0.8.8/src/tls_gnutls.c000066400000000000000000000051771256471717200170610ustar00rootroot00000000000000/* tls.c ** strophe XMPP client library -- TLS abstraction header ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * TLS implementation with GNUTLS */ #include #include "common.h" #include "tls.h" #include "sock.h" struct _tls { xmpp_ctx_t *ctx; /* do we need this? */ sock_t sock; gnutls_session_t session; gnutls_certificate_credentials_t cred; }; void tls_initialize(void) { /* initialize the GNU TLS global state */ gnutls_global_init(); /* TODO: wire in xmpp_ctx_t allocator somehow? unfortunately in gnutls it's global, so we can only do so much. */ } void tls_shutdown(void) { /* tear down the GNU TLS global state */ gnutls_global_deinit(); } tls_t *tls_new(xmpp_ctx_t *ctx, sock_t sock) { tls_t *tls = xmpp_alloc(ctx, sizeof(tls_t)); const int cert_type_priority[3] = { GNUTLS_CRT_X509, GNUTLS_CRT_OPENPGP, 0 }; if (tls) { tls->ctx = ctx; tls->sock = sock; gnutls_init(&tls->session, GNUTLS_CLIENT); gnutls_certificate_allocate_credentials(&tls->cred); gnutls_set_default_priority(tls->session); gnutls_certificate_type_set_priority(tls->session, cert_type_priority); /* fixme: this may require setting a callback on win32? */ gnutls_transport_set_ptr(tls->session, (gnutls_transport_ptr_t)sock); } return tls; } void tls_free(tls_t *tls) { gnutls_deinit(tls->session); gnutls_certificate_free_credentials(tls->cred); xmpp_free(tls->ctx, tls); } int tls_set_credentials(tls_t *tls, const char *cafilename) { int err; /* set trusted credentials -- takes a .pem filename */ err = gnutls_certificate_set_x509_trust_file(tls->cred, cafilename, GNUTLS_X509_FMT_PEM); if (err < 0) return err; err = gnutls_credentials_set(tls->session, GNUTLS_CRD_CERTIFICATE, tls->cred); return err; } int tls_start(tls_t *tls) { return gnutls_handshake(tls->session); } int tls_stop(tls_t *tls) { return gnutls_bye(tls->session, GNUTLS_SHUT_RDWR); } int tls_error(tls_t *tls) { /* todo: some kind of error polling/dump */ return 0; } int tls_pending(tls_t *tls) { return gnutls_record_check_pending (tls->session); } int tls_read(tls_t *tls, void * const buff, const size_t len) { int ret; ret = gnutls_record_recv(tls->session, buff, len); return ret; } int tls_write(tls_t *tls, const void * const buff, const size_t len) { int ret; ret = gnutls_record_send(tls->session, buff, len); return ret; } libstrophe-0.8.8/src/tls_openssl.c000066400000000000000000000062101256471717200172150ustar00rootroot00000000000000/* tls_openssl.c ** strophe XMPP client library -- TLS abstraction openssl impl. ** ** Copyright (C) 2005-008 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * TLS implementation with OpenSSL. */ #include #ifndef _WIN32 #include #else #include #endif #include #include "common.h" #include "tls.h" #include "sock.h" struct _tls { xmpp_ctx_t *ctx; sock_t sock; SSL_CTX *ssl_ctx; SSL *ssl; int lasterror; }; void tls_initialize(void) { SSL_library_init(); SSL_load_error_strings(); } void tls_shutdown(void) { return; } int tls_error(tls_t *tls) { return tls->lasterror; } tls_t *tls_new(xmpp_ctx_t *ctx, sock_t sock) { tls_t *tls = xmpp_alloc(ctx, sizeof(*tls)); if (tls) { int ret; memset(tls, 0, sizeof(*tls)); tls->ctx = ctx; tls->sock = sock; tls->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); SSL_CTX_set_client_cert_cb(tls->ssl_ctx, NULL); SSL_CTX_set_mode (tls->ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE); SSL_CTX_set_verify (tls->ssl_ctx, SSL_VERIFY_NONE, NULL); tls->ssl = SSL_new(tls->ssl_ctx); ret = SSL_set_fd(tls->ssl, sock); if (ret <= 0) { tls->lasterror = SSL_get_error(tls->ssl, ret); tls_error(tls); tls_free(tls); tls = NULL; } } return tls; } void tls_free(tls_t *tls) { SSL_free(tls->ssl); SSL_CTX_free(tls->ssl_ctx); xmpp_free(tls->ctx, tls); return; } int tls_set_credentials(tls_t *tls, const char *cafilename) { return -1; } int tls_start(tls_t *tls) { int ret = -1; /* Since we're non-blocking, loop the connect call until it succeeds or fails */ while (ret == -1) { ret = SSL_connect(tls->ssl); /* wait for something to happen on the sock before looping back */ if (ret == -1) { fd_set fds; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 1000; FD_ZERO(&fds); FD_SET(tls->sock, &fds); select(tls->sock + 1, &fds, &fds, NULL, &tv); } } if (ret <= 0) { tls->lasterror = SSL_get_error(tls->ssl, ret); return 0; } return 1; } int tls_stop(tls_t *tls) { int ret; ret = SSL_shutdown(tls->ssl); if (ret <= 0) { tls->lasterror = SSL_get_error(tls->ssl, ret); return 0; } return 1; } int tls_is_recoverable(int error) { return (error == SSL_ERROR_NONE || error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE || error == SSL_ERROR_WANT_CONNECT || error == SSL_ERROR_WANT_ACCEPT); } int tls_pending(tls_t *tls) { return SSL_pending(tls->ssl); } int tls_read(tls_t *tls, void * const buff, const size_t len) { int ret = SSL_read(tls->ssl, buff, len); if (ret <= 0) { tls->lasterror = SSL_get_error(tls->ssl, ret); } return ret; } int tls_write(tls_t *tls, const void * const buff, const size_t len) { int ret = SSL_write(tls->ssl, buff, len); if (ret <= 0) { tls->lasterror = SSL_get_error(tls->ssl, ret); } return ret; } int tls_clear_pending_write(tls_t *tls) { return 0; } libstrophe-0.8.8/src/tls_schannel.c000066400000000000000000000354021256471717200173320ustar00rootroot00000000000000/* tls_schannel.c ** strophe XMPP client library -- TLS abstraction schannel impl. ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * TLS implementation with Win32 SChannel. */ #include "common.h" #include "tls.h" #include "sock.h" #define SECURITY_WIN32 #include #include struct _tls { xmpp_ctx_t *ctx; sock_t sock; HANDLE hsec32; SecurityFunctionTable *sft; CredHandle hcred; SecPkgInfo *spi; int init; CtxtHandle hctxt; SecPkgContext_StreamSizes spcss; unsigned char *recvbuffer; unsigned int recvbuffermaxlen; unsigned int recvbufferpos; unsigned char *readybuffer; unsigned int readybufferpos; unsigned int readybufferlen; unsigned char *sendbuffer; unsigned int sendbuffermaxlen; unsigned int sendbufferlen; unsigned int sendbufferpos; SECURITY_STATUS lasterror; }; void tls_initialize(void) { return; } void tls_shutdown(void) { return; } tls_t *tls_new(xmpp_ctx_t *ctx, sock_t sock) { tls_t *tls; PSecurityFunctionTable (*pInitSecurityInterface)(void); SCHANNEL_CRED scred; int ret; ALG_ID algs[1]; SecPkgCred_SupportedAlgs spc_sa; SecPkgCred_CipherStrengths spc_cs; SecPkgCred_SupportedProtocols spc_sp; OSVERSIONINFO osvi; memset(&osvi, 0, sizeof(osvi)); osvi.dwOSVersionInfoSize = sizeof(osvi); GetVersionEx(&osvi); /* no TLS support on win9x/me, despite what anyone says */ if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { return NULL; } tls = xmpp_alloc(ctx, sizeof(*tls)); if (!tls) { return NULL; } memset(tls, 0, sizeof(*tls)); tls->ctx = ctx; tls->sock = sock; if (!(tls->hsec32 = LoadLibrary ("secur32.dll"))) { tls_free(tls); return NULL; } if (!(pInitSecurityInterface = (void *)GetProcAddress(tls->hsec32, "InitSecurityInterfaceA"))) { tls_free(tls); return NULL; } tls->sft = pInitSecurityInterface(); if (!tls->sft) { tls_free(tls); return NULL; } ret = tls->sft->QuerySecurityPackageInfo(UNISP_NAME, &(tls->spi)); if (ret != SEC_E_OK) { tls_free(tls); return NULL; } xmpp_debug(ctx, "TLSS", "QuerySecurityPackageInfo() success"); memset(&scred, 0, sizeof(scred)); scred.dwVersion = SCHANNEL_CRED_VERSION; /*scred.grbitEnabledProtocols = SP_PROT_TLS1_CLIENT;*/ /* Something down the line doesn't like AES, so force it to RC4 */ algs[0] = CALG_RC4; scred.cSupportedAlgs = 1; scred.palgSupportedAlgs = algs; ret = tls->sft->AcquireCredentialsHandleA(NULL, UNISP_NAME, SECPKG_CRED_OUTBOUND, NULL, &scred, NULL, NULL, &(tls->hcred), NULL); if (ret != SEC_E_OK) { tls_free(tls); return NULL; } xmpp_debug(ctx, "TLSS", "AcquireCredentialsHandle() success"); tls->init = 1; /* This bunch of queries should trip up wine until someone fixes * schannel support there */ ret = tls->sft->QueryCredentialsAttributes(&(tls->hcred), SECPKG_ATTR_SUPPORTED_ALGS, &spc_sa); if (ret != SEC_E_OK) { tls_free(tls); return NULL; } ret = tls->sft->QueryCredentialsAttributes(&(tls->hcred), SECPKG_ATTR_CIPHER_STRENGTHS, &spc_cs); if (ret != SEC_E_OK) { tls_free(tls); return NULL; } ret = tls->sft->QueryCredentialsAttributes(&(tls->hcred), SECPKG_ATTR_SUPPORTED_PROTOCOLS, &spc_sp); if (ret != SEC_E_OK) { tls_free(tls); return NULL; } return tls; } void tls_free(tls_t *tls) { if (tls->recvbuffer) { xmpp_free(tls->ctx, tls->recvbuffer); } if (tls->readybuffer) { xmpp_free(tls->ctx, tls->readybuffer); } if (tls->sendbuffer) { xmpp_free(tls->ctx, tls->sendbuffer); } if (tls->init) { tls->sft->FreeCredentialsHandle(&(tls->hcred)); } tls->sft = NULL; if (tls->hsec32) { FreeLibrary(tls->hsec32); tls->hsec32 = NULL; } xmpp_free(tls->ctx, tls); return; } int tls_set_credentials(tls_t *tls, const char *cafilename) { return -1; } int tls_start(tls_t *tls) { ULONG ctxtreq = 0, ctxtattr = 0; SecBufferDesc sbdin, sbdout; SecBuffer sbin[2], sbout[1]; SECURITY_STATUS ret; int sent; char *name = NULL; /* search the ctx's conns for our sock, and use the domain there as our * name */ { xmpp_connlist_t *listentry = tls->ctx->connlist; while (listentry) { xmpp_conn_t *conn = listentry->conn; if (conn->sock == tls->sock) { name = strdup(conn->domain); listentry = NULL; } else { listentry = listentry->next; } } } ctxtreq = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR | ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM | ISC_REQ_MANUAL_CRED_VALIDATION | ISC_REQ_INTEGRITY; memset(&(sbout[0]), 0, sizeof(sbout[0])); sbout[0].BufferType = SECBUFFER_TOKEN; memset(&sbdout, 0, sizeof(sbdout)); sbdout.ulVersion = SECBUFFER_VERSION; sbdout.cBuffers = 1; sbdout.pBuffers = sbout; memset(&(sbin[0]), 0, sizeof(sbin[0])); sbin[0].BufferType = SECBUFFER_TOKEN; sbin[0].pvBuffer = xmpp_alloc(tls->ctx, tls->spi->cbMaxToken); sbin[0].cbBuffer = tls->spi->cbMaxToken; memset(&(sbin[1]), 0, sizeof(sbin[1])); sbin[1].BufferType = SECBUFFER_EMPTY; memset(&sbdin, 0, sizeof(sbdin)); sbdin.ulVersion = SECBUFFER_VERSION; sbdin.cBuffers = 2; sbdin.pBuffers = sbin; ret = tls->sft->InitializeSecurityContextA(&(tls->hcred), NULL, name, ctxtreq, 0, 0, NULL, 0, &(tls->hctxt), &sbdout, &ctxtattr, NULL); while (ret == SEC_I_CONTINUE_NEEDED || ret == SEC_I_INCOMPLETE_CREDENTIALS) { unsigned char *p = sbin[0].pvBuffer; int len = 0, inbytes = 0; if (sbdout.pBuffers[0].cbBuffer) { unsigned char *writebuff = sbdout.pBuffers[0].pvBuffer; unsigned int writelen = sbdout.pBuffers[0].cbBuffer; sent = sock_write(tls->sock, writebuff, writelen); if (sent == -1) { tls->lasterror = sock_error(); } else { writebuff += sent; writelen -= sent; } tls->sft->FreeContextBuffer(sbdout.pBuffers[0].pvBuffer); sbdout.pBuffers[0].pvBuffer = NULL; sbdout.pBuffers[0].cbBuffer = 0; } /* poll for a bit until the remote server stops sending data, ie it * finishes sending the token */ inbytes = 1; { fd_set fds; struct timeval tv; tv.tv_sec = 2; tv.tv_usec = 0; FD_ZERO(&fds); FD_SET(tls->sock, &fds); select(tls->sock, &fds, NULL, NULL, &tv); } while (inbytes > 0) { fd_set fds; struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 1000; FD_ZERO(&fds); FD_SET(tls->sock, &fds); select(tls->sock, &fds, NULL, NULL, &tv); inbytes = sock_read(tls->sock, p, tls->spi->cbMaxToken - len); if (inbytes > 0) { len += inbytes; p += inbytes; } else { tls->lasterror = sock_error(); } } sbin[0].cbBuffer = len; ret = tls->sft->InitializeSecurityContextA(&(tls->hcred), &(tls->hctxt), name, ctxtreq, 0, 0, &sbdin, 0, &(tls->hctxt), &sbdout, &ctxtattr, NULL); } if (ret == SEC_E_OK) { if (sbdout.pBuffers[0].cbBuffer) { unsigned char *writebuff = sbdout.pBuffers[0].pvBuffer; unsigned int writelen = sbdout.pBuffers[0].cbBuffer; sent = sock_write(tls->sock, writebuff, writelen); if (sent == -1) { tls->lasterror = sock_error(); } else { writebuff += sent; writelen -= sent; } tls->sft->FreeContextBuffer(sbdout.pBuffers[0].pvBuffer); sbdout.pBuffers[0].pvBuffer = NULL; sbdout.pBuffers[0].cbBuffer = 0; } } xmpp_free(tls->ctx, sbin[0].pvBuffer); if (ret != SEC_E_OK) { tls->lasterror = ret; return 0; } tls->sft->QueryContextAttributes(&(tls->hctxt), SECPKG_ATTR_STREAM_SIZES, &(tls->spcss)); tls->recvbuffermaxlen = tls->spcss.cbHeader + tls->spcss.cbMaximumMessage + tls->spcss.cbTrailer; tls->recvbuffer = xmpp_alloc(tls->ctx, tls->recvbuffermaxlen); tls->recvbufferpos = 0; tls->sendbuffermaxlen = tls->spcss.cbHeader + tls->spcss.cbMaximumMessage + tls->spcss.cbTrailer; tls->sendbuffer = xmpp_alloc(tls->ctx, tls->sendbuffermaxlen); tls->sendbufferpos = 0; tls->sendbufferlen = 0; tls->readybuffer = xmpp_alloc(tls->ctx, tls->spcss.cbMaximumMessage); tls->readybufferpos = 0; tls->readybufferlen = 0; return 1; } int tls_stop(tls_t *tls) { return -1; } int tls_error(tls_t *tls) { return tls->lasterror; } int tls_is_recoverable(int error) { return (error == SEC_E_OK || error == SEC_E_INCOMPLETE_MESSAGE || error == WSAEWOULDBLOCK || error == WSAEMSGSIZE || error == WSAEINPROGRESS); } int tls_pending(tls_t *tls) { // There are 3 cases: // - there is data in ready buffer, so it is by default pending // - there is data in recv buffer. If it is not decrypted yet, means it // was incomplete. This should be processed again only if there is data // on the physical connection // - there is data on the physical connection. This case is treated // outside the tls (in event.c) if (tls->readybufferpos < tls->readybufferlen) { return tls->readybufferlen - tls->readybufferpos; } return 0; } int tls_read(tls_t *tls, void * const buff, const size_t len) { int bytes; /* first, if we've got some ready data, put that in the buffer */ if (tls->readybufferpos < tls->readybufferlen) { if (len < tls->readybufferlen - tls->readybufferpos) { bytes = len; } else { bytes = tls->readybufferlen - tls->readybufferpos; } memcpy(buff, tls->readybuffer + tls->readybufferpos, bytes); if (len < tls->readybufferlen - tls->readybufferpos) { tls->readybufferpos += bytes; return bytes; } else { unsigned char *newbuff = buff; int read; tls->readybufferpos += bytes; newbuff += bytes; read = tls_read(tls, newbuff, len - bytes); if (read == -1) { if (tls_is_recoverable(tls->lasterror)) { return bytes; } return -1; } return bytes + read; } } /* next, top up our recv buffer */ bytes = sock_read(tls->sock, tls->recvbuffer + tls->recvbufferpos, tls->recvbuffermaxlen - tls->recvbufferpos); if (bytes == 0) { tls->lasterror = WSAECONNRESET; return -1; } if (bytes == -1) { if (!tls_is_recoverable(sock_error())) { tls->lasterror = sock_error(); return -1; } } if (bytes > 0) { tls->recvbufferpos += bytes; } /* next, try to decrypt the recv buffer */ if (tls->recvbufferpos > 0) { SecBufferDesc sbddec; SecBuffer sbdec[4]; int ret; memset(&sbddec, 0, sizeof(sbddec)); sbddec.ulVersion = SECBUFFER_VERSION; sbddec.cBuffers = 4; sbddec.pBuffers = sbdec; memset(&(sbdec[0]), 0, sizeof(sbdec[0])); sbdec[0].BufferType = SECBUFFER_DATA; sbdec[0].pvBuffer = tls->recvbuffer; sbdec[0].cbBuffer = tls->recvbufferpos; memset(&(sbdec[1]), 0, sizeof(sbdec[1])); sbdec[1].BufferType = SECBUFFER_EMPTY; memset(&(sbdec[2]), 0, sizeof(sbdec[2])); sbdec[2].BufferType = SECBUFFER_EMPTY; memset(&(sbdec[3]), 0, sizeof(sbdec[3])); sbdec[3].BufferType = SECBUFFER_EMPTY; ret = tls->sft->DecryptMessage(&(tls->hctxt), &sbddec, 0, NULL); if (ret == SEC_E_OK) { memcpy(tls->readybuffer, sbdec[1].pvBuffer, sbdec[1].cbBuffer); tls->readybufferpos = 0; tls->readybufferlen = sbdec[1].cbBuffer; /* have we got some data left over? If so, copy it to the start * of the recv buffer */ if (sbdec[3].BufferType == SECBUFFER_EXTRA) { memcpy(tls->recvbuffer, sbdec[3].pvBuffer, sbdec[3].cbBuffer); tls->recvbufferpos = sbdec[3].cbBuffer; } else { tls->recvbufferpos = 0; } return tls_read(tls, buff, len); } else if (ret == SEC_E_INCOMPLETE_MESSAGE) { tls->lasterror = SEC_E_INCOMPLETE_MESSAGE; return -1; } else if (ret == SEC_I_RENEGOTIATE) { ret = tls_start(tls); if (!ret) { return -1; } /* fake an incomplete message so we're called again */ tls->lasterror = SEC_E_INCOMPLETE_MESSAGE; return -1; } /* something bad happened, so we bail */ tls->lasterror = ret; return -1; } tls->lasterror = SEC_E_INCOMPLETE_MESSAGE; return -1; } int tls_clear_pending_write(tls_t *tls) { if (tls->sendbufferpos < tls->sendbufferlen) { int bytes; bytes = sock_write(tls->sock, tls->sendbuffer + tls->sendbufferpos, tls->sendbufferlen - tls->sendbufferpos); if (bytes == -1) { tls->lasterror = sock_error(); return -1; } else if (bytes > 0) { tls->sendbufferpos += bytes; } if (tls->sendbufferpos < tls->sendbufferlen) { return 0; } } return 1; } int tls_write(tls_t *tls, const void * const buff, const size_t len) { SecBufferDesc sbdenc; SecBuffer sbenc[4]; unsigned char *sendbuffer; const unsigned char *p = buff; int sent = 0, ret, remain = len; ret = tls_clear_pending_write(tls); if (ret <= 0) { return ret; } tls->sendbufferpos = 0; tls->sendbufferlen = 0; memset(&sbdenc, 0, sizeof(sbdenc)); sbdenc.ulVersion = SECBUFFER_VERSION; sbdenc.cBuffers = 4; sbdenc.pBuffers = sbenc; memset(&(sbenc[0]), 0, sizeof(sbenc[0])); sbenc[0].BufferType = SECBUFFER_STREAM_HEADER; memset(&(sbenc[1]), 0, sizeof(sbenc[1])); sbenc[1].BufferType = SECBUFFER_DATA; memset(&(sbenc[2]), 0, sizeof(sbenc[2])); sbenc[2].BufferType = SECBUFFER_STREAM_TRAILER; memset(&(sbenc[3]), 0, sizeof(sbenc[3])); sbenc[3].BufferType = SECBUFFER_EMPTY; sbenc[0].pvBuffer = tls->sendbuffer; sbenc[0].cbBuffer = tls->spcss.cbHeader; sbenc[1].pvBuffer = tls->sendbuffer + tls->spcss.cbHeader; while (remain > 0) { if (remain > tls->spcss.cbMaximumMessage) { sbenc[1].cbBuffer = tls->spcss.cbMaximumMessage; } else { sbenc[1].cbBuffer = remain; } sbenc[2].pvBuffer = (unsigned char *)sbenc[1].pvBuffer + sbenc[1].cbBuffer; sbenc[2].cbBuffer = tls->spcss.cbTrailer; memcpy(sbenc[1].pvBuffer, p, sbenc[1].cbBuffer); p += tls->spcss.cbMaximumMessage; tls->sendbufferlen = sbenc[0].cbBuffer + sbenc[1].cbBuffer + sbenc[2].cbBuffer; ret = tls->sft->EncryptMessage(&(tls->hctxt), 0, &sbdenc, 0); if (ret != SEC_E_OK) { tls->lasterror = ret; return -1; } tls->sendbufferpos = 0; ret = tls_clear_pending_write(tls); if (ret == -1 && !tls_is_recoverable(tls_error(tls))) { return -1; } if (remain > tls->spcss.cbMaximumMessage) { sent += tls->spcss.cbMaximumMessage; remain -= tls->spcss.cbMaximumMessage; } else { sent += remain; remain = 0; } if (ret == 0 || (ret == -1 && tls_is_recoverable(tls_error(tls)))) { return sent; } } return sent; } libstrophe-0.8.8/src/util.c000066400000000000000000000050211256471717200156240ustar00rootroot00000000000000/* util.c ** strophe XMPP client library -- various utility functions ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Utility functions. */ #include #include #ifdef _WIN32 #include #else #include #include #endif #include "strophe.h" #include "common.h" #include "ostypes.h" #include "util.h" /** implement our own strdup that uses the ctx allocator */ /** Duplicate a string. * This function replaces the standard strdup library call with a version * that uses the Strophe context object's allocator. * * @param ctx a Strophe context object * @param s a string * * @return a new allocates string with the same data as s or NULL on error */ char *xmpp_strdup(const xmpp_ctx_t * const ctx, const char * const s) { size_t len; char *copy; len = strlen(s); copy = xmpp_alloc(ctx, len + 1); if (!copy) { xmpp_error(ctx, "xmpp", "failed to allocate required memory"); return NULL; } memcpy(copy, s, len + 1); return copy; } /** Return an integer based time stamp. * This function uses gettimeofday or timeGetTime (on Win32 platforms) to * compute an integer based time stamp. This is used internally by the * event loop and timed handlers. * * @return an integer time stamp */ uint64_t time_stamp(void) { #ifdef _WIN32 return timeGetTime(); #else struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)tv.tv_sec * 1000 + (uint64_t)tv.tv_usec / 1000; #endif } /** Get the time elapsed between two time stamps. * This function returns the time elapsed between t1 and t2 by subtracting * t1 from t2. If t2 happened before t1, the result will be negative. This * function is used internally by the event loop and timed handlers. * * @param t1 first time stamp * @param t2 second time stamp * * @return number of milliseconds between the stamps */ uint64_t time_elapsed(uint64_t t1, uint64_t t2) { return (uint64_t)(t2 - t1); } /** Disconnect the stream with a memory error. * This is a convenience function used internally by various parts of * the Strophe library for terminating the connection because of a * memory error. * * @param conn a Strophe connection object */ void disconnect_mem_error(xmpp_conn_t * const conn) { xmpp_error(conn->ctx, "xmpp", "Memory allocation error"); xmpp_disconnect(conn); } libstrophe-0.8.8/src/util.h000066400000000000000000000010471256471717200156350ustar00rootroot00000000000000/* util.h ** strophe XMPP client library -- various utility functions ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Internally used utility functions. */ #ifndef __LIBSTROPHE_UTIL_H__ #define __LIBSTROPHE_UTIL_H__ #include "ostypes.h" /* timing functions */ uint64_t time_stamp(void); uint64_t time_elapsed(uint64_t t1, uint64_t t2); #endif /* __LIBSTROPHE_UTIL_H__ */ libstrophe-0.8.8/strophe.h000066400000000000000000000255621256471717200155650ustar00rootroot00000000000000/* strophe.h ** strophe XMPP client library C API ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express or ** implied. ** ** This software is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Strophe public C API definitions. */ #ifndef __LIBSTROPHE_STROPHE_H__ #define __LIBSTROPHE_STROPHE_H__ #ifdef __cplusplus extern "C" { #endif #include /* namespace defines */ /** @def XMPP_NS_CLIENT * Namespace definition for 'jabber:client'. */ #define XMPP_NS_CLIENT "jabber:client" /** @def XMPP_NS_COMPONENT * Namespace definition for 'jabber:component:accept'. */ #define XMPP_NS_COMPONENT "jabber:component:accept" /** @def XMPP_NS_STREAMS * Namespace definition for 'http://etherx.jabber.org/streams'. */ #define XMPP_NS_STREAMS "http://etherx.jabber.org/streams" /** @def XMPP_NS_STREAMS_IETF * Namespace definition for 'urn:ietf:params:xml:ns:xmpp-streams'. */ #define XMPP_NS_STREAMS_IETF "urn:ietf:params:xml:ns:xmpp-streams" /** @def XMPP_NS_TLS * Namespace definition for 'url:ietf:params:xml:ns:xmpp-tls'. */ #define XMPP_NS_TLS "urn:ietf:params:xml:ns:xmpp-tls" /** @def XMPP_NS_SASL * Namespace definition for 'urn:ietf:params:xml:ns:xmpp-sasl'. */ #define XMPP_NS_SASL "urn:ietf:params:xml:ns:xmpp-sasl" /** @def XMPP_NS_BIND * Namespace definition for 'urn:ietf:params:xml:ns:xmpp-bind'. */ #define XMPP_NS_BIND "urn:ietf:params:xml:ns:xmpp-bind" /** @def XMPP_NS_SESSION * Namespace definition for 'urn:ietf:params:xml:ns:xmpp-session'. */ #define XMPP_NS_SESSION "urn:ietf:params:xml:ns:xmpp-session" /** @def XMPP_NS_AUTH * Namespace definition for 'jabber:iq:auth'. */ #define XMPP_NS_AUTH "jabber:iq:auth" /** @def XMPP_NS_DISCO_INFO * Namespace definition for 'http://jabber.org/protocol/disco#info'. */ #define XMPP_NS_DISCO_INFO "http://jabber.org/protocol/disco#info" /** @def XMPP_NS_DISCO_ITEMS * Namespace definition for 'http://jabber.org/protocol/disco#items'. */ #define XMPP_NS_DISCO_ITEMS "http://jabber.org/protocol/disco#items" /** @def XMPP_NS_ROSTER * Namespace definition for 'jabber:iq:roster'. */ #define XMPP_NS_ROSTER "jabber:iq:roster" /* error defines */ /** @def XMPP_EOK * Success error code. */ #define XMPP_EOK 0 /** @def XMPP_EMEM * Memory related failure error code. * * This is returned on allocation errors and signals that the host may * be out of memory. */ #define XMPP_EMEM -1 /** @def XMPP_EINVOP * Invalid operation error code. * * This error code is returned when the operation was invalid and signals * that the Strophe API is being used incorrectly. */ #define XMPP_EINVOP -2 /** @def XMPP_EINT * Internal failure error code. */ #define XMPP_EINT -3 /* initialization and shutdown */ void xmpp_initialize(void); void xmpp_shutdown(void); /* version */ int xmpp_version_check(int major, int minor); /* run-time contexts */ /* user-replaceable memory allocator */ typedef struct _xmpp_mem_t xmpp_mem_t; /* user-replaceable log object */ typedef struct _xmpp_log_t xmpp_log_t; /* opaque run time context containing the above hooks */ typedef struct _xmpp_ctx_t xmpp_ctx_t; xmpp_ctx_t *xmpp_ctx_new(const xmpp_mem_t * const mem, const xmpp_log_t * const log); void xmpp_ctx_free(xmpp_ctx_t * const ctx); struct _xmpp_mem_t { void *(*alloc)(const size_t size, void * const userdata); void (*free)(void *p, void * const userdata); void *(*realloc)(void *p, const size_t size, void * const userdata); void *userdata; }; typedef enum { XMPP_LEVEL_DEBUG, XMPP_LEVEL_INFO, XMPP_LEVEL_WARN, XMPP_LEVEL_ERROR } xmpp_log_level_t; typedef enum { XMPP_UNKNOWN, XMPP_CLIENT, XMPP_COMPONENT } xmpp_conn_type_t; typedef void (*xmpp_log_handler)(void * const userdata, const xmpp_log_level_t level, const char * const area, const char * const msg); struct _xmpp_log_t { xmpp_log_handler handler; void *userdata; /* mutex_t lock; */ }; /* return a default logger filtering at a given level */ xmpp_log_t *xmpp_get_default_logger(xmpp_log_level_t level); /* connection */ /* opaque connection object */ typedef struct _xmpp_conn_t xmpp_conn_t; typedef struct _xmpp_stanza_t xmpp_stanza_t; /* connect callback */ typedef enum { XMPP_CONN_CONNECT, XMPP_CONN_DISCONNECT, XMPP_CONN_FAIL } xmpp_conn_event_t; typedef enum { XMPP_SE_BAD_FORMAT, XMPP_SE_BAD_NS_PREFIX, XMPP_SE_CONFLICT, XMPP_SE_CONN_TIMEOUT, XMPP_SE_HOST_GONE, XMPP_SE_HOST_UNKNOWN, XMPP_SE_IMPROPER_ADDR, XMPP_SE_INTERNAL_SERVER_ERROR, XMPP_SE_INVALID_FROM, XMPP_SE_INVALID_ID, XMPP_SE_INVALID_NS, XMPP_SE_INVALID_XML, XMPP_SE_NOT_AUTHORIZED, XMPP_SE_POLICY_VIOLATION, XMPP_SE_REMOTE_CONN_FAILED, XMPP_SE_RESOURCE_CONSTRAINT, XMPP_SE_RESTRICTED_XML, XMPP_SE_SEE_OTHER_HOST, XMPP_SE_SYSTEM_SHUTDOWN, XMPP_SE_UNDEFINED_CONDITION, XMPP_SE_UNSUPPORTED_ENCODING, XMPP_SE_UNSUPPORTED_STANZA_TYPE, XMPP_SE_UNSUPPORTED_VERSION, XMPP_SE_XML_NOT_WELL_FORMED } xmpp_error_type_t; typedef struct { xmpp_error_type_t type; char *text; xmpp_stanza_t *stanza; } xmpp_stream_error_t; typedef void (*xmpp_conn_handler)(xmpp_conn_t * const conn, const xmpp_conn_event_t event, const int error, xmpp_stream_error_t * const stream_error, void * const userdata); xmpp_conn_t *xmpp_conn_new(xmpp_ctx_t * const ctx); xmpp_conn_t * xmpp_conn_clone(xmpp_conn_t * const conn); int xmpp_conn_release(xmpp_conn_t * const conn); const char *xmpp_conn_get_jid(const xmpp_conn_t * const conn); const char *xmpp_conn_get_bound_jid(const xmpp_conn_t * const conn); void xmpp_conn_set_jid(xmpp_conn_t * const conn, const char * const jid); const char *xmpp_conn_get_pass(const xmpp_conn_t * const conn); void xmpp_conn_set_pass(xmpp_conn_t * const conn, const char * const pass); xmpp_ctx_t* xmpp_conn_get_context(xmpp_conn_t * const conn); void xmpp_conn_disable_tls(xmpp_conn_t * const conn); int xmpp_connect_client(xmpp_conn_t * const conn, const char * const altdomain, unsigned short altport, xmpp_conn_handler callback, void * const userdata); int xmpp_connect_component(xmpp_conn_t * const conn, const char * const server, unsigned short port, xmpp_conn_handler callback, void * const userdata); void xmpp_disconnect(xmpp_conn_t * const conn); void xmpp_send(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza); void xmpp_send_raw_string(xmpp_conn_t * const conn, const char * const fmt, ...); void xmpp_send_raw(xmpp_conn_t * const conn, const char * const data, const size_t len); /* handlers */ /* if the handle returns false it is removed */ typedef int (*xmpp_timed_handler)(xmpp_conn_t * const conn, void * const userdata); void xmpp_timed_handler_add(xmpp_conn_t * const conn, xmpp_timed_handler handler, const unsigned long period, void * const userdata); void xmpp_timed_handler_delete(xmpp_conn_t * const conn, xmpp_timed_handler handler); /* if the handler returns false it is removed */ typedef int (*xmpp_handler)(xmpp_conn_t * const conn, xmpp_stanza_t * const stanza, void * const userdata); void xmpp_handler_add(xmpp_conn_t * const conn, xmpp_handler handler, const char * const ns, const char * const name, const char * const type, void * const userdata); void xmpp_handler_delete(xmpp_conn_t * const conn, xmpp_handler handler); void xmpp_id_handler_add(xmpp_conn_t * const conn, xmpp_handler handler, const char * const id, void * const userdata); void xmpp_id_handler_delete(xmpp_conn_t * const conn, xmpp_handler handler, const char * const id); /* void xmpp_register_stanza_handler(conn, stanza, xmlns, type, handler) */ /** stanzas **/ /** allocate an initialize a blank stanza */ xmpp_stanza_t *xmpp_stanza_new(xmpp_ctx_t *ctx); /** clone a stanza */ xmpp_stanza_t *xmpp_stanza_clone(xmpp_stanza_t * const stanza); /** copies a stanza and all children */ xmpp_stanza_t * xmpp_stanza_copy(const xmpp_stanza_t * const stanza); /** free a stanza object and it's contents */ int xmpp_stanza_release(xmpp_stanza_t * const stanza); /** free some blocks returned by other APIs, for example the buffer you get from xmpp_stanza_to_text **/ void xmpp_free(const xmpp_ctx_t * const ctx, void *p); int xmpp_stanza_is_text(xmpp_stanza_t * const stanza); int xmpp_stanza_is_tag(xmpp_stanza_t * const stanza); /** marshall a stanza into text for transmission or display **/ int xmpp_stanza_to_text(xmpp_stanza_t *stanza, char ** const buf, size_t * const buflen); xmpp_stanza_t *xmpp_stanza_get_children(xmpp_stanza_t * const stanza); xmpp_stanza_t *xmpp_stanza_get_child_by_name(xmpp_stanza_t * const stanza, const char * const name); xmpp_stanza_t *xmpp_stanza_get_child_by_ns(xmpp_stanza_t * const stanza, const char * const ns); xmpp_stanza_t *xmpp_stanza_get_next(xmpp_stanza_t * const stanza); char *xmpp_stanza_get_attribute(xmpp_stanza_t * const stanza, const char * const name); char * xmpp_stanza_get_ns(xmpp_stanza_t * const stanza); /* concatenate all child text nodes. this function * returns a string that must be freed by the caller */ char *xmpp_stanza_get_text(xmpp_stanza_t * const stanza); char *xmpp_stanza_get_text_ptr(xmpp_stanza_t * const stanza); char *xmpp_stanza_get_name(xmpp_stanza_t * const stanza); int xmpp_stanza_add_child(xmpp_stanza_t *stanza, xmpp_stanza_t *child); int xmpp_stanza_set_ns(xmpp_stanza_t * const stanza, const char * const ns); /* set_attribute adds/replaces attributes */ int xmpp_stanza_set_attribute(xmpp_stanza_t * const stanza, const char * const key, const char * const value); int xmpp_stanza_set_name(xmpp_stanza_t *stanza, const char * const name); int xmpp_stanza_set_text(xmpp_stanza_t *stanza, const char * const text); int xmpp_stanza_set_text_with_size(xmpp_stanza_t *stanza, const char * const text, const size_t size); /* common stanza helpers */ char *xmpp_stanza_get_type(xmpp_stanza_t * const stanza); char *xmpp_stanza_get_id(xmpp_stanza_t * const stanza); int xmpp_stanza_set_id(xmpp_stanza_t * const stanza, const char * const id); int xmpp_stanza_set_type(xmpp_stanza_t * const stanza, const char * const type); /* unimplemented int xmpp_stanza_set_to(); int xmpp_stanza_set_from(); */ /* allocate and initialize a stanza in reply to another */ /* unimplemented xmpp_stanza_t *xmpp_stanza_reply(const xmpp_stanza_t *stanza); */ /* stanza subclasses */ /* unimplemented void xmpp_message_new(); void xmpp_message_get_body(); void xmpp_message_set_body(); void xmpp_iq_new(); void xmpp_presence_new(); */ /** event loop **/ void xmpp_run_once(xmpp_ctx_t *ctx, const unsigned long timeout); void xmpp_run(xmpp_ctx_t *ctx); void xmpp_stop(xmpp_ctx_t *ctx); #ifdef __cplusplus } #endif #endif /* __LIBSTROPHE_STROPHE_H__ */ libstrophe-0.8.8/strophepp.h000066400000000000000000000065121256471717200161170ustar00rootroot00000000000000/* strophepp.h ** strophe XMPP client library C++ API ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express or ** implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ /** @file * Strophe public C++ API definitions. */ #ifndef __LIBSTROPHE_STROPHEPP_H__ #define __LIBSTROPHE_STROPHEPP_H__ #include "strophe.h" namespace XMPP { class Context { private: xmpp_mem_t m_mem; xmpp_log_t m_log; xmpp_ctx_t *m_ctx; public: Context(); virtual ~Context(); virtual void *alloc(const size_t size); virtual void *realloc(void *p, const size_t size); virtual void free(void *p); virtual void log(const xmpp_log_level_t level, const char * const area, const char * const msg); xmpp_ctx_t *getContext(); private: static void *callAlloc(const size_t size, void * const userdata); static void *callRealloc(void *p, const size_t size, void * const userdata); static void callFree(void *p, void * const userdata); static void callLog(void * const userdata, const xmpp_log_level_t level, const char * const area, const char * const msg); }; class Stanza { private: Context *m_ctx; xmpp_stanza_t *m_stanza; void *operator new(size_t size, Context *ctx); void operator delete(void *p); Stanza(Context *ctx); virtual ~Stanza(); public: static Stanza *create(Context *ctx); void release(); Stanza *clone(); Stanza *copy(); int toText(const char ** const buf, size_t * const buflen); Stanza *getChildren(); Stanza *getChildByName(const char * const name); Stanza *getNext(); char *getAttribute(const char * const name); char *getNamespace(); char *getText(); char *getName(); void addChild(Stanza *child); void setNamespace(const char * const ns); void setAttribute(const char * const key, const char * const value); void setName(const char * const name); void setText(const char * const text); void setText(const char * const text, const size_t size); char *getType(); char *getId(); char *getTo(); char *getFrom(); void setType(const char * const type); void setId(const char * const id); void setTo(const char * const to); void setFrom(const char * const from); }; class Connection { private: Context *m_ctx; xmpp_conn_t *conn; void *operator new(size_t size, Context *ctx); Connection(Context *ctx); public: static Connection *create(Context *ctx); virtual ~Connection(); Connection *clone(); void operator delete(void *p); const char *getJID(); void setJID(const char * const jid); const char *getPass(); void setPass(const char * const pass); bool connectClient(const char * const domain, xmpp_conn_handler callback, void * const userdata); void disconnect(); void send(Stanza *stanza); void addTimedHandler(xmpp_timed_handler handler, const unsigned long perdio, void * const userdata); void deleteTimedHandler(xmpp_timed_handler handler); void addHandler(xmpp_handler handler, const char * const ns, const char * const name, const char * const type, void * const userdata); void deleteHandler(xmpp_handler handler); void addIdHandler(xmpp_handler handler, const char * const id, void * const userdata); void deleteIdHandler(xmpp_handler handler); }; } #endif /* __LIBSTROPHE_STROPHEPP_H__ */ libstrophe-0.8.8/tests/000077500000000000000000000000001256471717200150605ustar00rootroot00000000000000libstrophe-0.8.8/tests/check_parser.c000066400000000000000000000037471256471717200176700ustar00rootroot00000000000000/* check_parser.h ** strophe XMPP client library -- parser tests ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express or ** implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include #include #include #include "parser.h" #include "test.h" START_TEST(create_destroy) { xmpp_ctx_t *ctx; parser_t *parser; ctx = xmpp_ctx_new(NULL, NULL); parser = parser_new(ctx, NULL, NULL, NULL, NULL); fail_unless(parser != NULL, "Parser creation failed."); parser_free(parser); xmpp_ctx_free(ctx); } END_TEST int cbtest_got_start = 0; void cbtest_handle_start(char *name, char **attrs, void *userdata) { if (strcmp(name, "stream") == 0) cbtest_got_start = 1; } int cbtest_got_end = 0; void cbtest_handle_end(char *name, void *userdata) { if (strcmp(name, "stream") == 0) cbtest_got_end = 1; } int cbtest_got_stanza = 0; void cbtest_handle_stanza(xmpp_stanza_t *stanza, void *userdata) { if (strcmp(xmpp_stanza_get_name(stanza), "message") == 0) cbtest_got_stanza = 1; } START_TEST(callbacks) { xmpp_ctx_t *ctx; parser_t *parser; int ret; ctx = xmpp_ctx_new(NULL, NULL); parser = parser_new(ctx, cbtest_handle_start, cbtest_handle_end, cbtest_handle_stanza, NULL); ret = parser_feed(parser, "", 8); ret = parser_feed(parser, "", 10); parser_feed(parser, "", 9); fail_unless(cbtest_got_start == 1); fail_unless(cbtest_got_end == 1); fail_unless(cbtest_got_stanza == 1); parser_free(parser); xmpp_ctx_free(ctx); } END_TEST Suite *parser_suite(void) { Suite *s = suite_create("Parser"); TCase *tc_core = tcase_create("Core"); tcase_add_test(tc_core, create_destroy); tcase_add_test(tc_core, callbacks); suite_add_tcase(s, tc_core); return s; } TEST_MAIN libstrophe-0.8.8/tests/test.h000066400000000000000000000006531256471717200162140ustar00rootroot00000000000000#ifndef __LIBSTROPHE_TEST_H__ #define __LIBSTROPHE_TEST_H__ #define TEST_MAIN \ int main(int argc, char **argv) {\ int num_failed;\ Suite *s = parser_suite();\ SRunner *sr = srunner_create(s);\ srunner_run_all(sr, CK_NORMAL);\ num_failed = srunner_ntests_failed(sr);\ srunner_free(sr);\ return (num_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE;\ }\ #endif /* __LIBSTROPHE_TEST_H__ */ libstrophe-0.8.8/tests/test_base64.c000066400000000000000000000115351256471717200173540ustar00rootroot00000000000000/* test_base64.c ** libstrophe XMPP client library -- test routines for the base64 codec ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include #include #include "strophe.h" #include "common.h" #include "sasl.h" static const unsigned char text_1[] = "How now brown cow?"; static const char base64_1[] = "SG93IG5vdyBicm93biBjb3c/"; static const unsigned char text_2[] = {0x14,0xfb,0x9c,0x03,0xd9,0x7e,0x00}; static const char base64_2[] = "FPucA9l+"; static const unsigned char text_3[] = "From rest and sleep, which but thy pictures be, " "Much pleasure; then from thee much more must flow, " "And soonest our best men with thee do go, " "Rest of their bones, and soul's delivery."; static const char base64_3[] = "RnJvbSByZXN0IGFuZCBzbGVlcCwgd2hpY2ggYnV0IHRoeSBwaWN0dXJl" "cyBiZSwgTXVjaCBwbGVhc3VyZTsgdGhlbiBmcm9tIHRoZWUgbXVjaCBt" "b3JlIG11c3QgZmxvdywgQW5kIHNvb25lc3Qgb3VyIGJlc3QgbWVuIHdp" "dGggdGhlZSBkbyBnbywgUmVzdCBvZiB0aGVpciBib25lcywgYW5kIHNv" "dWwncyBkZWxpdmVyeS4="; static const unsigned char text_4[] = {0xd6, 0x2f, 0x27, 0x49, 0x7e, 0xdd, 0xf3, 0xd5, 0x41, 0xbc, 0x1b, 0xe9, 0xdf, 0xe9, 0xb3, 0x08, 0x00}; static const char base64_4[] = "1i8nSX7d89VBvBvp3+mzCA=="; static const char text_5[] = "realm=\"chesspark.com\",nonce=\"b243c0d663257a9149999cef2f83a22116559e93\",qop=\"auth\",charset=utf-8,algorithm=md5-sess"; static const char base64_5[] = "cmVhbG09ImNoZXNzcGFyay5jb20iLG5vbmNlPSJiMjQzYzBkNjYzMjU3" "YTkxNDk5OTljZWYyZjgzYTIyMTE2NTU5ZTkzIixxb3A9ImF1dGgiLGNo" "YXJzZXQ9dXRmLTgsYWxnb3JpdGhtPW1kNS1zZXNz"; int test_encode(xmpp_ctx_t *ctx) { char *result; result = base64_encode(ctx, text_1, strlen(text_1)); if (result == NULL) return 2; if (strlen(result) != strlen(base64_1)) return 1; if (strncmp(base64_1, result, strlen(base64_1))) return 1; xmpp_free(ctx,result); result = base64_encode(ctx, text_2, strlen(text_2)); if (result == NULL) return 2; if (strlen(result) != strlen(base64_2)) return 1; if (strncmp(base64_2, result, strlen(base64_2))) return 1; xmpp_free(ctx,result); result = base64_encode(ctx, text_3, strlen(text_3)); if (result == NULL) return 2; if (strlen(result) != strlen(base64_3)) return 1; if (strncmp(base64_3, result, strlen(base64_3))) return 1; xmpp_free(ctx,result); result = base64_encode(ctx, text_4, strlen(text_4)); if (result == NULL) return 2; if (strlen(result) != strlen(base64_4)) return 1; if (strncmp(base64_4, result, strlen(base64_4))) return 1; xmpp_free(ctx,result); result = base64_encode(ctx, text_5, strlen(text_5)); if (result == NULL) return 2; if (strlen(result) != strlen(base64_5)) return 1; if (strncmp(base64_5, result, strlen(base64_5))) return 1; xmpp_free(ctx,result); return 0; } int test_decode(xmpp_ctx_t *ctx) { unsigned char *result; result = base64_decode(ctx, base64_1, strlen(base64_1)); if (result == NULL) return 2; if (strlen(result) != strlen(text_1)) return 1; if (strncmp(text_1, result, strlen(text_1))) return 1; xmpp_free(ctx,result); result = base64_decode(ctx, base64_2, strlen(base64_2)); if (result == NULL) return 2; if (strlen(result) != strlen(text_2)) return 1; if (strncmp(text_2, result, strlen(text_2))) return 1; xmpp_free(ctx,result); result = base64_decode(ctx, base64_3, strlen(base64_3)); if (result == NULL) return 2; if (strlen(result) != strlen(text_3)) return 1; if (strncmp(text_3, result, strlen(text_3))) return 1; xmpp_free(ctx,result); result = base64_decode(ctx, base64_4, strlen(base64_4)); if (result == NULL) return 2; if (strlen(result) != strlen(text_4)) return 1; if (strncmp(text_4, result, strlen(text_4))) return 1; xmpp_free(ctx,result); result = base64_decode(ctx, base64_5, strlen(base64_5)); if (result == NULL) return 2; if (strlen(result) != strlen(text_5)) return 1; if (strncmp(text_5, result, strlen(text_5))) return 1; xmpp_free(ctx,result); return 0; } int main(int argc, char *argv[]) { xmpp_ctx_t *ctx; int ret; printf("allocating context... "); ctx = xmpp_ctx_new(NULL, NULL); if (ctx == NULL) printf("failed to create context\n"); if (ctx == NULL) return -1; printf("ok.\n"); printf("testing encode... "); ret = test_encode(ctx); if (ret) printf("base64_encode failed!\n"); if (ret) return ret; printf("ok.\n"); printf("testing decode... "); ret = test_decode(ctx); if (ret) printf("base64_decode failed!\n"); if (ret) return ret; printf("ok.\n"); printf("freeing context... "); xmpp_ctx_free(ctx); printf("ok.\n"); return ret; } libstrophe-0.8.8/tests/test_ctx.c000066400000000000000000000041771256471717200170720ustar00rootroot00000000000000/* test_ctx.c ** libstrophe XMPP client library -- test routines for the library run-time context ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include #include #include #include "strophe.h" #include "common.h" static int log_called = 0; static int mem_alloc_called = 0; static int mem_free_called = 0; static int mem_realloc_called = 0; void *my_alloc(const size_t size, void * const userdata) { mem_alloc_called++; return malloc(size); } void my_free(void *p, void * const userdata) { mem_free_called++; return free(p); } void *my_realloc(void *p, const size_t size, void * const userdata) { mem_realloc_called++; return realloc(p, size); } void my_logger(void * const userdata, const xmpp_log_level_t level, const char * const area, const char * const msg) { if (strcmp((char *)userdata, "asdf") == 0 && level == XMPP_LEVEL_DEBUG && strcmp(area, "test") == 0 && strcmp(msg, "hello") == 0) log_called++; } int main(int argc, char **argv) { xmpp_ctx_t *ctx; xmpp_mem_t mymem; xmpp_log_t mylog; char my_str[5] = "asdf"; void *testptr1, *testptr2; ctx = xmpp_ctx_new(NULL, NULL); if (ctx == NULL) return 1; /* destroy context */ xmpp_ctx_free(ctx); /* setup our memory handler */ mymem.alloc = my_alloc; mymem.free = my_free; mymem.realloc = my_realloc; /* setup our logger */ mylog.handler = my_logger; mylog.userdata = my_str; ctx = xmpp_ctx_new(&mymem, &mylog); xmpp_debug(ctx, "test", "hello"); testptr1 = xmpp_alloc(ctx, 1024); if (testptr1 == NULL) { xmpp_ctx_free(ctx); return 1; } testptr2 = xmpp_realloc(ctx, testptr1, 2048); if (testptr2 == NULL) { xmpp_free(ctx, testptr1); xmpp_ctx_free(ctx); return 1; } xmpp_free(ctx, testptr2); xmpp_ctx_free(ctx); /* check for test failure */ if (!(log_called && mem_alloc_called && mem_realloc_called && mem_free_called)) return 1; return 0; } libstrophe-0.8.8/tests/test_hash.c000066400000000000000000000057471256471717200172230ustar00rootroot00000000000000/* test_hash.c ** libstrophe XMPP client library -- self-test for the hash-table implementation ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include #include #include #include "strophe.h" #include "common.h" #include "hash.h" #define TABLESIZE 100 #define TESTSIZE 500 /* static test data */ const int nkeys = 5; const char *keys[] = { "foo", "bar", "baz", "quux", "xyzzy" }; const char *values[] = { "wuzzle", "mug", "canonical", "rosebud", "lottery" }; int main(int argc, char **argv) { xmpp_ctx_t *ctx; hash_t *table, *clone; hash_iterator_t *iter; unsigned int seed; const char *key; char *result; int err = 0; int i; /* initialize random numbers */ if (argc > 2) { /* use a seed from the command line */ seed = (unsigned int)atoi(argv[1]); } else { seed = (unsigned int)clock(); } /* using random seed 'seed' */ srand(seed); /* allocate a default context */ ctx = xmpp_ctx_new(NULL, NULL); if (ctx == NULL) { /* ctx allocation failed! */ return -1; } /* allocate a hash table */ table = hash_new(ctx, TABLESIZE, NULL); if (table == NULL) { /* table allocation failed! */ return 1; } /* test insertion */ for (i = 0; i < nkeys; i++) { err = hash_add(table, keys[i], (void*)values[i]); if (err) return err; } /* test key count */ if (hash_num_keys(table) != nkeys) { /* wrong number of keys in table! */ return 1; } /* test cloning */ clone = hash_clone(table); /* test lookup */ for (i = 0; i < nkeys; i++) { result = hash_get(clone, keys[i]); if (result == NULL) { /* lookup failed! */ return 1; } if (strcmp(values[i], result)) { /* lookup returned incorrect value! */ return 1; } } /* test key iterator */ iter = hash_iter_new(clone); if (iter == NULL) { /* iterator allocation failed! */ return 1; } for (i = 0; i < nkeys; i++) { key = hash_iter_next(iter); printf("key: '%s'\n", key); } key = hash_iter_next(iter); if (key != NULL) { /* extra keys returned! */ return 1; } key = hash_iter_next(iter); if (key != NULL) { /* extra keys returned! */ return 1; } hash_iter_release(iter); /* release the hash table */ hash_release(table); /* test drops */ hash_drop(clone, keys[2]); if (hash_get(clone, keys[2]) != NULL) return 1; hash_drop(clone, keys[1]); hash_drop(clone, keys[4]); if (hash_get(clone, keys[4]) != NULL) return 1; if (hash_get(clone, keys[1]) != NULL) return 1; /* keys 0,3 should still be available */ if (hash_get(clone, keys[0]) == NULL) return 1; if (hash_get(clone, keys[3]) == NULL) return 1; /* release our clone */ hash_release(clone); /* release our library context */ xmpp_ctx_free(ctx); return err; } libstrophe-0.8.8/tests/test_jid.c000066400000000000000000000067301256471717200170370ustar00rootroot00000000000000/* test_base64.c ** libstrophe XMPP client library -- test routines for the jid utils ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include #include #include "strophe.h" #include "common.h" static const char jid1[] = "foo@bar.com"; static const char jid2[] = "anyone@example.com/hullo"; static const char jid3[] = "manic.porter@xyz.net/frob"; static const char jid4[] = "domain.tld"; int test_jid(xmpp_ctx_t *ctx) { char *node; char *domain; char *resource; node = xmpp_jid_node(ctx, jid1); domain = xmpp_jid_domain(ctx, jid1); resource = xmpp_jid_resource(ctx, jid1); printf("jid '%s' parsed to %s, %s, %s\n", jid1, node, domain, resource); if (strcmp(node, "foo")) return 1; if (strcmp(domain, "bar.com")) return 1; if (resource != NULL) return 1; if (node) xmpp_free(ctx, node); if (domain) xmpp_free(ctx, domain); if (resource) xmpp_free(ctx, resource); node = xmpp_jid_node(ctx, jid2); domain = xmpp_jid_domain(ctx, jid2); resource = xmpp_jid_resource(ctx, jid2); printf("jid '%s' parsed to %s, %s, %s\n", jid2, node, domain, resource); if (strcmp(node, "anyone")) return 1; if (strcmp(domain, "example.com")) return 1; if (strcmp(resource, "hullo")) return 1; if (node) xmpp_free(ctx, node); if (domain) xmpp_free(ctx, domain); if (resource) xmpp_free(ctx, resource); node = xmpp_jid_node(ctx, jid3); domain = xmpp_jid_domain(ctx, jid3); resource = xmpp_jid_resource(ctx, jid3); printf("jid '%s' parsed to %s, %s, %s\n", jid3, node, domain, resource); if (strcmp(node, "manic.porter")) return 1; if (strcmp(domain, "xyz.net")) return 1; if (strcmp(resource, "frob")) return 1; if (node) xmpp_free(ctx, node); if (domain) xmpp_free(ctx, domain); if (resource) xmpp_free(ctx, resource); node = xmpp_jid_node(ctx, jid4); domain = xmpp_jid_domain(ctx, jid4); resource = xmpp_jid_resource(ctx, jid4); printf("jid '%s' parsed to %s, %s, %s\n", jid4, node, domain, resource); if (node != NULL) return 1; if (strcmp(domain, "domain.tld")) return 1; if (resource != NULL) return 1; if (node) xmpp_free(ctx, node); if (domain) xmpp_free(ctx, domain); if (resource) xmpp_free(ctx, resource); return 0; } int test_jid_new(xmpp_ctx_t *ctx) { char *jid; jid = xmpp_jid_new(ctx, "node", "domain", "resource"); printf("new jid: '%s'\n", jid); if (strcmp(jid, "node@domain/resource")) return 1; xmpp_free(ctx, jid); jid = xmpp_jid_new(ctx, "foo", "bar.com", NULL); printf("new jid: '%s'\n", jid); if (strcmp(jid, "foo@bar.com")) return 1; xmpp_free(ctx, jid); return 0; } int main(int argc, char *argv[]) { xmpp_ctx_t *ctx; int ret; printf("allocating context... "); ctx = xmpp_ctx_new(NULL, NULL); if (ctx == NULL) printf("failed to create context\n"); if (ctx == NULL) return -1; printf("ok.\n"); printf("testing jid routines... "); ret = test_jid(ctx); if (ret) printf("failed!\n"); if (ret) return ret; printf("ok.\n"); printf("testing jid new routines... "); ret = test_jid_new(ctx); if (ret) printf("failed!\n"); if (ret) return ret; printf("ok.\n"); printf("freeing context... "); xmpp_ctx_free(ctx); printf("ok.\n"); return ret; } libstrophe-0.8.8/tests/test_sasl.c000066400000000000000000000062101256471717200172240ustar00rootroot00000000000000/* test_sasl.c ** libstrophe XMPP client library -- test routines for the SASL implementation ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include #include #include "strophe.h" #include "common.h" #include "sasl.h" static const unsigned char jid[] = "foo@bar.com"; static const char password[] = "secret"; static const char response_plain[] = "AGZvb0BiYXIuY29tAHNlY3JldA=="; static const char challenge_md5[] = "cmVhbG09InNvbWVyZWFsbSIsbm9uY2U9Ik9BNk1HOXRFUUdtMmhoIixxb3A9ImF1dGgi" "LGNoYXJzZXQ9dXRmLTgsYWxnb3JpdGhtPW1kNS1zZXNzCg=="; static const char response_md5[] = "dXNlcm5hbWU9InNvbWVub2RlIixyZWFsbT0ic29tZXJlYWxtIixub25jZT0i" "T0E2TUc5dEVRR20yaGgiLGNub25jZT0iMDBERUFEQkVFRjAwIixuYz0wMDAw" "MDAwMSxxb3A9YXV0aCxkaWdlc3QtdXJpPSJ4bXBwL3NvbWVyZWFsbSIscmVz" "cG9uc2U9NGVhNmU4N2JjMDkzMzUwNzQzZGIyOGQ3MDIwOGNhZmIsY2hhcnNl" "dD11dGYtOA=="; static const char response_md5_rfc[] = "dXNlcm5hbWU9InNvbWVub2RlIixyZWFsbT0ic29tZXJlYWxtIixub25jZT0i" "T0E2TUc5dEVRR20yaGgiLGNub25jZT0iT0E2TUhYaDZWcVRyUmsiLG5jPTAw" "MDAwMDAxLHFvcD1hdXRoLGRpZ2VzdC11cmk9InhtcHAvZXhhbXBsZS5jb20i" "LHJlc3BvbnNlPWQzODhkYWQ5MGQ0YmJkNzYwYTE1MjMyMWYyMTQzYWY3LGNo" "YXJzZXQ9dXRmLTgK"; static const char challenge_md5_2[] = "cmVhbG09ImVsd29vZC5pbm5vc29mdC5jb20iLG5vbmNlPSJPQTZNRzl0" "RVFHbTJoaCIscW9wPSJhdXRoIixhbGdvcml0aG09bWQ1LXNlc3MsY2hh" "cnNldD11dGYtOA=="; static const char response_md5_2[] = "Y2hhcnNldD11dGYtOCx1c2VybmFtZT0iY2hyaXMiLHJlYWxtPSJlbHdvb2" "QuaW5ub3NvZnQuY29tIixub25jZT0iT0E2TUc5dEVRR20yaGgiLG5jPTAw" "MDAwMDAxLGNub25jZT0iT0E2TUhYaDZWcVRyUmsiLGRpZ2VzdC11cmk9Im" "ltYXAvZWx3b29kLmlubm9zb2Z0LmNvbSIscmVzcG9uc2U9ZDM4OGRhZDkw" "ZDRiYmQ3NjBhMTUyMzIxZjIxNDNhZjcscW9wPWF1dGg="; int test_plain(xmpp_ctx_t *ctx) { char *result; result = sasl_plain(ctx, jid, password); if (result == NULL) { /* SASL PLAIN internal failure! */ return 1; } if (strncmp(response_plain, result, strlen(response_plain))) { /* SASL PLAIN returned incorrect string! */ return 2; } xmpp_free(ctx, result); return 0; } int test_digest_md5(xmpp_ctx_t *ctx) { char *result; result = sasl_digest_md5(ctx, challenge_md5, "somenode@somerealm", "secret"); printf("response:\n%s\n", result); if (strcmp(response_md5, result)) { /* generated incorrect response to challenge */ return 1; } return 0; } int main(int argc, char *argv[]) { xmpp_ctx_t *ctx; int ret; printf("allocating context... "); ctx = xmpp_ctx_new(NULL, NULL); if (ctx == NULL) printf("failed to create context\n"); if (ctx == NULL) return -1; printf("ok.\n"); printf("testing SASL PLAIN... "); ret = test_plain(ctx); if (ret) printf("failed!\n"); if (ret) return ret; printf("ok.\n"); printf("testing SASL DIGEST-MD5... "); ret = test_digest_md5(ctx); if (ret) printf("failed!\n"); if (ret) return ret; printf("ok.\n"); printf("freeing context... "); xmpp_ctx_free(ctx); printf("ok.\n"); return ret; } libstrophe-0.8.8/tests/test_sock.c000066400000000000000000000021261256471717200172230ustar00rootroot00000000000000/* test_sock.c ** libstrophe XMPP client library -- test routines for the socket abstraction ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include #include #ifndef _WIN32 #include #endif #include "sock.h" int wait_for_connect(sock_t sock) { fd_set wfds, efds; int ret; FD_ZERO(&wfds); FD_SET(sock, &wfds); FD_ZERO(&efds); FD_SET(sock, &efds); ret = select(sock + 1, NULL, &wfds, &efds, NULL); if (ret <= 0) return -1; if (FD_ISSET(sock, &efds)) return 0; if (FD_ISSET(sock, &wfds)) return 1; return -1; } int main(int argc, char **argv) { sock_t sock; int err; sock_initialize(); sock = sock_connect("www.google.com", 80); if (sock < 0) { sock_shutdown(); return 1; } err = wait_for_connect(sock); if (err < 0) { sock_close(sock); sock_shutdown(); return 1; } sock_close(sock); sock_shutdown(); return 0; } libstrophe-0.8.8/vs2008/000077500000000000000000000000001256471717200146605ustar00rootroot00000000000000libstrophe-0.8.8/vs2008/active.vcproj000066400000000000000000000077171256471717200173740ustar00rootroot00000000000000 libstrophe-0.8.8/vs2008/basic.vcproj000066400000000000000000000077141256471717200171770ustar00rootroot00000000000000 libstrophe-0.8.8/vs2008/bot.vcproj000066400000000000000000000077061256471717200167030ustar00rootroot00000000000000 libstrophe-0.8.8/vs2008/expat.vcproj000066400000000000000000000137531256471717200172370ustar00rootroot00000000000000 libstrophe-0.8.8/vs2008/libstrophe.sln000066400000000000000000000100151256471717200175460ustar00rootroot00000000000000 Microsoft Visual Studio Solution File, Format Version 10.00 # Visual C++ Express 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libstrophe", "libstrophe.vcproj", "{659E3B17-B1BF-4D3B-94E6-438F85EBC410}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "active example", "active.vcproj", "{FB499990-F569-426A-9215-5B013D94B70C}" ProjectSection(ProjectDependencies) = postProject {659E3B17-B1BF-4D3B-94E6-438F85EBC410} = {659E3B17-B1BF-4D3B-94E6-438F85EBC410} {AAFBC1E9-6192-46AE-95BC-642DCB20D361} = {AAFBC1E9-6192-46AE-95BC-642DCB20D361} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "basic example", "basic.vcproj", "{7BD355D0-941D-4630-B82F-1FB43A971440}" ProjectSection(ProjectDependencies) = postProject {659E3B17-B1BF-4D3B-94E6-438F85EBC410} = {659E3B17-B1BF-4D3B-94E6-438F85EBC410} {AAFBC1E9-6192-46AE-95BC-642DCB20D361} = {AAFBC1E9-6192-46AE-95BC-642DCB20D361} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "bot example", "bot.vcproj", "{DEE25458-271F-4F9A-8979-C460C64B49C8}" ProjectSection(ProjectDependencies) = postProject {659E3B17-B1BF-4D3B-94E6-438F85EBC410} = {659E3B17-B1BF-4D3B-94E6-438F85EBC410} {AAFBC1E9-6192-46AE-95BC-642DCB20D361} = {AAFBC1E9-6192-46AE-95BC-642DCB20D361} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "roster example", "roster.vcproj", "{5F6591E0-3FAD-45AE-80CF-A47C1F8BA2CC}" ProjectSection(ProjectDependencies) = postProject {659E3B17-B1BF-4D3B-94E6-438F85EBC410} = {659E3B17-B1BF-4D3B-94E6-438F85EBC410} {AAFBC1E9-6192-46AE-95BC-642DCB20D361} = {AAFBC1E9-6192-46AE-95BC-642DCB20D361} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "expat", "expat.vcproj", "{AAFBC1E9-6192-46AE-95BC-642DCB20D361}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {659E3B17-B1BF-4D3B-94E6-438F85EBC410}.Debug|Win32.ActiveCfg = Debug|Win32 {659E3B17-B1BF-4D3B-94E6-438F85EBC410}.Debug|Win32.Build.0 = Debug|Win32 {659E3B17-B1BF-4D3B-94E6-438F85EBC410}.Release|Win32.ActiveCfg = Release|Win32 {659E3B17-B1BF-4D3B-94E6-438F85EBC410}.Release|Win32.Build.0 = Release|Win32 {FB499990-F569-426A-9215-5B013D94B70C}.Debug|Win32.ActiveCfg = Debug|Win32 {FB499990-F569-426A-9215-5B013D94B70C}.Debug|Win32.Build.0 = Debug|Win32 {FB499990-F569-426A-9215-5B013D94B70C}.Release|Win32.ActiveCfg = Release|Win32 {FB499990-F569-426A-9215-5B013D94B70C}.Release|Win32.Build.0 = Release|Win32 {7BD355D0-941D-4630-B82F-1FB43A971440}.Debug|Win32.ActiveCfg = Debug|Win32 {7BD355D0-941D-4630-B82F-1FB43A971440}.Debug|Win32.Build.0 = Debug|Win32 {7BD355D0-941D-4630-B82F-1FB43A971440}.Release|Win32.ActiveCfg = Release|Win32 {7BD355D0-941D-4630-B82F-1FB43A971440}.Release|Win32.Build.0 = Release|Win32 {DEE25458-271F-4F9A-8979-C460C64B49C8}.Debug|Win32.ActiveCfg = Debug|Win32 {DEE25458-271F-4F9A-8979-C460C64B49C8}.Debug|Win32.Build.0 = Debug|Win32 {DEE25458-271F-4F9A-8979-C460C64B49C8}.Release|Win32.ActiveCfg = Release|Win32 {DEE25458-271F-4F9A-8979-C460C64B49C8}.Release|Win32.Build.0 = Release|Win32 {5F6591E0-3FAD-45AE-80CF-A47C1F8BA2CC}.Debug|Win32.ActiveCfg = Debug|Win32 {5F6591E0-3FAD-45AE-80CF-A47C1F8BA2CC}.Debug|Win32.Build.0 = Debug|Win32 {5F6591E0-3FAD-45AE-80CF-A47C1F8BA2CC}.Release|Win32.ActiveCfg = Release|Win32 {5F6591E0-3FAD-45AE-80CF-A47C1F8BA2CC}.Release|Win32.Build.0 = Release|Win32 {AAFBC1E9-6192-46AE-95BC-642DCB20D361}.Debug|Win32.ActiveCfg = Debug|Win32 {AAFBC1E9-6192-46AE-95BC-642DCB20D361}.Debug|Win32.Build.0 = Debug|Win32 {AAFBC1E9-6192-46AE-95BC-642DCB20D361}.Release|Win32.ActiveCfg = Release|Win32 {AAFBC1E9-6192-46AE-95BC-642DCB20D361}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal libstrophe-0.8.8/vs2008/libstrophe.vcproj000066400000000000000000000121521256471717200202610ustar00rootroot00000000000000 libstrophe-0.8.8/vs2008/roster.vcproj000066400000000000000000000077261256471717200174370ustar00rootroot00000000000000