[
  {
    "path": ".git-blame-ignore-revs",
    "content": "# Unify coding style with clang-format\n562a06425b96450481cdbc88e8872a2bf5a7d8aa\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/01-bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a bug report\ntitle: ''\nlabels: bug\nassignees: ''\n\n---\n\n<!--\n\nProvide a general summary of the issue in the Title above\n\nThis is a very generic template, remove items that do not apply. For completed items, change [ ] to [x].\n\n-->\n\n### Prerequisites\n\n* [ ] Checked that your issue isn't already filed: https://github.com/strophe/libstrophe/issues?q=\n\n### Additional Information\n\n<!--- Any additional information, configuration or data that might be necessary to reproduce the issue. -->\n\n## Expected Behavior\n\n<!--- If you're describing a bug, tell us what should happen -->\n<!--- If you're suggesting a change/improvement, tell us how it should work -->\n\n## Current Behavior\n\n<!--- If describing a bug, tell us what happens instead of the expected behavior or even better, provide a functional code example reproducing your issue. -->\n<!--- If suggesting a change/improvement, explain the difference from current behavior -->\n\n## Possible Solution\n<!--- Not obligatory, but suggest a fix/reason for the bug, -->\n<!--- or ideas how to implement the addition or change -->\n\n## Steps to Reproduce (for bugs)\n\n<!--- Please either describe your issue in detail or even better, provide a functional code example reproducing your issue. -->\n1.\n2.\n3.\n4.\n\n## Context\n\n<!--- How has this issue affected you? What are you trying to accomplish? -->\n\n## Environment\n\n<!---\nPlease provide the version of the library you're using.\nYou can find the version either in the first line of the `configure.ac` file or if you're using the Git repository, please run `git describe --always --tags --dirty`.\nAlso, please include the compiler, the compiler version, the architecture, the OS and what version of the OS you're experiencing the issue.\n -->\n"
  },
  {
    "path": ".github/workflows/main.yml",
    "content": "name: CI\n\non:\n  push:\n    branches:\n      - master\n      - next\n  pull_request:\n    branches: [master]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}\n  cancel-in-progress: true\n\njobs:\n  linux-tests:\n    runs-on: ubuntu-24.04\n    strategy:\n      matrix:\n        valgrind:\n           - { configure: ''                  , cflags: '',    make: 'check' }\n           - { configure: '--enable-valgrind' , cflags: '-O2', make: 'check-valgrind'  }\n        options:\n           - { configure: ''                    }\n           - { configure: '--without-libxml2'   }\n           - { configure: '--with-libxml2'      }\n           - { configure: '--with-gnutls'       }\n           - { configure: '--disable-tls'       }\n           - { configure: '--enable-cares'      }\n           - { configure: '--disable-getrandom' }\n           - { configure: '--disable-static'    }\n    name: Regular Tests\n    steps:\n      - uses: actions/checkout@v2\n      - name: install dependencies\n        run: |\n          sudo apt update\n          sudo apt install -y libtool pkg-config libexpat1-dev libxml2-dev libssl-dev libgnutls28-dev libc-ares-dev valgrind\n      - name: Build the library\n        run: |\n          ./bootstrap.sh\n          ./configure ${{ matrix.options.configure }} ${{ matrix.valgrind.configure }} CFLAGS=\"-Werror -g3 ${{ matrix.valgrind.cflags }}\"\n          make -j$(nproc)\n      - name: Run tests\n        run: |\n          make -j$(nproc) ${{ matrix.valgrind.make }}\n      - name: Error logs\n        if: ${{ failure() }}\n        run: |\n          cat test-suite*.log || true\n\n  xssl-tests:\n    runs-on: ubuntu-24.04\n    strategy:\n      matrix:\n        xssl_versions:\n           - { version: \"master\",          continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_8\",     continue: true,  libressl: true }\n           - { version: \"v4.2.1\",          continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_7\",     continue: true,  libressl: true }\n           - { version: \"v4.1.2\",          continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_6\",     continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_5\",     continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_4\",     continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_3\",     continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_2\",     continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_1\",     continue: true,  libressl: true }\n           # https://github.com/libressl-portable/portable/issues/760\n           # - { version: \"v3.5.2\",        continue: true,  libressl: true }\n           - { version: \"OPENBSD_7_0\",       continue: true,  libressl: true }\n           # OPENBSD_7_0 is basically the \"fixed v3.4.3\"\n           # - { version: \"v3.4.3\",          continue: true,  libressl: true }\n           - { version: \"v3.4.2\",          continue: true,  libressl: true }\n           - { version: \"OPENBSD_6_9\",     continue: true,  libressl: true }\n           - { version: \"v3.1.5\",          continue: true,  libressl: true }\n           - { version: \"v2.1.10\",         continue: true,  libressl: true }\n           - { version: \"openssl-3.0\",     continue: true,  libressl: false }\n           - { version: \"openssl-3.0.18\",  continue: false, libressl: false }\n           - { version: \"openssl-3.2\",     continue: true,  libressl: false }\n           - { version: \"openssl-3.2.6\",   continue: false, libressl: false }\n           - { version: \"openssl-3.3\",     continue: true,  libressl: false }\n           - { version: \"openssl-3.3.5\",   continue: false, libressl: false }\n           - { version: \"openssl-3.4\",     continue: true,  libressl: false }\n           - { version: \"openssl-3.4.3\",   continue: false, libressl: false }\n           - { version: \"openssl-3.5\",     continue: true,  libressl: false }\n           - { version: \"openssl-3.5.3\",   continue: false, libressl: false }\n           - { version: \"openssl-3.6\",     continue: true,  libressl: false }\n           - { version: \"openssl-3.6.0\",   continue: false, libressl: false }\n    name: xSSL tests\n    continue-on-error: ${{ matrix.xssl_versions.continue }}\n    steps:\n      - uses: actions/checkout@v2\n      - name: install dependencies\n        run: |\n          sudo apt update\n          sudo apt install -y libtool pkg-config libexpat1-dev valgrind\n      - name: build&install the TLS stack\n        env:\n           XSSL_COMMITISH: ${{ matrix.xssl_versions.version }}\n           LIBRESSL: ${{ matrix.xssl_versions.libressl }}\n        run: |\n          ./travis/before_script.sh\n      - name: Build the library\n        run: |\n          ./bootstrap.sh\n          PKG_CONFIG_PATH=\"${HOME}/xssl/lib/pkgconfig\" ./configure CFLAGS=\"-Werror -g3\" --prefix=\"${HOME}/xssl\"\n          make -j$(nproc)\n      - name: Run tests\n        run: |\n          LD_LIBRARY_PATH=\"${HOME}/xssl/lib\" make -j$(nproc) check\n      - name: Build the library with Valgrind enabled\n        run: |\n          ./bootstrap.sh\n          PKG_CONFIG_PATH=\"${HOME}/xssl/lib/pkgconfig\" ./configure --enable-valgrind CFLAGS=\"-Werror -g3\" --prefix=\"${HOME}/xssl\"\n          make -j$(nproc)\n      - name: Run tests with Valgrind enabled\n        run: |\n          LD_LIBRARY_PATH=\"${HOME}/xssl/lib\" make -j$(nproc) check-valgrind\n      - name: Error logs\n        if: ${{ failure() }}\n        run: |\n          cat test-suite*.log || true\n\n  release-test:\n    runs-on: ubuntu-22.04\n    name: Check if release would work\n    steps:\n      - uses: actions/checkout@v2\n      - name: install dependencies & bootstrap\n        run: |\n          sudo apt update\n          sudo apt install -y libtool pkg-config libexpat1-dev dash\n          ./bootstrap.sh\n      - name: Check if configure works with non-bash shells\n        # https://github.com/actions/runner/issues/241 requires us to use this following line...\n        shell: 'script --return --quiet --command \"bash {0}\"'\n        run: |\n          [ \"`CONFIG_SHELL=/bin/dash ./configure 2>&1 1>/dev/null | tee /dev/tty | wc -l`\" = \"0\" ]\n      - name: Re-run configure with the default shell\n        run: |\n          ./configure\n      - name: Try release & tests\n        run: |\n          make test-release\n      - name: Show logs from release build\n        if: ${{ !failure() }}\n        run: |\n          cat testbuild.log\n      - name: Error logs\n        if: ${{ failure() }}\n        run: |\n          cat testbuild.log || true\n          cat testerr.log || true\n\n  code-style:\n    runs-on: ubuntu-24.04\n    name: Check coding style\n    continue-on-error: true\n    steps:\n      - uses: actions/checkout@v2\n      - name: install dependencies\n        run: |\n          sudo apt update\n          sudo apt install -y libtool pkg-config libexpat1-dev libxml2-dev libssl-dev libgnutls28-dev libc-ares-dev dos2unix\n      - name: Configure\n        run: |\n          ./bootstrap.sh\n          ./configure\n      - name: Check style\n        run: |\n          make format\n          git diff --exit-code\n"
  },
  {
    "path": ".gitignore",
    "content": "*.swp\n*.orig\nMakefile\ntest-driver\n.libs\nMakefile.in\nconfigure\nlibtool\nltmain.sh\nconfig.guess\nconfig.sub\ninstall-sh\nmissing\ncompile\naclocal.m4\nconfig.log\nconfig.status\ndepcomp\nautom4te.cache\n.dirstamp\n.deps\n.sconsign*\nsrc/*.gcda\nsrc/*.gcno\nsrc/*.o\nsrc/*.lo\nexamples/*.o\n*.a\n*.la\n*.pc\n*.tar.gz\n*.tar.bz2\n*.tar.xz\n*.zip\ndocs/html\nTAGS\ntags\nexamples/active\nexamples/basic\nexamples/bot\nexamples/complex\nexamples/component\nexamples/perf\nexamples/register\nexamples/roster\nexamples/uuid\nexamples/vcard\ntestbuild*.log\ntesterr*.log\ntest-release/\ntest_stamp\ntest-suite*.log\ntests/*.o\ntests/*.log\ntests/*.trs\ntests/check_parser\ntests/test_base64\ntests/test_ctx\ntests/test_fuzz_parser\ntests/test_fuzz_resolver\ntests/test_hash\ntests/test_jid\ntests/test_md5\ntests/test_rand\ntests/test_resolver\ntests/test_sasl\ntests/test_scram\ntests/test_send_queue\ntests/test_serialize_sm\ntests/test_sha1\ntests/test_sha256\ntests/test_sha512\ntests/test_snprintf\ntests/test_sock\ntests/test_stanza\ntests/test_string\ntests/test_xmppaddr\nm4/lt*\nm4/libtool*\nlibstrophe.project\nlibs/\nobj/\nexpat/\n.settings/\n.project\n.cproject\ncoverage/\ncoverage.info\nconfigure~\nfuzz-*.log\nbuild*/\n"
  },
  {
    "path": "AUTHORS",
    "content": "Current maintainer:\nSteffen Jaeckel <gh@jaeckel.eu>\n\nPrevious maintainers:\nDmitry Podgorny <pasis.ua@gmail.com>\nJack Moffit <jack@metajack.im>\n\nOther contributors can be extracted from the Git log.\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\nCopyright (c) 2005-2009 Collecta, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n"
  },
  {
    "path": "ChangeLog",
    "content": "0.14.0\n\t- Add SM-state serialization mechanism (#239)\n\t- Add support for `SCRAM-SHA-512-PLUS` (da122981)\n\t- Add support for `SSLKEYLOGFILE` with OpenSSL (d82df127)\n\t- Fix some issues related to Stream Management (03d43132, 4359536a)\n\t- Fix a potential segfault (9fef4b7d)\n\t- New API:\n\t\t- xmpp_conn_set_sm_callback()\n\t\t- xmpp_conn_restore_sm_state()\n\n0.13.1\n\t- Fix SCRAM-*-PLUS SASL mechanisms with OpenSSL and TLS < v1.3 (40f2452)\n\t- Only signal \"stream negotiation success\" once (1cf09b1)\n\t- Fix `sock_connect()` not looping over all DNS records returned if no `sockopt_cb` is set (5edc480)\n\t- Replace usage of EBADFD, it's not in POSIX (#235)\n\n0.13.0\n\t- Fix connected/connecting signaling to user (#227)\n\t- Fix wording of licensing terms (#225)\n\t- Prepare for future changes in OpenSSL (#226)\n\t- Improve Stream Management (#227) (#230)\n\t- Add SCRAM-PLUS Variants (#228)\n\t- Introduce XEP-0138 stream compression (#231)\n\t- Deprecated the following API (#227):\n\t\t- xmpp_conn_disable_tls() - replaced by a flag set by xmpp_conn_set_flags()\n\n0.12.3\n\t- Improve TCP-connection establishment (#221)\n\t- Handle case where the server doesn't provide the `bind` feature (#224)\n\t- Fix configure script for non-bash shells (#218)\n\t- Parse JID's according to RFC7622 (#219)\n\t- Fix potential memory leak in internal DNS resolver (#219)\n\t- Fix potential memory leaks in `xmpp_conn_set_cafile()` and `xmpp_conn_set_capath()` (#219)\n\t- Internal improvements (#219)\n\n0.12.2\n\t- Fix reconnect issues when Stream Management is enabled (#211)\n\t- Fix resolver ... this time for real hopefully (fixup of #200) (#214)\n\t- Fix clearing of password cache on resumed connection (#214)\n\t- Improve detection&implementation of `va_copy` (#213)\n\t- Fix Valgrind CI builds against LibreSSL (#212)\n\t- Fix perf example on platforms where an `rdtsc()` equivalent isn't implemented (#212)\n\n0.12.1\n\t- Fix compilation in buildroot (#207)\n\t- Fixes regarding OpenSSL (#208)\n\t- Fix some build steps when builddir != srcdir (#208)\n\t- Allow the user to disable build of examples (#209)\n\t- CI builds against OpenSSL 3 (#206)\n\t- Change the call signature of the following API (#208):\n\t\t- xmpp_conn_set_client_cert() - the PKCS#12 file has now to be passed via the `cert`\n\t\t\t\tparameter. Originally it was via `key`. Currently both styles are supported,\n\t\t\t\tbut in a future release only passing via `cert` will be accepted.\n\n0.12.0\n\t- Fix potential infinite loop in resolver (#200)\n\t- Prevent potential memory leak in `xmpp_stanza_new_from_string()` (#205)\n\t- Do proper SO versioning\n\t- Add code coverage support (#188)\n\t- Add support for password-protected TLS key & PKCS#12/PFX files (#195, #205)\n\t- Stream-Management support - XEP-0198 (#184)\n\t- New API:\n\t\t- xmpp_conn_send_queue_len()\n\t\t- xmpp_conn_send_queue_drop_element()\n\t\t- xmpp_conn_get_sm_state()\n\t\t- xmpp_conn_set_sm_state()\n\t\t- xmpp_free_sm_state()\n\t\t- xmpp_conn_get_keyfile()\n\t\t- xmpp_conn_set_password_callback()\n\t\t- xmpp_conn_set_password_retries()\n\t\t- xmpp_stanza_get_child_by_path()\n\t\t- xmpp_conn_set_sockopt_callback()\n\t\t- xmpp_sockopt_cb_keepalive()\n\t- The following APIs were public in the shared library, but not in `strophe.h`.\n\t  Now they are officially public API:\n\t\t- xmpp_rand_new()\n\t\t- xmpp_rand_free()\n\t\t- xmpp_rand()\n\t\t- xmpp_rand_bytes()\n\t\t- xmpp_rand_nonce()\n\t\t- xmpp_rand_bytes()\n\t- The following APIs were public in the shared library, but not in `strophe.h`.\n\t  In a future version of the library they will be private without replacement:\n\t\t- xmpp_alloc()\n\t\t- xmpp_realloc()\n\t\t- xmpp_strdup()\n\t\t- xmpp_strndup()\n\t\t- xmpp_strtok_r()\n\t\t- xmpp_snprintf()\n\t\t- xmpp_vsnprintf()\n\t\t- xmpp_log()\n\t\t- xmpp_error()\n\t\t- xmpp_warn()\n\t\t- xmpp_info()\n\t\t- xmpp_debug()\n\t\t- xmpp_debug_verbose()\n\t- Deprecated the following API:\n\t\t- xmpp_conn_set_keepalive() - replaced by xmpp_conn_set_sockopt_callback()\n\n0.11.0\n\t- SASL EXTERNAL support (XEP-0178)\n\t- Client certificate can be provided for TLS negotiation. If the\n\t  certificate contains a single xmppAddr and JID is not provided with\n\t  xmpp_conn_set_jid(), the xmppAddr is chosen as JID\n\t- <stream> element contains \"from\" attribute over TLS connections now\n\t- GnuTLS can be selected optionally with configure script\n\t- Support for manual certificate verification\n\t- New API:\n\t\t- xmpp_conn_set_client_cert()\n\t\t- xmpp_conn_cert_xmppaddr_num()\n\t\t- xmpp_conn_cert_xmppaddr()\n\t\t- xmpp_conn_set_cafile()\n\t\t- xmpp_conn_set_capath()\n\t\t- xmpp_conn_set_certfail_handler()\n\t\t- xmpp_conn_get_peer_cert()\n\t\t- xmpp_tlscert_get_ctx()\n\t\t- xmpp_tlscert_get_conn()\n\t\t- xmpp_tlscert_get_pem()\n\t\t- xmpp_tlscert_get_dnsname()\n\t\t- xmpp_tlscert_get_string()\n\t\t- xmpp_tlscert_get_description()\n\t\t- xmpp_tlscert_free()\n\n0.10.1\n\t- Fixed compilation error when LibreSSL is used\n\t- Fixed crash when NULL is provided as password\n\n0.10.0\n\t- Coding style has been unified\n\t- SCRAM-SHA-256 and SCRAM-SHA-512 support\n\t- c-ares support\n\t- LibreSSL support\n\t- Introduced global timed handlers that fire periodically regardless of\n\t  connections status, such a handler can be used to implement deferred\n\t  re-connection\n\t- examples/register implements XEP-0077\n\t- Fixed issue with IPv6 on Windows (#153)\n\t- Improved portability across systems such as Haiku, Windows\n\t- New API:\n\t\t- xmpp_stanza_get_child_by_name_and_ns()\n\t\t- xmpp_conn_is_connecting()\n\t\t- xmpp_conn_is_connected()\n\t\t- xmpp_conn_is_disconnected()\n\t\t- xmpp_stanza_new_from_string()\n\t\t- xmpp_stanza_add_child_ex()\n\t\t- xmpp_stanza_get_context()\n\t\t- xmpp_stanza_reply_error()\n\t\t- xmpp_global_timed_handler_add()\n\t\t- xmpp_global_timed_handler_delete()\n\n0.9.3\n\t- PLAIN mechanism is used only when no other mechanisms are supported\n\t- Legacy authentication is disabled by default, can be enabled with\n\t  connection flag XMPP_CONN_FLAG_LEGACY_AUTH\n\t- Session is not established if it is optional\n\t- Fixed a bug causing a reused connection not to cleanup properly\n\t- Improved debug logging in OpenSSL module\n\t- Few memory leaks fixed\n\n0.9.2\n\t- OpenSSL tls module verifies certificate by default. Set flag\n\t  XMPP_CONN_FLAG_TRUST_TLS to ignore result of the verification\n\t- Certificate hostname verification is forced for openssl-1.0.2 and\n\t  newer\n\t- OpenSSL tls module disables insecure SSLv2 SSLv3 and TLSv1\n\t- Support of handlers with the same callback function, but different\n\t  userdata\n\t- System handlers are deleted on xmpp_conn_t reconnection. Old system\n\t  handlers could cause problems\n\t- Default timeout for xmpp_run() is increased from 1 millisecond to 1\n\t  second in order to reduce CPU consumption\n\t- Reduced memory usage in expat module\n\t- New functions:\n\t\t- xmpp_error_new()\n\t\t- xmpp_send_error()\n\t\t- xmpp_ctx_set_timeout()\n\t\t- xmpp_sha1_digest()\n\n0.9.1\n\t- Fixed bug #95 (DNS lookup failing on Cygwin)\n\t- Removed dependency on the check package\n\n0.9.0\n\t- IPv6 support\n\t- Legacy SSL support\n\t- Initial Android support\n\t- Resolver returns all SRV records instead of one. Lookup is performed\n\t  according to RFC2052\n\t- xmpp_connect_raw() provides access to a xmpp_conn object just after\n\t  establishing TCP connection. This allows to implement in-band\n\t  registration, authentication mechanisms or serverless messaging\n\t- xmpp_conn_t object is reusable now and can be reconnected with saving\n\t  all handlers, flags, jid and password\n\t- New API:\n\t\t- xmpp_uuid_gen()\n\t\t- xmpp_connect_raw()\n\t\t- xmpp_conn_open_stream_default()\n\t\t- xmpp_conn_open_stream()\n\t\t- xmpp_conn_tls_start()\n\t\t- xmpp_conn_get_flags()\n\t\t- xmpp_conn_set_flags()\n\t\t- xmpp_conn_set_keepalive()\n\t\t- xmpp_conn_is_secured()\n\t\t- xmpp_stanza_del_attribute()\n\t\t- xmpp_stanza_get_to()\n\t\t- xmpp_stanza_get_from()\n\t\t- xmpp_stanza_set_to()\n\t\t- xmpp_stanza_set_from()\n\t\t- xmpp_stanza_reply()\n\t\t- xmpp_message_new()\n\t\t- xmpp_message_get_body()\n\t\t- xmpp_message_set_body()\n\t\t- xmpp_iq_new()\n\t\t- xmpp_presence_new()\n\t- Exposed private API:\n\t\t- xmpp_jid_new()\n\t\t- xmpp_jid_bare()\n\t\t- xmpp_jid_node()\n\t\t- xmpp_jid_domain()\n\t\t- xmpp_jid_resource()\n\t\t- xmpp_stanza_get_attribute_count()\n\t\t- xmpp_stanza_get_attributes()\n\n0.8.8\n\t- XML namespace support\n\t- XEP-0114 support\n\n0.8.7\n\t- SCRAM-SHA-1 authentication mechanism\n\t- pkg-config support\n\n0.8.5\n\t- libtoolize to generate .so\n"
  },
  {
    "path": "Doxyfile",
    "content": "# Doxyfile 1.16.1\n\n# This file describes the settings to be used by the documentation system\n# Doxygen (www.doxygen.org) for a project.\n#\n# All text after a double hash (##) is considered a comment and is placed in\n# front of the TAG it is preceding.\n#\n# All text after a single hash (#) is considered a comment and will be ignored.\n# The format is:\n# TAG = value [value, ...]\n# For lists, items can also be appended using:\n# TAG += value [value, ...]\n# Values that contain spaces should be placed between quotes (\\\" \\\").\n#\n# Note:\n#\n# Use Doxygen to compare the used configuration file with the template\n# configuration file:\n# doxygen -x [configFile]\n# Use Doxygen to compare the used configuration file with the template\n# configuration file without replacing the environment variables or CMake type\n# replacement variables:\n# doxygen -x_noenv [configFile]\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\n\n# This tag specifies the encoding used for all characters in the configuration\n# file that follow. The default is UTF-8 which is also the encoding used for all\n# text before the first occurrence of this tag. Doxygen uses libiconv (or the\n# iconv built into libc) for the transcoding. See\n# https://www.gnu.org/software/libiconv/ for the list of possible encodings.\n# The default value is: UTF-8.\n\nDOXYFILE_ENCODING      = UTF-8\n\n# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by\n# double-quotes, unless you are using Doxywizard) that should identify the\n# project for which the documentation is generated. This name is used in the\n# title of most generated pages and in a few other places.\n# The default value is: My Project.\n\nPROJECT_NAME           = Strophe\n\n# The PROJECT_NUMBER tag can be used to enter a project or revision number. This\n# could be handy for archiving the generated documentation or if some version\n# control system is used.\n\nPROJECT_NUMBER         = 0.14\n\n# Using the PROJECT_BRIEF tag one can provide an optional one line description\n# for a project that appears at the top of each page and should give viewers a\n# quick idea about the purpose of the project. Keep the description short.\n\nPROJECT_BRIEF          = \"XMPP client library\"\n\n# With the PROJECT_LOGO tag one can specify a logo or an icon that is included\n# in the documentation. The maximum height of the logo should not exceed 55\n# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy\n# the logo to the output directory.\n\nPROJECT_LOGO           =\n\n# With the PROJECT_ICON tag one can specify an icon that is included in the tabs\n# when the HTML document is shown. Doxygen will copy the logo to the output\n# directory.\n\nPROJECT_ICON           =\n\n# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path\n# into which the generated documentation will be written. If a relative path is\n# entered, it will be relative to the location where Doxygen was started. If\n# left blank the current directory will be used.\n\nOUTPUT_DIRECTORY       = ./docs/\n\n# If the CREATE_SUBDIRS tag is set to YES then Doxygen will create up to 4096\n# sub-directories (in 2 levels) under the output directory of each output format\n# and will distribute the generated files over these directories. Enabling this\n# option can be useful when feeding Doxygen a huge amount of source files, where\n# putting all generated files in the same directory would otherwise cause\n# performance problems for the file system. Adapt CREATE_SUBDIRS_LEVEL to\n# control the number of sub-directories.\n# The default value is: NO.\n\nCREATE_SUBDIRS         = NO\n\n# Controls the number of sub-directories that will be created when\n# CREATE_SUBDIRS tag is set to YES. Level 0 represents 16 directories, and every\n# level increment doubles the number of directories, resulting in 4096\n# directories at level 8 which is the default and also the maximum value. The\n# sub-directories are organized in 2 levels, the first level always has a fixed\n# number of 16 directories.\n# Minimum value: 0, maximum value: 8, default value: 8.\n# This tag requires that the tag CREATE_SUBDIRS is set to YES.\n\nCREATE_SUBDIRS_LEVEL   = 8\n\n# If the ALLOW_UNICODE_NAMES tag is set to YES, Doxygen will allow non-ASCII\n# characters to appear in the names of generated files. If set to NO, non-ASCII\n# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode\n# U+3044.\n# The default value is: NO.\n\nALLOW_UNICODE_NAMES    = NO\n\n# The OUTPUT_LANGUAGE tag is used to specify the language in which all\n# documentation generated by Doxygen is written. Doxygen will use this\n# information to generate all constant output in the proper language.\n# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Bulgarian,\n# Catalan, Chinese, Chinese-Traditional, Croatian, Czech, Danish, Dutch, English\n# (United States), Esperanto, Farsi (Persian), Finnish, French, German, Greek,\n# Hindi, Hungarian, Indonesian, Italian, Japanese, Japanese-en (Japanese with\n# English messages), Korean, Korean-en (Korean with English messages), Latvian,\n# Lithuanian, Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese,\n# Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish,\n# Swedish, Turkish, Ukrainian and Vietnamese.\n# The default value is: English.\n\nOUTPUT_LANGUAGE        = English\n\n# If the BRIEF_MEMBER_DESC tag is set to YES, Doxygen will include brief member\n# descriptions after the members that are listed in the file and class\n# documentation (similar to Javadoc). Set to NO to disable this.\n# The default value is: YES.\n\nBRIEF_MEMBER_DESC      = YES\n\n# If the REPEAT_BRIEF tag is set to YES, Doxygen will prepend the brief\n# description of a member or function before the detailed description\n#\n# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the\n# brief descriptions will be completely suppressed.\n# The default value is: YES.\n\nREPEAT_BRIEF           = YES\n\n# This tag implements a quasi-intelligent brief description abbreviator that is\n# used to form the text in various listings. Each string in this list, if found\n# as the leading text of the brief description, will be stripped from the text\n# and the result, after processing the whole list, is used as the annotated\n# text. Otherwise, the brief description is used as-is. If left blank, the\n# following values are used ($name is automatically replaced with the name of\n# the entity):The $name class, The $name widget, The $name file, is, provides,\n# specifies, contains, represents, a, an and the.\n\nABBREVIATE_BRIEF       = \"The $name class\" \\\n                         \"The $name widget\" \\\n                         \"The $name file\" \\\n                         is \\\n                         provides \\\n                         specifies \\\n                         contains \\\n                         represents \\\n                         a \\\n                         an \\\n                         the\n\n# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then\n# Doxygen will generate a detailed section even if there is only a brief\n# description.\n# The default value is: NO.\n\nALWAYS_DETAILED_SEC    = NO\n\n# If the INLINE_INHERITED_MEMB tag is set to YES, Doxygen will show all\n# inherited members of a class in the documentation of that class as if those\n# members were ordinary class members. Constructors, destructors and assignment\n# operators of the base classes will not be shown.\n# The default value is: NO.\n\nINLINE_INHERITED_MEMB  = NO\n\n# If the FULL_PATH_NAMES tag is set to YES, Doxygen will prepend the full path\n# before files name in the file list and in the header files. If set to NO the\n# shortest path that makes the file name unique will be used\n# The default value is: YES.\n\nFULL_PATH_NAMES        = NO\n\n# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.\n# Stripping is only done if one of the specified strings matches the left-hand\n# part of the path. The tag can be used to show relative paths in the file list.\n# If left blank the directory from which Doxygen is run is used as the path to\n# strip.\n#\n# Note that you can specify absolute paths here, but also relative paths, which\n# will be relative from the directory where Doxygen is started.\n# This tag requires that the tag FULL_PATH_NAMES is set to YES.\n\nSTRIP_FROM_PATH        =\n\n# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the\n# path mentioned in the documentation of a class, which tells the reader which\n# header file to include in order to use a class. If left blank only the name of\n# the header file containing the class definition is used. Otherwise one should\n# specify the list of include paths that are normally passed to the compiler\n# using the -I flag.\n\nSTRIP_FROM_INC_PATH    =\n\n# If the SHORT_NAMES tag is set to YES, Doxygen will generate much shorter (but\n# less readable) file names. This can be useful if your file system doesn't\n# support long names like on DOS, Mac, or CD-ROM.\n# The default value is: NO.\n\nSHORT_NAMES            = NO\n\n# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen will interpret the\n# first line (until the first dot, question mark or exclamation mark) of a\n# Javadoc-style comment as the brief description. If set to NO, the Javadoc-\n# style will behave just like regular Qt-style comments (thus requiring an\n# explicit @brief command for a brief description.)\n# The default value is: NO.\n\nJAVADOC_AUTOBRIEF      = YES\n\n# If the JAVADOC_BANNER tag is set to YES then Doxygen will interpret a line\n# such as\n# /***************\n# as being the beginning of a Javadoc-style comment \"banner\". If set to NO, the\n# Javadoc-style will behave just like regular comments and it will not be\n# interpreted by Doxygen.\n# The default value is: NO.\n\nJAVADOC_BANNER         = NO\n\n# If the QT_AUTOBRIEF tag is set to YES then Doxygen will interpret the first\n# line (until the first dot, question mark or exclamation mark) of a Qt-style\n# comment as the brief description. If set to NO, the Qt-style will behave just\n# like regular Qt-style comments (thus requiring an explicit \\brief command for\n# a brief description.)\n# The default value is: NO.\n\nQT_AUTOBRIEF           = NO\n\n# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen treat a\n# multi-line C++ special comment block (i.e. a block of //! or /// comments) as\n# a brief description. This used to be the default behavior. The new default is\n# to treat a multi-line C++ comment block as a detailed description. Set this\n# tag to YES if you prefer the old behavior instead.\n#\n# Note that setting this tag to YES also means that rational rose comments are\n# not recognized any more.\n# The default value is: NO.\n\nMULTILINE_CPP_IS_BRIEF = NO\n\n# By default Python docstrings are displayed as preformatted text and Doxygen's\n# special commands cannot be used. By setting PYTHON_DOCSTRING to NO the\n# Doxygen's special commands can be used and the contents of the docstring\n# documentation blocks is shown as Doxygen documentation.\n# The default value is: YES.\n\nPYTHON_DOCSTRING       = YES\n\n# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the\n# documentation from any documented member that it re-implements.\n# The default value is: YES.\n\nINHERIT_DOCS           = YES\n\n# If the SEPARATE_MEMBER_PAGES tag is set to YES then Doxygen will produce a new\n# page for each member. If set to NO, the documentation of a member will be part\n# of the file/class/namespace that contains it.\n# The default value is: NO.\n\nSEPARATE_MEMBER_PAGES  = NO\n\n# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen\n# uses this value to replace tabs by spaces in code fragments.\n# Minimum value: 1, maximum value: 16, default value: 4.\n\nTAB_SIZE               = 8\n\n# This tag can be used to specify a number of aliases that act as commands in\n# the documentation. An alias has the form:\n# name=value\n# For example adding\n# \"sideeffect=@par Side Effects:^^\"\n# will allow you to put the command \\sideeffect (or @sideeffect) in the\n# documentation, which will result in a user-defined paragraph with heading\n# \"Side Effects:\". Note that you cannot put \\n's in the value part of an alias\n# to insert newlines (in the resulting output). You can put ^^ in the value part\n# of an alias to insert a newline as if a physical newline was in the original\n# file. When you need a literal { or } or , in the value part of an alias you\n# have to escape them by means of a backslash (\\), this can lead to conflicts\n# with the commands \\{ and \\} for these it is advised to use the version @{ and\n# @} or use a double escape (\\\\{ and \\\\})\n\nALIASES                =\n\n# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources\n# only. Doxygen will then generate output that is more tailored for C. For\n# instance, some of the names that are used will be different. The list of all\n# members will be omitted, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_FOR_C  = YES\n\n# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or\n# Python sources only. Doxygen will then generate output that is more tailored\n# for that language. For instance, namespaces will be presented as packages,\n# qualified scopes will look different, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_JAVA   = NO\n\n# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran\n# sources. Doxygen will then generate output that is tailored for Fortran.\n# The default value is: NO.\n\nOPTIMIZE_FOR_FORTRAN   = NO\n\n# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL\n# sources. Doxygen will then generate output that is tailored for VHDL.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_VHDL   = NO\n\n# Set the OPTIMIZE_OUTPUT_SLICE tag to YES if your project consists of Slice\n# sources only. Doxygen will then generate output that is more tailored for that\n# language. For instance, namespaces will be presented as modules, types will be\n# separated into more groups, etc.\n# The default value is: NO.\n\nOPTIMIZE_OUTPUT_SLICE  = NO\n\n# Doxygen selects the parser to use depending on the extension of the files it\n# parses. With this tag you can assign which parser to use for a given\n# extension. Doxygen has a built-in mapping, but you can override or extend it\n# using this tag. The format is ext=language, where ext is a file extension, and\n# language is one of the parsers supported by Doxygen: IDL, Java, JavaScript,\n# Csharp (C#), C, C++, Lex, D, PHP, md (Markdown), Objective-C, Python, Slice,\n# VHDL, Fortran (fixed format Fortran: FortranFixed, free formatted Fortran:\n# FortranFree, unknown formatted Fortran: Fortran. In the later case the parser\n# tries to guess whether the code is fixed or free formatted code, this is the\n# default for Fortran type files). For instance to make Doxygen treat .inc files\n# as Fortran files (default is PHP), and .f files as C (default is Fortran),\n# use: inc=Fortran f=C.\n#\n# Note: For files without extension you can use no_extension as a placeholder.\n#\n# Note that for custom extensions you also need to set FILE_PATTERNS otherwise\n# the files are not read by Doxygen. When specifying no_extension you should add\n# * to the FILE_PATTERNS.\n#\n# Note see also the list of default file extension mappings.\n\nEXTENSION_MAPPING      =\n\n# If the MARKDOWN_SUPPORT tag is enabled then Doxygen pre-processes all comments\n# according to the Markdown format, which allows for more readable\n# documentation. See https://daringfireball.net/projects/markdown/ for details.\n# The output of markdown processing is further processed by Doxygen, so you can\n# mix Doxygen, HTML, and XML commands with Markdown formatting. Disable only in\n# case of backward compatibilities issues.\n# The default value is: YES.\n\nMARKDOWN_SUPPORT       = YES\n\n# If the MARKDOWN_STRICT tag is enabled then Doxygen treats text in comments as\n# Markdown formatted also in cases where Doxygen's native markup format\n# conflicts with that of Markdown. This is only relevant in cases where\n# backticks are used. Doxygen's native markup style allows a single quote to end\n# a text fragment started with a backtick and then treat it as a piece of quoted\n# text, whereas in Markdown such text fragment is treated as verbatim and only\n# ends when a second matching backtick is found. Also, Doxygen's native markup\n# format requires double quotes to be escaped when they appear in a backtick\n# section, whereas this is not needed for Markdown.\n# The default value is: YES.\n# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.\n\nMARKDOWN_STRICT        = YES\n\n# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up\n# to that level are automatically included in the table of contents, even if\n# they do not have an id attribute.\n# Note: This feature currently applies only to Markdown headings.\n# Minimum value: 0, maximum value: 99, default value: 6.\n# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.\n\nTOC_INCLUDE_HEADINGS   = 5\n\n# The MARKDOWN_ID_STYLE tag can be used to specify the algorithm used to\n# generate identifiers for the Markdown headings. Note: Every identifier is\n# unique.\n# Possible values are: DOXYGEN use a fixed 'autotoc_md' string followed by a\n# sequence number starting at 0 and GITHUB use the lower case version of title\n# with any whitespace replaced by '-' and punctuation characters removed.\n# The default value is: DOXYGEN.\n# This tag requires that the tag MARKDOWN_SUPPORT is set to YES.\n\nMARKDOWN_ID_STYLE      = DOXYGEN\n\n# When enabled Doxygen tries to link words that correspond to documented\n# classes, or namespaces to their corresponding documentation. Such a link can\n# be prevented in individual cases by putting a % sign in front of the word or\n# globally by setting AUTOLINK_SUPPORT to NO. Words listed in the\n# AUTOLINK_IGNORE_WORDS tag are excluded from automatic linking.\n# The default value is: YES.\n\nAUTOLINK_SUPPORT       = YES\n\n# This tag specifies a list of words that, when matching the start of a word in\n# the documentation, will suppress auto links generation, if it is enabled via\n# AUTOLINK_SUPPORT. This list does not affect links explicitly created using #\n# or the \\link or \\ref commands.\n# This tag requires that the tag AUTOLINK_SUPPORT is set to YES.\n\nAUTOLINK_IGNORE_WORDS  =\n\n# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want\n# to include (a tag file for) the STL sources as input, then you should set this\n# tag to YES in order to let Doxygen match functions declarations and\n# definitions whose arguments contain STL classes (e.g. func(std::string);\n# versus func(std::string) {}). This also makes the inheritance and\n# collaboration diagrams that involve STL classes more complete and accurate.\n# The default value is: NO.\n\nBUILTIN_STL_SUPPORT    = NO\n\n# If you use Microsoft's C++/CLI language, you should set this option to YES to\n# enable parsing support.\n# The default value is: NO.\n\nCPP_CLI_SUPPORT        = NO\n\n# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:\n# https://www.riverbankcomputing.com/software) sources only. Doxygen will parse\n# them like normal C++ but will assume all classes use public instead of private\n# inheritance when no explicit protection keyword is present.\n# The default value is: NO.\n\nSIP_SUPPORT            = NO\n\n# For Microsoft's IDL there are propget and propput attributes to indicate\n# getter and setter methods for a property. Setting this option to YES will make\n# Doxygen to replace the get and set methods by a property in the documentation.\n# This will only work if the methods are indeed getting or setting a simple\n# type. If this is not the case, or you want to show the methods anyway, you\n# should set this option to NO.\n# The default value is: YES.\n\nIDL_PROPERTY_SUPPORT   = YES\n\n# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC\n# tag is set to YES then Doxygen will reuse the documentation of the first\n# member in the group (if any) for the other members of the group. By default\n# all members of a group must be documented explicitly.\n# The default value is: NO.\n\nDISTRIBUTE_GROUP_DOC   = NO\n\n# If one adds a struct or class to a group and this option is enabled, then also\n# any nested class or struct is added to the same group. By default this option\n# is disabled and one has to add nested compounds explicitly via \\ingroup.\n# The default value is: NO.\n\nGROUP_NESTED_COMPOUNDS = NO\n\n# Set the SUBGROUPING tag to YES to allow class member groups of the same type\n# (for instance a group of public functions) to be put as a subgroup of that\n# type (e.g. under the Public Functions section). Set it to NO to prevent\n# subgrouping. Alternatively, this can be done per class using the\n# \\nosubgrouping command.\n# The default value is: YES.\n\nSUBGROUPING            = YES\n\n# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions\n# are shown inside the group in which they are included (e.g. using \\ingroup)\n# instead of on a separate page (for HTML and Man pages) or section (for LaTeX\n# and RTF).\n#\n# Note that this feature does not work in combination with\n# SEPARATE_MEMBER_PAGES.\n# The default value is: NO.\n\nINLINE_GROUPED_CLASSES = NO\n\n# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions\n# with only public data fields or simple typedef fields will be shown inline in\n# the documentation of the scope in which they are defined (i.e. file,\n# namespace, or group documentation), provided this scope is documented. If set\n# to NO, structs, classes, and unions are shown on a separate page (for HTML and\n# Man pages) or section (for LaTeX and RTF).\n# The default value is: NO.\n\nINLINE_SIMPLE_STRUCTS  = NO\n\n# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or\n# enum is documented as struct, union, or enum with the name of the typedef. So\n# typedef struct TypeS {} TypeT, will appear in the documentation as a struct\n# with name TypeT. When disabled the typedef will appear as a member of a file,\n# namespace, or class. And the struct will be named TypeS. This can typically be\n# useful for C code in case the coding convention dictates that all compound\n# types are typedef'ed and only the typedef is referenced, never the tag name.\n# The default value is: NO.\n\nTYPEDEF_HIDES_STRUCT   = YES\n\n# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This\n# cache is used to resolve symbols given their name and scope. Since this can be\n# an expensive process and often the same symbol appears multiple times in the\n# code, Doxygen keeps a cache of pre-resolved symbols. If the cache is too small\n# Doxygen will become slower. If the cache is too large, memory is wasted. The\n# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range\n# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536\n# symbols. At the end of a run Doxygen will report the cache usage and suggest\n# the optimal cache size from a speed point of view.\n# Minimum value: 0, maximum value: 9, default value: 0.\n\nLOOKUP_CACHE_SIZE      = 0\n\n# The NUM_PROC_THREADS specifies the number of threads Doxygen is allowed to use\n# during processing. When set to 0 Doxygen will based this on the number of\n# cores available in the system. You can set it explicitly to a value larger\n# than 0 to get more control over the balance between CPU load and processing\n# speed. At this moment only the input processing can be done using multiple\n# threads. Since this is still an experimental feature the default is set to 1,\n# which effectively disables parallel processing. Please report any issues you\n# encounter. Generating dot graphs in parallel is controlled by the\n# DOT_NUM_THREADS setting.\n# Minimum value: 0, maximum value: 512, default value: 1.\n\nNUM_PROC_THREADS       = 1\n\n# If the TIMESTAMP tag is set different from NO then each generated page will\n# contain the date or date and time when the page was generated. Setting this to\n# NO can help when comparing the output of multiple runs.\n# Possible values are: YES, NO, DATETIME and DATE.\n# The default value is: NO.\n\nTIMESTAMP              = YES\n\n#---------------------------------------------------------------------------\n# Build related configuration options\n#---------------------------------------------------------------------------\n\n# If the EXTRACT_ALL tag is set to YES, Doxygen will assume all entities in\n# documentation are documented, even if no documentation was available. Private\n# class members and static file members will be hidden unless the\n# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.\n# Note: This will also disable the warnings about undocumented members that are\n# normally produced when WARNINGS is set to YES.\n# The default value is: NO.\n\nEXTRACT_ALL            = YES\n\n# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will\n# be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIVATE        = YES\n\n# If the EXTRACT_PRIV_VIRTUAL tag is set to YES, documented private virtual\n# methods of a class will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PRIV_VIRTUAL   = NO\n\n# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal\n# scope will be included in the documentation.\n# The default value is: NO.\n\nEXTRACT_PACKAGE        = NO\n\n# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be\n# included in the documentation.\n# The default value is: NO.\n\nEXTRACT_STATIC         = YES\n\n# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined\n# locally in source files will be included in the documentation. If set to NO,\n# only classes defined in header files are included. Does not have any effect\n# for Java sources.\n# The default value is: YES.\n\nEXTRACT_LOCAL_CLASSES  = YES\n\n# This flag is only useful for Objective-C code. If set to YES, local methods,\n# which are defined in the implementation section but not in the interface are\n# included in the documentation. If set to NO, only methods in the interface are\n# included.\n# The default value is: NO.\n\nEXTRACT_LOCAL_METHODS  = YES\n\n# If this flag is set to YES, the members of anonymous namespaces will be\n# extracted and appear in the documentation as a namespace called\n# 'anonymous_namespace{file}', where file will be replaced with the base name of\n# the file that contains the anonymous namespace. By default anonymous namespace\n# are hidden.\n# The default value is: NO.\n\nEXTRACT_ANON_NSPACES   = YES\n\n# If this flag is set to YES, the name of an unnamed parameter in a declaration\n# will be determined by the corresponding definition. By default unnamed\n# parameters remain unnamed in the output.\n# The default value is: YES.\n\nRESOLVE_UNNAMED_PARAMS = YES\n\n# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all\n# undocumented members inside documented classes or files. If set to NO these\n# members will be included in the various overviews, but no documentation\n# section is generated. This option has no effect if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_MEMBERS     = NO\n\n# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all\n# undocumented classes that are normally visible in the class hierarchy. If set\n# to NO, these classes will be included in the various overviews. This option\n# will also hide undocumented C++ concepts if enabled. This option has no effect\n# if EXTRACT_ALL is enabled.\n# The default value is: NO.\n\nHIDE_UNDOC_CLASSES     = NO\n\n# If the HIDE_UNDOC_NAMESPACES tag is set to YES, Doxygen will hide all\n# undocumented namespaces that are normally visible in the namespace hierarchy.\n# If set to NO, these namespaces will be included in the various overviews. This\n# option has no effect if EXTRACT_ALL is enabled.\n# The default value is: YES.\n\nHIDE_UNDOC_NAMESPACES  = YES\n\n# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all friend\n# declarations. If set to NO, these declarations will be included in the\n# documentation.\n# The default value is: NO.\n\nHIDE_FRIEND_COMPOUNDS  = NO\n\n# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any\n# documentation blocks found inside the body of a function. If set to NO, these\n# blocks will be appended to the function's detailed documentation block.\n# The default value is: NO.\n\nHIDE_IN_BODY_DOCS      = NO\n\n# The INTERNAL_DOCS tag determines if documentation that is typed after a\n# \\internal command is included. If the tag is set to NO then the documentation\n# will be excluded. Set it to YES to include the internal documentation.\n# The default value is: NO.\n\nINTERNAL_DOCS          = NO\n\n# With the correct setting of option CASE_SENSE_NAMES Doxygen will better be\n# able to match the capabilities of the underlying filesystem. In case the\n# filesystem is case sensitive (i.e. it supports files in the same directory\n# whose names only differ in casing), the option must be set to YES to properly\n# deal with such files in case they appear in the input. For filesystems that\n# are not case sensitive the option should be set to NO to properly deal with\n# output files written for symbols that only differ in casing, such as for two\n# classes, one named CLASS and the other named Class, and to also support\n# references to files without having to specify the exact matching casing. On\n# Windows (including Cygwin) and macOS, users should typically set this option\n# to NO, whereas on Linux or other Unix flavors it should typically be set to\n# YES.\n# Possible values are: SYSTEM, NO and YES.\n# The default value is: SYSTEM.\n\nCASE_SENSE_NAMES       = NO\n\n# If the HIDE_SCOPE_NAMES tag is set to NO then Doxygen will show members with\n# their full class and namespace scopes in the documentation. If set to YES, the\n# scope will be hidden.\n# The default value is: NO.\n\nHIDE_SCOPE_NAMES       = NO\n\n# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then Doxygen will\n# append additional text to a page's title, such as Class Reference. If set to\n# YES the compound reference will be hidden.\n# The default value is: NO.\n\nHIDE_COMPOUND_REFERENCE= NO\n\n# If the SHOW_HEADERFILE tag is set to YES then the documentation for a class\n# will show which file needs to be included to use the class.\n# The default value is: YES.\n\nSHOW_HEADERFILE        = YES\n\n# If the SHOW_INCLUDE_FILES tag is set to YES then Doxygen will put a list of\n# the files that are included by a file in the documentation of that file.\n# The default value is: YES.\n\nSHOW_INCLUDE_FILES     = NO\n\n# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each\n# grouped member an include statement to the documentation, telling the reader\n# which file to include in order to use the member.\n# The default value is: NO.\n\nSHOW_GROUPED_MEMB_INC  = NO\n\n# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen will list include\n# files with double quotes in the documentation rather than with sharp brackets.\n# The default value is: NO.\n\nFORCE_LOCAL_INCLUDES   = NO\n\n# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the\n# documentation for inline members.\n# The default value is: YES.\n\nINLINE_INFO            = YES\n\n# If the SORT_MEMBER_DOCS tag is set to YES then Doxygen will sort the\n# (detailed) documentation of file and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order.\n# The default value is: YES.\n\nSORT_MEMBER_DOCS       = NO\n\n# If the SORT_BRIEF_DOCS tag is set to YES then Doxygen will sort the brief\n# descriptions of file, namespace and class members alphabetically by member\n# name. If set to NO, the members will appear in declaration order. Note that\n# this will also influence the order of the classes in the class list.\n# The default value is: NO.\n\nSORT_BRIEF_DOCS        = NO\n\n# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then Doxygen will sort the\n# (brief and detailed) documentation of class members so that constructors and\n# destructors are listed first. If set to NO the constructors will appear in the\n# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.\n# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief\n# member documentation.\n# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting\n# detailed member documentation.\n# The default value is: NO.\n\nSORT_MEMBERS_CTORS_1ST = NO\n\n# If the SORT_GROUP_NAMES tag is set to YES then Doxygen will sort the hierarchy\n# of group names into alphabetical order. If set to NO the group names will\n# appear in their defined order.\n# The default value is: NO.\n\nSORT_GROUP_NAMES       = NO\n\n# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by\n# fully-qualified names, including namespaces. If set to NO, the class list will\n# be sorted only by class name, not including the namespace part.\n# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.\n# Note: This option applies only to the class list, not to the alphabetical\n# list.\n# The default value is: NO.\n\nSORT_BY_SCOPE_NAME     = NO\n\n# If the STRICT_PROTO_MATCHING option is enabled and Doxygen fails to do proper\n# type resolution of all parameters of a function it will reject a match between\n# the prototype and the implementation of a member function even if there is\n# only one candidate or it is obvious which candidate to choose by doing a\n# simple string match. By disabling STRICT_PROTO_MATCHING Doxygen will still\n# accept a match between prototype and implementation in such cases.\n# The default value is: NO.\n\nSTRICT_PROTO_MATCHING  = NO\n\n# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo\n# list. This list is created by putting \\todo commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TODOLIST      = YES\n\n# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test\n# list. This list is created by putting \\test commands in the documentation.\n# The default value is: YES.\n\nGENERATE_TESTLIST      = YES\n\n# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug\n# list. This list is created by putting \\bug commands in the documentation.\n# The default value is: YES.\n\nGENERATE_BUGLIST       = YES\n\n# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO)\n# the deprecated list. This list is created by putting \\deprecated commands in\n# the documentation.\n# The default value is: YES.\n\nGENERATE_DEPRECATEDLIST= YES\n\n# The GENERATE_REQUIREMENTS tag can be used to enable (YES) or disable (NO) the\n# requirements page. When enabled, this page is automatically created when at\n# least one comment block with a \\requirement command appears in the input.\n# The default value is: YES.\n\nGENERATE_REQUIREMENTS  = YES\n\n# The REQ_TRACEABILITY_INFO tag controls if traceability information is shown on\n# the requirements page (only relevant when using \\requirement comment blocks).\n# The setting NO will disable the traceablility information altogether. The\n# setting UNSATISFIED_ONLY will show a list of requirements that are missing a\n# satisfies relation (through the command: \\satisfies). Similarly the setting\n# UNVERIFIED_ONLY will show a list of requirements that are missing a verifies\n# relation (through the command: \\verifies). Setting the tag to YES (the\n# default) will show both lists if applicable.\n# Possible values are: YES, NO, UNSATISFIED_ONLY and UNVERIFIED_ONLY.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_REQUIREMENTS is set to YES.\n\nREQ_TRACEABILITY_INFO  = YES\n\n# The ENABLED_SECTIONS tag can be used to enable conditional documentation\n# sections, marked by \\if <section_label> ... \\endif and \\cond <section_label>\n# ... \\endcond blocks.\n\nENABLED_SECTIONS       =\n\n# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the\n# initial value of a variable or macro / define can have for it to appear in the\n# documentation. If the initializer consists of more lines than specified here\n# it will be hidden. Use a value of 0 to hide initializers completely. The\n# appearance of the value of individual variables and macros / defines can be\n# controlled using \\showinitializer or \\hideinitializer command in the\n# documentation regardless of this setting.\n# Minimum value: 0, maximum value: 10000, default value: 30.\n\nMAX_INITIALIZER_LINES  = 30\n\n# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at\n# the bottom of the documentation of classes and structs. If set to YES, the\n# list will mention the files that were used to generate the documentation.\n# The default value is: YES.\n\nSHOW_USED_FILES        = YES\n\n# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This\n# will remove the Files entry from the Quick Index and from the Folder Tree View\n# (if specified).\n# The default value is: YES.\n\nSHOW_FILES             = YES\n\n# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces\n# page. This will remove the Namespaces entry from the Quick Index and from the\n# Folder Tree View (if specified).\n# The default value is: YES.\n\nSHOW_NAMESPACES        = YES\n\n# The FILE_VERSION_FILTER tag can be used to specify a program or script that\n# Doxygen should invoke to get the current version for each file (typically from\n# the version control system). Doxygen will invoke the program by executing (via\n# popen()) the command command input-file, where command is the value of the\n# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided\n# by Doxygen. Whatever the program writes to standard output is used as the file\n# version. For an example see the documentation.\n\nFILE_VERSION_FILTER    =\n\n# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed\n# by Doxygen. The layout file controls the global structure of the generated\n# output files in an output format independent way. To create the layout file\n# that represents Doxygen's defaults, run Doxygen with the -l option. You can\n# optionally specify a file name after the option, if omitted DoxygenLayout.xml\n# will be used as the name of the layout file. See also section \"Changing the\n# layout of pages\" for information.\n#\n# Note that if you run Doxygen from a directory containing a file called\n# DoxygenLayout.xml, Doxygen will parse it automatically even if the LAYOUT_FILE\n# tag is left empty.\n\nLAYOUT_FILE            =\n\n# The CITE_BIB_FILES tag can be used to specify one or more bib files containing\n# the reference definitions. This must be a list of .bib files. The .bib\n# extension is automatically appended if omitted. This requires the bibtex tool\n# to be installed. See also https://en.wikipedia.org/wiki/BibTeX for more info.\n# For LaTeX the style of the bibliography can be controlled using\n# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the\n# search path. See also \\cite for info how to create references.\n\nCITE_BIB_FILES         =\n\n# The EXTERNAL_TOOL_PATH tag can be used to extend the search path (PATH\n# environment variable) so that external tools such as latex and gs can be\n# found.\n# Note: Directories specified with EXTERNAL_TOOL_PATH are added in front of the\n# path already specified by the PATH variable, and are added in the order\n# specified.\n# Note: This option is particularly useful for macOS version 14 (Sonoma) and\n# higher, when running Doxygen from Doxywizard, because in this case any user-\n# defined changes to the PATH are ignored. A typical example on macOS is to set\n# EXTERNAL_TOOL_PATH = /Library/TeX/texbin /usr/local/bin\n# together with the standard path, the full search path used by doxygen when\n# launching external tools will then become\n# PATH=/Library/TeX/texbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\n\nEXTERNAL_TOOL_PATH     =\n\n#---------------------------------------------------------------------------\n# Configuration options related to warning and progress messages\n#---------------------------------------------------------------------------\n\n# The QUIET tag can be used to turn on/off the messages that are generated to\n# standard output by Doxygen. If QUIET is set to YES this implies that the\n# messages are off.\n# The default value is: NO.\n\nQUIET                  = NO\n\n# The WARNINGS tag can be used to turn on/off the warning messages that are\n# generated to standard error (stderr) by Doxygen. If WARNINGS is set to YES\n# this implies that the warnings are on.\n#\n# Tip: Turn warnings on while writing the documentation.\n# The default value is: YES.\n\nWARNINGS               = YES\n\n# If the WARN_IF_UNDOCUMENTED tag is set to YES then Doxygen will generate\n# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag\n# will automatically be disabled.\n# The default value is: YES.\n\nWARN_IF_UNDOCUMENTED   = YES\n\n# If the WARN_IF_DOC_ERROR tag is set to YES, Doxygen will generate warnings for\n# potential errors in the documentation, such as documenting some parameters in\n# a documented function twice, or documenting parameters that don't exist or\n# using markup commands wrongly.\n# The default value is: YES.\n\nWARN_IF_DOC_ERROR      = YES\n\n# If WARN_IF_INCOMPLETE_DOC is set to YES, Doxygen will warn about incomplete\n# function parameter documentation. If set to NO, Doxygen will accept that some\n# parameters have no documentation without warning.\n# The default value is: YES.\n\nWARN_IF_INCOMPLETE_DOC = YES\n\n# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that\n# are documented, but have no documentation for their parameters or return\n# value. If set to NO, Doxygen will only warn about wrong parameter\n# documentation, but not about the absence of documentation. If EXTRACT_ALL is\n# set to YES then this flag will automatically be disabled. See also\n# WARN_IF_INCOMPLETE_DOC\n# The default value is: NO.\n\nWARN_NO_PARAMDOC       = YES\n\n# If WARN_IF_UNDOC_ENUM_VAL option is set to YES, Doxygen will warn about\n# undocumented enumeration values. If set to NO, Doxygen will accept\n# undocumented enumeration values. If EXTRACT_ALL is set to YES then this flag\n# will automatically be disabled.\n# The default value is: NO.\n\nWARN_IF_UNDOC_ENUM_VAL = NO\n\n# If WARN_LAYOUT_FILE option is set to YES, Doxygen will warn about issues found\n# while parsing the user defined layout file, such as missing or wrong elements.\n# See also LAYOUT_FILE for details. If set to NO, problems with the layout file\n# will be suppressed.\n# The default value is: YES.\n\nWARN_LAYOUT_FILE       = YES\n\n# If the WARN_AS_ERROR tag is set to YES then Doxygen will immediately stop when\n# a warning is encountered. If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS\n# then Doxygen will continue running as if WARN_AS_ERROR tag is set to NO, but\n# at the end of the Doxygen process Doxygen will return with a non-zero status.\n# If the WARN_AS_ERROR tag is set to FAIL_ON_WARNINGS_PRINT then Doxygen behaves\n# like FAIL_ON_WARNINGS but in case no WARN_LOGFILE is defined Doxygen will not\n# write the warning messages in between other messages but write them at the end\n# of a run, in case a WARN_LOGFILE is defined the warning messages will be\n# besides being in the defined file also be shown at the end of a run, unless\n# the WARN_LOGFILE is defined as - i.e. standard output (stdout) in that case\n# the behavior will remain as with the setting FAIL_ON_WARNINGS.\n# Possible values are: NO, YES, FAIL_ON_WARNINGS and FAIL_ON_WARNINGS_PRINT.\n# The default value is: NO.\n\nWARN_AS_ERROR          = NO\n\n# The WARN_FORMAT tag determines the format of the warning messages that Doxygen\n# can produce. The string should contain the $file, $line, and $text tags, which\n# will be replaced by the file and line number from which the warning originated\n# and the warning text. Optionally the format may contain $version, which will\n# be replaced by the version of the file (if it could be obtained via\n# FILE_VERSION_FILTER)\n# See also: WARN_LINE_FORMAT\n# The default value is: $file:$line: $text.\n\nWARN_FORMAT            = \"$file:$line: $text\"\n\n# In the $text part of the WARN_FORMAT command it is possible that a reference\n# to a more specific place is given. To make it easier to jump to this place\n# (outside of Doxygen) the user can define a custom \"cut\" / \"paste\" string.\n# Example:\n# WARN_LINE_FORMAT = \"'vi $file +$line'\"\n# See also: WARN_FORMAT\n# The default value is: at line $line of file $file.\n\nWARN_LINE_FORMAT       = \"at line $line of file $file\"\n\n# The WARN_LOGFILE tag can be used to specify a file to which warning and error\n# messages should be written. If left blank the output is written to standard\n# error (stderr). In case the file specified cannot be opened for writing the\n# warning and error messages are written to standard error. When as file - is\n# specified the warning and error messages are written to standard output\n# (stdout).\n\nWARN_LOGFILE           =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the input files\n#---------------------------------------------------------------------------\n\n# The INPUT tag is used to specify the files and/or directories that contain\n# documented source files. You may enter file names like myfile.cpp or\n# directories like /usr/src/myproject. Separate the files or directories with\n# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING\n# Note: If this tag is empty the current directory is searched.\n\nINPUT                  = $(SRCDIR)\n\n# This tag can be used to specify the character encoding of the source files\n# that Doxygen parses. Internally Doxygen uses the UTF-8 encoding. Doxygen uses\n# libiconv (or the iconv built into libc) for the transcoding. See the libiconv\n# documentation (see:\n# https://www.gnu.org/software/libiconv/) for the list of possible encodings.\n# See also: INPUT_FILE_ENCODING\n# The default value is: UTF-8.\n\nINPUT_ENCODING         = UTF-8\n\n# This tag can be used to specify the character encoding of the source files\n# that Doxygen parses. The INPUT_FILE_ENCODING tag can be used to specify\n# character encoding on a per file pattern basis. Doxygen will compare the file\n# name with each pattern and apply the encoding instead of the default\n# INPUT_ENCODING if there is a match. The character encodings are a list of the\n# form: pattern=encoding (like *.php=ISO-8859-1).\n# See also: INPUT_ENCODING for further information on supported encodings.\n\nINPUT_FILE_ENCODING    =\n\n# If the value of the INPUT tag contains directories, you can use the\n# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and\n# *.h) to filter out the source-files in the directories.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# read by Doxygen.\n#\n# Note the list of default checked file patterns might differ from the list of\n# default file extension mappings.\n#\n# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cxxm,\n# *.cpp, *.cppm, *.ccm, *.c++, *.c++m, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl,\n# *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp, *.h++, *.l, *.cs, *.d, *.php,\n# *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown, *.md, *.mm, *.dox (to be\n# provided as Doxygen C comment), *.py, *.pyw, *.f90, *.f95, *.f03, *.f08,\n# *.f18, *.f, *.for, *.vhd, *.vhdl, *.ucf, *.qsf and *.ice.\n\nFILE_PATTERNS          = *.c \\\n                         *.h\n\n# The RECURSIVE tag can be used to specify whether or not subdirectories should\n# be searched for input files as well.\n# The default value is: NO.\n\nRECURSIVE              = YES\n\n# The EXCLUDE tag can be used to specify files and/or directories that should be\n# excluded from the INPUT source files. This way you can easily exclude a\n# subdirectory from a directory tree whose root is specified with the INPUT tag.\n#\n# Note that relative paths are relative to the directory from which Doxygen is\n# run.\n\nEXCLUDE                = examples \\\n                         tests\n\n# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or\n# directories that are symbolic links (a Unix file system feature) are excluded\n# from the input.\n# The default value is: NO.\n\nEXCLUDE_SYMLINKS       = NO\n\n# If the value of the INPUT tag contains directories, you can use the\n# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude\n# certain files from those directories.\n#\n# Note that the wildcards are matched against the file with absolute path, so to\n# exclude all test directories for example use the pattern */test/*\n\nEXCLUDE_PATTERNS       = .svn\n\n# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names\n# (namespaces, classes, functions, etc.) that should be excluded from the\n# output. The symbol name can be a fully qualified name, a word, or if the\n# wildcard * is used, a substring. Examples: ANamespace, AClass,\n# ANamespace::AClass, ANamespace::*Test\n\nEXCLUDE_SYMBOLS        =\n\n# The EXAMPLE_PATH tag can be used to specify one or more files or directories\n# that contain example code fragments that are included (see the \\include\n# command).\n\nEXAMPLE_PATH           =\n\n# If the value of the EXAMPLE_PATH tag contains directories, you can use the\n# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and\n# *.h) to filter out the source-files in the directories. If left blank all\n# files are included.\n\nEXAMPLE_PATTERNS       = *\n\n# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be\n# searched for input files to be used with the \\include or \\dontinclude commands\n# irrespective of the value of the RECURSIVE tag.\n# The default value is: NO.\n\nEXAMPLE_RECURSIVE      = NO\n\n# The IMAGE_PATH tag can be used to specify one or more files or directories\n# that contain images that are to be included in the documentation (see the\n# \\image command).\n\nIMAGE_PATH             =\n\n# The INPUT_FILTER tag can be used to specify a program that Doxygen should\n# invoke to filter for each input file. Doxygen will invoke the filter program\n# by executing (via popen()) the command:\n#\n# <filter> <input-file>\n#\n# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the\n# name of an input file. Doxygen will then use the output that the filter\n# program writes to standard output. If FILTER_PATTERNS is specified, this tag\n# will be ignored.\n#\n# Note that the filter must not add or remove lines; it is applied before the\n# code is scanned, but not when the output code is generated. If lines are added\n# or removed, the anchors will not be placed correctly.\n#\n# Note that Doxygen will use the data processed and written to standard output\n# for further processing, therefore nothing else, like debug statements or used\n# commands (so in case of a Windows batch file always use @echo OFF), should be\n# written to standard output.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by Doxygen.\n\nINPUT_FILTER           =\n\n# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern\n# basis. Doxygen will compare the file name with each pattern and apply the\n# filter if there is a match. The filters are a list of the form: pattern=filter\n# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how\n# filters are used. If the FILTER_PATTERNS tag is empty or if none of the\n# patterns match the file name, INPUT_FILTER is applied.\n#\n# Note that for custom extensions or not directly supported extensions you also\n# need to set EXTENSION_MAPPING for the extension otherwise the files are not\n# properly processed by Doxygen.\n\nFILTER_PATTERNS        =\n\n# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using\n# INPUT_FILTER) will also be used to filter the input files that are used for\n# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).\n# The default value is: NO.\n\nFILTER_SOURCE_FILES    = NO\n\n# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file\n# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and\n# it is also possible to disable source filtering for a specific pattern using\n# *.ext= (so without naming a filter).\n# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.\n\nFILTER_SOURCE_PATTERNS =\n\n# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that\n# is part of the input, its contents will be placed on the main page\n# (index.html). This can be useful if you have a project on for instance GitHub\n# and want to reuse the introduction page also for the Doxygen output.\n\nUSE_MDFILE_AS_MAINPAGE =\n\n# If the IMPLICIT_DIR_DOCS tag is set to YES, any README.md file found in sub-\n# directories of the project's root, is used as the documentation for that sub-\n# directory, except when the README.md starts with a \\dir, \\page or \\mainpage\n# command. If set to NO, the README.md file needs to start with an explicit \\dir\n# command in order to be used as directory documentation.\n# The default value is: YES.\n\nIMPLICIT_DIR_DOCS      = YES\n\n# The Fortran standard specifies that for fixed formatted Fortran code all\n# characters from position 72 are to be considered as comment. A common\n# extension is to allow longer lines before the automatic comment starts. The\n# setting FORTRAN_COMMENT_AFTER will also make it possible that longer lines can\n# be processed before the automatic comment starts.\n# Minimum value: 7, maximum value: 10000, default value: 72.\n\nFORTRAN_COMMENT_AFTER  = 72\n\n#---------------------------------------------------------------------------\n# Configuration options related to source browsing\n#---------------------------------------------------------------------------\n\n# If the SOURCE_BROWSER tag is set to YES then a list of source files will be\n# generated. Documented entities will be cross-referenced with these sources.\n#\n# Note: To get rid of all source code in the generated output, make sure that\n# also VERBATIM_HEADERS is set to NO.\n# The default value is: NO.\n\nSOURCE_BROWSER         = NO\n\n# Setting the INLINE_SOURCES tag to YES will include the body of functions,\n# multi-line macros, enums or list initialized variables directly into the\n# documentation.\n# The default value is: NO.\n\nINLINE_SOURCES         = NO\n\n# Setting the STRIP_CODE_COMMENTS tag to YES will instruct Doxygen to hide any\n# special comment blocks from generated source code fragments. Normal C, C++ and\n# Fortran comments will always remain visible.\n# The default value is: YES.\n\nSTRIP_CODE_COMMENTS    = YES\n\n# If the REFERENCED_BY_RELATION tag is set to YES then for each documented\n# entity all documented functions referencing it will be listed.\n# The default value is: NO.\n\nREFERENCED_BY_RELATION = NO\n\n# If the REFERENCES_RELATION tag is set to YES then for each documented function\n# all documented entities called/used by that function will be listed.\n# The default value is: NO.\n\nREFERENCES_RELATION    = NO\n\n# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set\n# to YES then the hyperlinks from functions in REFERENCES_RELATION and\n# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will\n# link to the documentation.\n# The default value is: YES.\n\nREFERENCES_LINK_SOURCE = YES\n\n# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the\n# source code will show a tooltip with additional information such as prototype,\n# brief description and links to the definition and documentation. Since this\n# will make the HTML file larger and loading of large files a bit slower, you\n# can opt to disable this feature.\n# The default value is: YES.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nSOURCE_TOOLTIPS        = YES\n\n# If the USE_HTAGS tag is set to YES then the references to source code will\n# point to the HTML generated by the htags(1) tool instead of Doxygen built-in\n# source browser. The htags tool is part of GNU's global source tagging system\n# (see https://www.gnu.org/software/global/global.html). You will need version\n# 4.8.6 or higher.\n#\n# To use it do the following:\n# - Install the latest version of global\n# - Enable SOURCE_BROWSER and USE_HTAGS in the configuration file\n# - Make sure the INPUT points to the root of the source tree\n# - Run doxygen as normal\n#\n# Doxygen will invoke htags (and that will in turn invoke gtags), so these\n# tools must be available from the command line (i.e. in the search path).\n#\n# The result: instead of the source browser generated by Doxygen, the links to\n# source code will now point to the output of htags.\n# The default value is: NO.\n# This tag requires that the tag SOURCE_BROWSER is set to YES.\n\nUSE_HTAGS              = NO\n\n# If the VERBATIM_HEADERS tag is set the YES then Doxygen will generate a\n# verbatim copy of the header file for each class for which an include is\n# specified. Set to NO to disable this.\n# See also: Section \\class.\n# The default value is: YES.\n\nVERBATIM_HEADERS       = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the alphabetical class index\n#---------------------------------------------------------------------------\n\n# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all\n# compounds will be generated. Enable this if the project contains a lot of\n# classes, structs, unions or interfaces.\n# The default value is: YES.\n\nALPHABETICAL_INDEX     = NO\n\n# The IGNORE_PREFIX tag can be used to specify a prefix (or a list of prefixes)\n# that should be ignored while generating the index headers. The IGNORE_PREFIX\n# tag works for classes, function and member names. The entity will be placed in\n# the alphabetical list under the first letter of the entity name that remains\n# after removing the prefix.\n# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.\n\nIGNORE_PREFIX          =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the HTML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_HTML tag is set to YES, Doxygen will generate HTML output\n# The default value is: YES.\n\nGENERATE_HTML          = YES\n\n# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_OUTPUT            = html\n\n# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each\n# generated HTML page (for example: .htm, .php, .asp).\n# The default value is: .html.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FILE_EXTENSION    = .html\n\n# The HTML_HEADER tag can be used to specify a user-defined HTML header file for\n# each generated HTML page. If the tag is left blank Doxygen will generate a\n# standard header.\n#\n# To get valid HTML the header file that includes any scripts and style sheets\n# that Doxygen needs, which is dependent on the configuration options used (e.g.\n# the setting GENERATE_TREEVIEW). It is highly recommended to start with a\n# default header using\n# doxygen -w html new_header.html new_footer.html new_stylesheet.css\n# YourConfigFile\n# and then modify the file new_header.html. See also section \"Doxygen usage\"\n# for information on how to generate the default header that Doxygen normally\n# uses.\n# Note: The header is subject to change so you typically have to regenerate the\n# default header when upgrading to a newer version of Doxygen. For a description\n# of the possible markers and block names see the documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_HEADER            =\n\n# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each\n# generated HTML page. If the tag is left blank Doxygen will generate a standard\n# footer. See HTML_HEADER for more information on how to generate a default\n# footer and what special commands can be used inside the footer. See also\n# section \"Doxygen usage\" for information on how to generate the default footer\n# that Doxygen normally uses.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FOOTER            =\n\n# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style\n# sheet that is used by each HTML page. It can be used to fine-tune the look of\n# the HTML output. If left blank Doxygen will generate a default style sheet.\n# See also section \"Doxygen usage\" for information on how to generate the style\n# sheet that Doxygen normally uses.\n# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as\n# it is more robust and this tag (HTML_STYLESHEET) will in the future become\n# obsolete.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_STYLESHEET        =\n\n# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# cascading style sheets that are included after the standard style sheets\n# created by Doxygen. Using this option one can overrule certain style aspects.\n# This is preferred over using HTML_STYLESHEET since it does not replace the\n# standard style sheet and is therefore more robust against future updates.\n# Doxygen will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list).\n# Note: Since the styling of scrollbars can currently not be overruled in\n# Webkit/Chromium, the styling will be left out of the default doxygen.css if\n# one or more extra stylesheets have been specified. So if scrollbar\n# customization is desired it has to be added explicitly. For an example see the\n# documentation.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_STYLESHEET  =\n\n# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the HTML output directory. Note\n# that these files will be copied to the base HTML output directory. Use the\n# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these\n# files. In the HTML_STYLESHEET file, use the file name only. Also note that the\n# files will be copied as-is; there are no commands or markers available.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_EXTRA_FILES       =\n\n# The HTML_COLORSTYLE tag can be used to specify if the generated HTML output\n# should be rendered with a dark or light theme.\n# Possible values are: LIGHT always generates light mode output, DARK always\n# generates dark mode output, AUTO_LIGHT automatically sets the mode according\n# to the user preference, uses light mode if no preference is set (the default),\n# AUTO_DARK automatically sets the mode according to the user preference, uses\n# dark mode if no preference is set and TOGGLE allows a user to switch between\n# light and dark mode via a button.\n# The default value is: AUTO_LIGHT.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE        = DARK\n\n# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen\n# will adjust the colors in the style sheet and background images according to\n# this color. Hue is specified as an angle on a color-wheel, see\n# https://en.wikipedia.org/wiki/Hue for more information. For instance the value\n# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300\n# purple, and 360 is red again.\n# Minimum value: 0, maximum value: 359, default value: 220.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_HUE    = 220\n\n# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors\n# in the HTML output. For a value of 0 the output will use gray-scales only. A\n# value of 255 will produce the most vivid colors.\n# Minimum value: 0, maximum value: 255, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_SAT    = 100\n\n# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the\n# luminance component of the colors in the HTML output. Values below 100\n# gradually make the output lighter, whereas values above 100 make the output\n# darker. The value divided by 100 is the actual gamma applied, so 80 represents\n# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not\n# change the gamma.\n# Minimum value: 40, maximum value: 240, default value: 80.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COLORSTYLE_GAMMA  = 80\n\n# If the HTML_DYNAMIC_MENUS tag is set to YES then the generated HTML\n# documentation will contain a main index with vertical navigation menus that\n# are dynamically created via JavaScript. If disabled, the navigation index will\n# consists of multiple levels of tabs that are statically embedded in every HTML\n# page. Disable this option to support browsers that do not have JavaScript,\n# like the Qt help browser.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_MENUS     = NO\n\n# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML\n# documentation will contain sections that can be hidden and shown after the\n# page has loaded.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_DYNAMIC_SECTIONS  = NO\n\n# If the HTML_CODE_FOLDING tag is set to YES then classes and functions can be\n# dynamically folded and expanded in the generated HTML source code.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_CODE_FOLDING      = YES\n\n# If the HTML_COPY_CLIPBOARD tag is set to YES then Doxygen will show an icon in\n# the top right corner of code and text fragments that allows the user to copy\n# its content to the clipboard. Note this only works if supported by the browser\n# and the web page is served via a secure context (see:\n# https://www.w3.org/TR/secure-contexts/), i.e. using the https: or file:\n# protocol.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_COPY_CLIPBOARD    = NO\n\n# Doxygen stores a couple of settings persistently in the browser (via e.g.\n# cookies). By default these settings apply to all HTML pages generated by\n# Doxygen across all projects. The HTML_PROJECT_COOKIE tag can be used to store\n# the settings under a project specific key, such that the user preferences will\n# be stored separately.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_PROJECT_COOKIE    =\n\n# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries\n# shown in the various tree structured indices initially; the user can expand\n# and collapse entries dynamically later on. Doxygen will expand the tree to\n# such a level that at most the specified number of entries are visible (unless\n# a fully collapsed tree already exceeds this amount). So setting the number of\n# entries 1 will produce a full collapsed tree by default. 0 is a special value\n# representing an infinite number of entries and will result in a full expanded\n# tree by default.\n# Minimum value: 0, maximum value: 9999, default value: 100.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_INDEX_NUM_ENTRIES = 100\n\n# If the GENERATE_DOCSET tag is set to YES, additional index files will be\n# generated that can be used as input for Apple's Xcode 3 integrated development\n# environment (see:\n# https://developer.apple.com/xcode/), introduced with OSX 10.5 (Leopard). To\n# create a documentation set, Doxygen will generate a Makefile in the HTML\n# output directory. Running make will produce the docset in that directory and\n# running make install will install the docset in\n# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at\n# startup. See https://developer.apple.com/library/archive/featuredarticles/Doxy\n# genXcode/_index.html for more information.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_DOCSET        = NO\n\n# This tag determines the name of the docset feed. A documentation feed provides\n# an umbrella under which multiple documentation sets from a single provider\n# (such as a company or product suite) can be grouped.\n# The default value is: Doxygen generated docs.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_FEEDNAME        = \"Doxygen generated docs\"\n\n# This tag determines the URL of the docset feed. A documentation feed provides\n# an umbrella under which multiple documentation sets from a single provider\n# (such as a company or product suite) can be grouped.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_FEEDURL         =\n\n# This tag specifies a string that should uniquely identify the documentation\n# set bundle. This should be a reverse domain-name style string, e.g.\n# com.mycompany.MyDocSet. Doxygen will append .docset to the name.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_BUNDLE_ID       = org.doxygen.Project\n\n# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify\n# the documentation publisher. This should be a reverse domain-name style\n# string, e.g. com.mycompany.MyDocSet.documentation.\n# The default value is: org.doxygen.Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_ID    = org.doxygen.Publisher\n\n# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.\n# The default value is: Publisher.\n# This tag requires that the tag GENERATE_DOCSET is set to YES.\n\nDOCSET_PUBLISHER_NAME  = Publisher\n\n# If the GENERATE_HTMLHELP tag is set to YES then Doxygen generates three\n# additional HTML index files: index.hhp, index.hhc, and index.hhk. The\n# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop\n# on Windows. In the beginning of 2021 Microsoft took the original page, with\n# a.o. the download links, offline (the HTML help workshop was already many\n# years in maintenance mode). You can download the HTML help workshop from the\n# web archives at Installation executable (see:\n# http://web.archive.org/web/20160201063255/http://download.microsoft.com/downlo\n# ad/0/A/9/0A939EF6-E31C-430F-A3DF-DFAE7960D564/htmlhelp.exe).\n#\n# The HTML Help Workshop contains a compiler that can convert all HTML output\n# generated by Doxygen into a single compiled HTML file (.chm). Compiled HTML\n# files are now used as the Windows 98 help format, and will replace the old\n# Windows help format (.hlp) on all Windows platforms in the future. Compressed\n# HTML files also contain an index, a table of contents, and you can search for\n# words in the documentation. The HTML workshop also contains a viewer for\n# compressed HTML files.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_HTMLHELP      = YES\n\n# The CHM_FILE tag can be used to specify the file name of the resulting .chm\n# file. You can add a path in front of the file if the result should not be\n# written to the html output directory.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_FILE               =\n\n# The HHC_LOCATION tag can be used to specify the location (absolute path\n# including file name) of the HTML help compiler (hhc.exe). If non-empty,\n# Doxygen will try to run the HTML help compiler on the generated index.hhp.\n# The file has to be specified with full path.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nHHC_LOCATION           =\n\n# The GENERATE_CHI flag controls if a separate .chi index file is generated\n# (YES) or that it should be included in the main .chm file (NO).\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nGENERATE_CHI           = NO\n\n# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc)\n# and project file content.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nCHM_INDEX_ENCODING     =\n\n# The BINARY_TOC flag controls whether a binary table of contents is generated\n# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it\n# enables the Previous and Next buttons.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nBINARY_TOC             = NO\n\n# The TOC_EXPAND flag can be set to YES to add extra items for group members to\n# the table of contents of the HTML help documentation and to the tree view.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTMLHELP is set to YES.\n\nTOC_EXPAND             = NO\n\n# The SITEMAP_URL tag is used to specify the full URL of the place where the\n# generated documentation will be placed on the server by the user during the\n# deployment of the documentation. The generated sitemap is called sitemap.xml\n# and placed on the directory specified by HTML_OUTPUT. In case no SITEMAP_URL\n# is specified no sitemap is generated. For information about the sitemap\n# protocol see https://www.sitemaps.org\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nSITEMAP_URL            =\n\n# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and\n# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that\n# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help\n# (.qch) of the generated HTML documentation.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_QHP           = NO\n\n# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify\n# the file name of the resulting .qch file. The path specified is relative to\n# the HTML output folder.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQCH_FILE               =\n\n# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help\n# Project output. For more information please see Qt Help Project / Namespace\n# (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#namespace).\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_NAMESPACE          = org.doxygen.Project\n\n# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt\n# Help Project output. For more information please see Qt Help Project / Virtual\n# Folders (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#virtual-folders).\n# The default value is: doc.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_VIRTUAL_FOLDER     = doc\n\n# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom\n# filter to add. For more information please see Qt Help Project / Custom\n# Filters (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_NAME   =\n\n# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the\n# custom filter to add. For more information please see Qt Help Project / Custom\n# Filters (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#custom-filters).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_CUST_FILTER_ATTRS  =\n\n# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this\n# project's filter section matches. Qt Help Project / Filter Attributes (see:\n# https://doc.qt.io/archives/qt-4.8/qthelpproject.html#filter-attributes).\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHP_SECT_FILTER_ATTRS  =\n\n# The QHG_LOCATION tag can be used to specify the location (absolute path\n# including file name) of Qt's qhelpgenerator. If non-empty Doxygen will try to\n# run qhelpgenerator on the generated .qhp file.\n# This tag requires that the tag GENERATE_QHP is set to YES.\n\nQHG_LOCATION           =\n\n# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be\n# generated, together with the HTML files, they form an Eclipse help plugin. To\n# install this plugin and make it available under the help contents menu in\n# Eclipse, the contents of the directory containing the HTML and XML files needs\n# to be copied into the plugins directory of eclipse. The name of the directory\n# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.\n# After copying Eclipse needs to be restarted before the help appears.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_ECLIPSEHELP   = NO\n\n# A unique identifier for the Eclipse help plugin. When installing the plugin\n# the directory name containing the HTML and XML files should also have this\n# name. Each documentation set should have its own identifier.\n# The default value is: org.doxygen.Project.\n# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.\n\nECLIPSE_DOC_ID         = org.doxygen.Project\n\n# If you want full control over the layout of the generated HTML pages it might\n# be necessary to disable the index and replace it with your own. The\n# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top\n# of each HTML page. A value of NO enables the index and the value YES disables\n# it. Since the tabs in the index contain the same information as the navigation\n# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nDISABLE_INDEX          = YES\n\n# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index\n# structure should be generated to display hierarchical information. If the tag\n# value is set to YES, a side panel will be generated containing a tree-like\n# index structure (just like the one that is generated for HTML Help). For this\n# to work a browser that supports JavaScript, DHTML, CSS and frames is required\n# (i.e. any modern browser). Windows users are probably better off using the\n# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can\n# further fine tune the look of the index (see \"Fine-tuning the output\"). As an\n# example, the default style sheet generated by Doxygen has an example that\n# shows how to put an image at the root of the tree instead of the PROJECT_NAME.\n# Since the tree basically has more details information than the tab index, you\n# could consider setting DISABLE_INDEX to YES when enabling this option.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nGENERATE_TREEVIEW      = NO\n\n# When GENERATE_TREEVIEW is set to YES, the PAGE_OUTLINE_PANEL option determines\n# if an additional navigation panel is shown at the right hand side of the\n# screen, displaying an outline of the contents of the main page, similar to\n# e.g. https://developer.android.com/reference If GENERATE_TREEVIEW is set to\n# NO, this option has no effect.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nPAGE_OUTLINE_PANEL     = YES\n\n# When GENERATE_TREEVIEW is set to YES, the FULL_SIDEBAR option determines if\n# the side bar is limited to only the treeview area (value NO) or if it should\n# extend to the full height of the window (value YES). Setting this to YES gives\n# a layout similar to e.g. https://docs.readthedocs.io with more room for\n# contents, but less room for the project logo, title, and description. If\n# GENERATE_TREEVIEW is set to NO, this option has no effect.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFULL_SIDEBAR           = NO\n\n# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that\n# Doxygen will group on one line in the generated HTML documentation.\n#\n# Note that a value of 0 will completely suppress the enum values from appearing\n# in the overview section.\n# Minimum value: 0, maximum value: 20, default value: 4.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nENUM_VALUES_PER_LINE   = 4\n\n# When the SHOW_ENUM_VALUES tag is set doxygen will show the specified\n# enumeration values besides the enumeration mnemonics.\n# The default value is: NO.\n\nSHOW_ENUM_VALUES       = NO\n\n# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used\n# to set the initial width (in pixels) of the frame in which the tree is shown.\n# Minimum value: 0, maximum value: 1500, default value: 250.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nTREEVIEW_WIDTH         = 250\n\n# If the EXT_LINKS_IN_WINDOW option is set to YES, Doxygen will open links to\n# external symbols imported via tag files in a separate window.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nEXT_LINKS_IN_WINDOW    = NO\n\n# If the OBFUSCATE_EMAILS tag is set to YES, Doxygen will obfuscate email\n# addresses.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nOBFUSCATE_EMAILS       = YES\n\n# If the HTML_FORMULA_FORMAT option is set to svg, Doxygen will use the pdf2svg\n# tool (see https://github.com/dawbarton/pdf2svg) or inkscape (see\n# https://inkscape.org) to generate formulas as SVG images instead of PNGs for\n# the HTML output. These images will generally look nicer at scaled resolutions.\n# Possible values are: png (the default) and svg (looks nicer but requires the\n# pdf2svg or inkscape tool).\n# The default value is: png.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nHTML_FORMULA_FORMAT    = png\n\n# Use this tag to change the font size of LaTeX formulas included as images in\n# the HTML documentation. When you change the font size after a successful\n# Doxygen run you need to manually remove any form_*.png images from the HTML\n# output directory to force them to be regenerated.\n# Minimum value: 8, maximum value: 50, default value: 10.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nFORMULA_FONTSIZE       = 10\n\n# The FORMULA_MACROFILE can contain LaTeX \\newcommand and \\renewcommand commands\n# to create new LaTeX commands to be used in formulas as building blocks. See\n# the section \"Including formulas\" for details.\n\nFORMULA_MACROFILE      =\n\n# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see\n# https://www.mathjax.org) which uses client side JavaScript for the rendering\n# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX\n# installed or if you want to formulas look prettier in the HTML output. When\n# enabled you may also need to install MathJax separately and configure the path\n# to it using the MATHJAX_RELPATH option.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nUSE_MATHJAX            = NO\n\n# With MATHJAX_VERSION it is possible to specify the MathJax version to be used.\n# Note that the different versions of MathJax have different requirements with\n# regards to the different settings, so it is possible that also other MathJax\n# settings have to be changed when switching between the different MathJax\n# versions.\n# Possible values are: MathJax_2, MathJax_3 and MathJax_4.\n# The default value is: MathJax_2.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_VERSION        = MathJax_2\n\n# When MathJax is enabled you can set the default output format to be used for\n# the MathJax output. For more details about the output format see MathJax\n# version 2 (see:\n# https://docs.mathjax.org/en/v2.7/output.html), MathJax version 3 (see:\n# https://docs.mathjax.org/en/v3.2/output/index.html) and MathJax version 4\n# (see:\n# https://docs.mathjax.org/en/v4.0/output/index.htm).\n# Possible values are: HTML-CSS (which is slower, but has the best\n# compatibility. This is the name for Mathjax version 2, for MathJax version 3\n# this will be translated into chtml), NativeMML (i.e. MathML. Only supported\n# for MathJax 2. For MathJax version 3 chtml will be used instead.), chtml (This\n# is the name for Mathjax version 3, for MathJax version 2 this will be\n# translated into HTML-CSS) and SVG.\n# The default value is: HTML-CSS.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_FORMAT         = HTML-CSS\n\n# When MathJax is enabled you need to specify the location relative to the HTML\n# output directory using the MATHJAX_RELPATH option. For Mathjax version 2 the\n# destination directory should contain the MathJax.js script. For instance, if\n# the mathjax directory is located at the same level as the HTML output\n# directory, then MATHJAX_RELPATH should be ../mathjax.s For Mathjax versions 3\n# and 4 the destination directory should contain the tex-<format>.js script\n# (where <format> is either chtml or svg). The default value points to the\n# MathJax Content Delivery Network so you can quickly see the result without\n# installing MathJax. However, it is strongly recommended to install a local\n# copy of MathJax from https://www.mathjax.org before deployment. The default\n# value is:\n# - in case of MathJax version 2: https://cdn.jsdelivr.net/npm/mathjax@2\n# - in case of MathJax version 3: https://cdn.jsdelivr.net/npm/mathjax@3\n# - in case of MathJax version 4: https://cdn.jsdelivr.net/npm/mathjax@4\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_RELPATH        = http://www.mathjax.org/mathjax\n\n# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax\n# extension names that should be enabled during MathJax rendering. For example\n# for MathJax version 2 (see https://docs.mathjax.org/en/v2.7/tex.html):\n# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols\n# For example for MathJax version 3 (see\n# https://docs.mathjax.org/en/v3.2/input/tex/extensions/):\n# MATHJAX_EXTENSIONS = ams\n# For example for MathJax version 4 (see\n# https://docs.mathjax.org/en/v4.0/input/tex/extensions/):\n# MATHJAX_EXTENSIONS = units\n# Note that for Mathjax version 4 quite a few extensions are already\n# automatically loaded. To disable a package in Mathjax version 4 one can use\n# the package name prepended with a minus sign (- like MATHJAX_EXTENSIONS +=\n# -textmacros)\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_EXTENSIONS     =\n\n# The MATHJAX_CODEFILE tag can be used to specify a file with JavaScript pieces\n# of code that will be used on startup of the MathJax code. See the Mathjax site\n# for more details:\n# - MathJax version 2 (see:\n# https://docs.mathjax.org/en/v2.7/)\n# - MathJax version 3 (see:\n# https://docs.mathjax.org/en/v3.2/)\n# - MathJax version 4 (see:\n# https://docs.mathjax.org/en/v4.0/) For an example see the documentation.\n# This tag requires that the tag USE_MATHJAX is set to YES.\n\nMATHJAX_CODEFILE       =\n\n# When the SEARCHENGINE tag is enabled Doxygen will generate a search box for\n# the HTML output. The underlying search engine uses JavaScript and DHTML and\n# should work on any modern browser. Note that when using HTML help\n# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)\n# there is already a search function so this one should typically be disabled.\n# For large projects the JavaScript based search engine can be slow, then\n# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to\n# search using the keyboard; to jump to the search box use <access key> + S\n# (what the <access key> is depends on the OS and browser, but it is typically\n# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down\n# key> to jump into the search results window, the results can be navigated\n# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel\n# the search. The filter options can be selected when the cursor is inside the\n# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>\n# to select a filter and <Enter> or <escape> to activate or cancel the filter\n# option.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_HTML is set to YES.\n\nSEARCHENGINE           = NO\n\n# When the SERVER_BASED_SEARCH tag is enabled the search engine will be\n# implemented using a web server instead of a web client using JavaScript. There\n# are two flavors of web server based searching depending on the EXTERNAL_SEARCH\n# setting. When disabled, Doxygen will generate a PHP script for searching and\n# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing\n# and searching needs to be provided by external tools. See the section\n# \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSERVER_BASED_SEARCH    = NO\n\n# When EXTERNAL_SEARCH tag is enabled Doxygen will no longer generate the PHP\n# script for searching. Instead the search results are written to an XML file\n# which needs to be processed by an external indexer. Doxygen will invoke an\n# external search engine pointed to by the SEARCHENGINE_URL option to obtain the\n# search results.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see:\n# https://xapian.org/).\n#\n# See the section \"External Indexing and Searching\" for details.\n# The default value is: NO.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH        = NO\n\n# The SEARCHENGINE_URL should point to a search engine hosted by a web server\n# which will return the search results when EXTERNAL_SEARCH is enabled.\n#\n# Doxygen ships with an example indexer (doxyindexer) and search engine\n# (doxysearch.cgi) which are based on the open source search engine library\n# Xapian (see:\n# https://xapian.org/). See the section \"External Indexing and Searching\" for\n# details.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHENGINE_URL       =\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed\n# search data is written to a file for indexing by an external tool. With the\n# SEARCHDATA_FILE tag the name of this file can be specified.\n# The default file is: searchdata.xml.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nSEARCHDATA_FILE        = searchdata.xml\n\n# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the\n# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is\n# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple\n# projects and redirect the results back to the right project.\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTERNAL_SEARCH_ID     =\n\n# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through Doxygen\n# projects other than the one defined by this configuration file, but that are\n# all added to the same external search index. Each project needs to have a\n# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of\n# to a relative location where the documentation can be found. The format is:\n# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...\n# This tag requires that the tag SEARCHENGINE is set to YES.\n\nEXTRA_SEARCH_MAPPINGS  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the LaTeX output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_LATEX tag is set to YES, Doxygen will generate LaTeX output.\n# The default value is: YES.\n\nGENERATE_LATEX         = NO\n\n# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: latex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_OUTPUT           = latex\n\n# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be\n# invoked.\n#\n# Note that when not enabling USE_PDFLATEX the default is latex when enabling\n# USE_PDFLATEX the default is pdflatex and when in the later case latex is\n# chosen this is overwritten by pdflatex. For specific output languages the\n# default can have been set differently, this depends on the implementation of\n# the output language.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_CMD_NAME         = latex\n\n# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate\n# index for LaTeX.\n# Note: This tag is used in the Makefile / make.bat.\n# See also: LATEX_MAKEINDEX_CMD for the part in the generated output file\n# (.tex).\n# The default file is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nMAKEINDEX_CMD_NAME     = makeindex\n\n# The LATEX_MAKEINDEX_CMD tag can be used to specify the command name to\n# generate index for LaTeX. In case there is no backslash (\\) as first character\n# it will be automatically added in the LaTeX code.\n# Note: This tag is used in the generated output file (.tex).\n# See also: MAKEINDEX_CMD_NAME for the part in the Makefile / make.bat.\n# The default value is: makeindex.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_MAKEINDEX_CMD    = makeindex\n\n# If the COMPACT_LATEX tag is set to YES, Doxygen generates more compact LaTeX\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nCOMPACT_LATEX          = NO\n\n# The PAPER_TYPE tag can be used to set the paper type that is used by the\n# printer.\n# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x\n# 14 inches) and executive (7.25 x 10.5 inches).\n# The default value is: a4.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPAPER_TYPE             = a4\n\n# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names\n# that should be included in the LaTeX output. The package can be specified just\n# by its name or with the correct syntax as to be used with the LaTeX\n# \\usepackage command. To get the times font for instance you can specify :\n# EXTRA_PACKAGES=times or EXTRA_PACKAGES={times}\n# To use the option intlimits with the amsmath package you can specify:\n# EXTRA_PACKAGES=[intlimits]{amsmath}\n# If left blank no extra packages will be included.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nEXTRA_PACKAGES         =\n\n# The LATEX_HEADER tag can be used to specify a user-defined LaTeX header for\n# the generated LaTeX document. The header should contain everything until the\n# first chapter. If it is left blank Doxygen will generate a standard header. It\n# is highly recommended to start with a default header using\n# doxygen -w latex new_header.tex new_footer.tex new_stylesheet.sty\n# and then modify the file new_header.tex. See also section \"Doxygen usage\" for\n# information on how to generate the default header that Doxygen normally uses.\n#\n# Note: Only use a user-defined header if you know what you are doing!\n# Note: The header is subject to change so you typically have to regenerate the\n# default header when upgrading to a newer version of Doxygen. The following\n# commands have a special meaning inside the header (and footer): For a\n# description of the possible markers and block names see the documentation.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HEADER           =\n\n# The LATEX_FOOTER tag can be used to specify a user-defined LaTeX footer for\n# the generated LaTeX document. The footer should contain everything after the\n# last chapter. If it is left blank Doxygen will generate a standard footer. See\n# LATEX_HEADER for more information on how to generate a default footer and what\n# special commands can be used inside the footer. See also section \"Doxygen\n# usage\" for information on how to generate the default footer that Doxygen\n# normally uses. Note: Only use a user-defined footer if you know what you are\n# doing!\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_FOOTER           =\n\n# The LATEX_EXTRA_STYLESHEET tag can be used to specify additional user-defined\n# LaTeX style sheets that are included after the standard style sheets created\n# by Doxygen. Using this option one can overrule certain style aspects. Doxygen\n# will copy the style sheet files to the output directory.\n# Note: The order of the extra style sheet files is of importance (e.g. the last\n# style sheet in the list overrules the setting of the previous ones in the\n# list).\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_STYLESHEET =\n\n# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the LATEX_OUTPUT output\n# directory. Note that the files will be copied as-is; there are no commands or\n# markers available.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EXTRA_FILES      =\n\n# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is\n# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will\n# contain links (just like the HTML output) instead of page references. This\n# makes the output suitable for online browsing using a PDF viewer.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nPDF_HYPERLINKS         = YES\n\n# If the USE_PDFLATEX tag is set to YES, Doxygen will use the engine as\n# specified with LATEX_CMD_NAME to generate the PDF file directly from the LaTeX\n# files. Set this option to YES, to get a higher quality PDF documentation.\n#\n# See also section LATEX_CMD_NAME for selecting the engine.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nUSE_PDFLATEX           = YES\n\n# The LATEX_BATCHMODE tag signals the behavior of LaTeX in case of an error.\n# Possible values are: NO same as ERROR_STOP, YES same as BATCH, BATCH In batch\n# mode nothing is printed on the terminal, errors are scrolled as if <return> is\n# hit at every error; missing files that TeX tries to input or request from\n# keyboard input (\\read on a not open input stream) cause the job to abort,\n# NON_STOP In nonstop mode the diagnostic message will appear on the terminal,\n# but there is no possibility of user interaction just like in batch mode,\n# SCROLL In scroll mode, TeX will stop only for missing files to input or if\n# keyboard input is necessary and ERROR_STOP In errorstop mode, TeX will stop at\n# each error, asking for user intervention.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BATCHMODE        = NO\n\n# If the LATEX_HIDE_INDICES tag is set to YES then Doxygen will not include the\n# index chapters (such as File Index, Compound Index, etc.) in the output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_HIDE_INDICES     = NO\n\n# The LATEX_BIB_STYLE tag can be used to specify the style to use for the\n# bibliography, e.g. plainnat, or ieeetr. See\n# https://en.wikipedia.org/wiki/BibTeX and \\cite for more info.\n# The default value is: plainnat.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_BIB_STYLE        = plain\n\n# The LATEX_EMOJI_DIRECTORY tag is used to specify the (relative or absolute)\n# path from which the emoji images will be read. If a relative path is entered,\n# it will be relative to the LATEX_OUTPUT directory. If left blank the\n# LATEX_OUTPUT directory will be used.\n# This tag requires that the tag GENERATE_LATEX is set to YES.\n\nLATEX_EMOJI_DIRECTORY  =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the RTF output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_RTF tag is set to YES, Doxygen will generate RTF output. The\n# RTF output is optimized for Word 97 and may not look too pretty with other RTF\n# readers/editors.\n# The default value is: NO.\n\nGENERATE_RTF           = NO\n\n# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: rtf.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_OUTPUT             = rtf\n\n# If the COMPACT_RTF tag is set to YES, Doxygen generates more compact RTF\n# documents. This may be useful for small projects and may help to save some\n# trees in general.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nCOMPACT_RTF            = NO\n\n# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will\n# contain hyperlink fields. The RTF file will contain links (just like the HTML\n# output) instead of page references. This makes the output suitable for online\n# browsing using Word or some other Word compatible readers that support those\n# fields.\n#\n# Note: WordPad (write) and others do not support links.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_HYPERLINKS         = NO\n\n# Load stylesheet definitions from file. Syntax is similar to Doxygen's\n# configuration file, i.e. a series of assignments. You only have to provide\n# replacements, missing definitions are set to their default value.\n#\n# See also section \"Doxygen usage\" for information on how to generate the\n# default style sheet that Doxygen normally uses.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_STYLESHEET_FILE    =\n\n# Set optional variables used in the generation of an RTF document. Syntax is\n# similar to Doxygen's configuration file. A template extensions file can be\n# generated using doxygen -e rtf extensionFile.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_EXTENSIONS_FILE    =\n\n# The RTF_EXTRA_FILES tag can be used to specify one or more extra images or\n# other source files which should be copied to the RTF_OUTPUT output directory.\n# Note that the files will be copied as-is; there are no commands or markers\n# available.\n# This tag requires that the tag GENERATE_RTF is set to YES.\n\nRTF_EXTRA_FILES        =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the man page output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_MAN tag is set to YES, Doxygen will generate man pages for\n# classes and files.\n# The default value is: NO.\n\nGENERATE_MAN           = NO\n\n# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it. A directory man3 will be created inside the directory specified by\n# MAN_OUTPUT.\n# The default directory is: man.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_OUTPUT             = man\n\n# The MAN_EXTENSION tag determines the extension that is added to the generated\n# man pages. In case the manual section does not start with a number, the number\n# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is\n# optional.\n# The default value is: .3.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_EXTENSION          = .3\n\n# The MAN_SUBDIR tag determines the name of the directory created within\n# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by\n# MAN_EXTENSION with the initial . removed.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_SUBDIR             =\n\n# If the MAN_LINKS tag is set to YES and Doxygen generates man output, then it\n# will generate one additional man file for each entity documented in the real\n# man page(s). These additional files only source the real man page, but without\n# them the man command would be unable to find the correct page.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_MAN is set to YES.\n\nMAN_LINKS              = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the XML output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_XML tag is set to YES, Doxygen will generate an XML file that\n# captures the structure of the code including all documentation.\n# The default value is: NO.\n\nGENERATE_XML           = NO\n\n# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a\n# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of\n# it.\n# The default directory is: xml.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_OUTPUT             = xml\n\n# If the XML_PROGRAMLISTING tag is set to YES, Doxygen will dump the program\n# listings (including syntax highlighting and cross-referencing information) to\n# the XML output. Note that enabling this will significantly increase the size\n# of the XML output.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_PROGRAMLISTING     = YES\n\n# If the XML_NS_MEMB_FILE_SCOPE tag is set to YES, Doxygen will include\n# namespace members in file scope as well, matching the HTML output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_XML is set to YES.\n\nXML_NS_MEMB_FILE_SCOPE = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to the DOCBOOK output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_DOCBOOK tag is set to YES, Doxygen will generate Docbook files\n# that can be used to generate PDF.\n# The default value is: NO.\n\nGENERATE_DOCBOOK       = NO\n\n# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.\n# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in\n# front of it.\n# The default directory is: docbook.\n# This tag requires that the tag GENERATE_DOCBOOK is set to YES.\n\nDOCBOOK_OUTPUT         = docbook\n\n#---------------------------------------------------------------------------\n# Configuration options for the AutoGen Definitions output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_AUTOGEN_DEF tag is set to YES, Doxygen will generate an\n# AutoGen Definitions (see https://autogen.sourceforge.net/) file that captures\n# the structure of the code including all documentation. Note that this feature\n# is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_AUTOGEN_DEF   = NO\n\n#---------------------------------------------------------------------------\n# Configuration options related to Sqlite3 output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_SQLITE3 tag is set to YES Doxygen will generate a Sqlite3\n# database with symbols found by Doxygen stored in tables.\n# The default value is: NO.\n\nGENERATE_SQLITE3       = NO\n\n# The SQLITE3_OUTPUT tag is used to specify where the Sqlite3 database will be\n# put. If a relative path is entered the value of OUTPUT_DIRECTORY will be put\n# in front of it.\n# The default directory is: sqlite3.\n# This tag requires that the tag GENERATE_SQLITE3 is set to YES.\n\nSQLITE3_OUTPUT         = sqlite3\n\n# The SQLITE3_RECREATE_DB tag is set to YES, the existing doxygen_sqlite3.db\n# database file will be recreated with each Doxygen run. If set to NO, Doxygen\n# will warn if a database file is already found and not modify it.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_SQLITE3 is set to YES.\n\nSQLITE3_RECREATE_DB    = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to the Perl module output\n#---------------------------------------------------------------------------\n\n# If the GENERATE_PERLMOD tag is set to YES, Doxygen will generate a Perl module\n# file that captures the structure of the code including all documentation.\n#\n# Note that this feature is still experimental and incomplete at the moment.\n# The default value is: NO.\n\nGENERATE_PERLMOD       = NO\n\n# If the PERLMOD_LATEX tag is set to YES, Doxygen will generate the necessary\n# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI\n# output from the Perl module output.\n# The default value is: NO.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_LATEX          = NO\n\n# If the PERLMOD_PRETTY tag is set to YES, the Perl module output will be nicely\n# formatted so it can be parsed by a human reader. This is useful if you want to\n# understand what is going on. On the other hand, if this tag is set to NO, the\n# size of the Perl module output will be much smaller and Perl will parse it\n# just the same.\n# The default value is: YES.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_PRETTY         = YES\n\n# The names of the make variables in the generated doxyrules.make file are\n# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful\n# so different doxyrules.make files included by the same Makefile don't\n# overwrite each other's variables.\n# This tag requires that the tag GENERATE_PERLMOD is set to YES.\n\nPERLMOD_MAKEVAR_PREFIX =\n\n#---------------------------------------------------------------------------\n# Configuration options related to the preprocessor\n#---------------------------------------------------------------------------\n\n# If the ENABLE_PREPROCESSING tag is set to YES, Doxygen will evaluate all\n# C-preprocessor directives found in the sources and include files.\n# The default value is: YES.\n\nENABLE_PREPROCESSING   = YES\n\n# If the MACRO_EXPANSION tag is set to YES, Doxygen will expand all macro names\n# in the source code. If set to NO, only conditional compilation will be\n# performed. Macro expansion can be done in a controlled way by setting\n# EXPAND_ONLY_PREDEF to YES.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nMACRO_EXPANSION        = YES\n\n# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then\n# the macro expansion is limited to the macros specified with the PREDEFINED and\n# EXPAND_AS_DEFINED tags.\n# The default value is: NO.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_ONLY_PREDEF     = YES\n\n# If the SEARCH_INCLUDES tag is set to YES, the include files in the\n# INCLUDE_PATH will be searched if a #include is found.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSEARCH_INCLUDES        = YES\n\n# The INCLUDE_PATH tag can be used to specify one or more directories that\n# contain include files that are not input files but should be processed by the\n# preprocessor. Note that the INCLUDE_PATH is not recursive, so the setting of\n# RECURSIVE has no effect here.\n# This tag requires that the tag SEARCH_INCLUDES is set to YES.\n\nINCLUDE_PATH           =\n\n# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard\n# patterns (like *.h and *.hpp) to filter out the header-files in the\n# directories. If left blank, the patterns specified with FILE_PATTERNS will be\n# used.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nINCLUDE_FILE_PATTERNS  =\n\n# The PREDEFINED tag can be used to specify one or more macro names that are\n# defined before the preprocessor is started (similar to the -D option of e.g.\n# gcc). The argument of the tag is a list of macros of the form: name or\n# name=definition (no spaces). If the definition and the \"=\" are omitted, \"=1\"\n# is assumed. To prevent a macro definition from being undefined via #undef or\n# recursively expanded use the := operator instead of the = operator.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nPREDEFINED             = VA_START(f)= \\\n                         \"VA_SHIFT(v,t)=\" \\\n                         \"MIN(p,q)=\" \\\n                         \"MAX(p,q)=\" \\\n                         char_to_int(p)= \\\n                         GET_32BIT_LSB_FIRST(cp)= \\\n                         \"PUT_32BIT_LSB_FIRST(cp, value)=\" \\\n                         \"F1(x,y,z)=\" \\\n                         \"F2(x,y,z)=\" \\\n                         \"F3(x,y,z)=\" \\\n                         \"F4(x,y,z)=\" \\\n                         \"MD5STEP(f,w,x,y,z,data,s)=\" \\\n                         \"rol(value,bits)=\" \\\n                         blk0(i)= \\\n                         blk(i)= \\\n                         \"R0(v,w,x,y,z,i)=\" \\\n                         \"R1(v,w,x,y,z,i)=\" \\\n                         \"R2(v,w,x,y,z,i)=\" \\\n                         \"R3(v,w,x,y,z,i)=\" \\\n                         \"R4(v,w,x,y,z,i)=\"\n\n# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this\n# tag can be used to specify a list of macro names that should be expanded. The\n# macro definition that is found in the sources will be used. Use the PREDEFINED\n# tag if you want to use a different macro definition that overrules the\n# definition found in the source code.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nEXPAND_AS_DEFINED      =\n\n# If the SKIP_FUNCTION_MACROS tag is set to YES then Doxygen's preprocessor will\n# remove all references to function-like macros that are alone on a line, have\n# an all uppercase name, and do not end with a semicolon. Such function macros\n# are typically used for boiler-plate code, and will confuse the parser if not\n# removed.\n# The default value is: YES.\n# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.\n\nSKIP_FUNCTION_MACROS   = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to external references\n#---------------------------------------------------------------------------\n\n# The TAGFILES tag can be used to specify one or more tag files. For each tag\n# file the location of the external documentation should be added. The format of\n# a tag file without this location is as follows:\n# TAGFILES = file1 file2 ...\n# Adding location for the tag files is done as follows:\n# TAGFILES = file1=loc1 \"file2 = loc2\" ...\n# where loc1 and loc2 can be relative or absolute paths or URLs. See the\n# section \"Linking to external documentation\" for more information about the use\n# of tag files.\n# Note: Each tag file must have a unique name (where the name does NOT include\n# the path). If a tag file is not located in the directory in which Doxygen is\n# run, you must also specify the path to the tagfile here.\n\nTAGFILES               =\n\n# When a file name is specified after GENERATE_TAGFILE, Doxygen will create a\n# tag file that is based on the input files it reads. See section \"Linking to\n# external documentation\" for more information about the usage of tag files.\n\nGENERATE_TAGFILE       =\n\n# If the ALLEXTERNALS tag is set to YES, all external classes and namespaces\n# will be listed in the class and namespace index. If set to NO, only the\n# inherited external classes will be listed.\n# The default value is: NO.\n\nALLEXTERNALS           = NO\n\n# If the EXTERNAL_GROUPS tag is set to YES, all external groups will be listed\n# in the topic index. If set to NO, only the current project's groups will be\n# listed.\n# The default value is: YES.\n\nEXTERNAL_GROUPS        = YES\n\n# If the EXTERNAL_PAGES tag is set to YES, all external pages will be listed in\n# the related pages index. If set to NO, only the current project's pages will\n# be listed.\n# The default value is: YES.\n\nEXTERNAL_PAGES         = YES\n\n#---------------------------------------------------------------------------\n# Configuration options related to diagram generator tools\n#---------------------------------------------------------------------------\n\n# If set to YES the inheritance and collaboration graphs will hide inheritance\n# and usage relations if the target is undocumented or is not a class.\n# The default value is: YES.\n\nHIDE_UNDOC_RELATIONS   = YES\n\n# If you set the HAVE_DOT tag to YES then Doxygen will assume the dot tool is\n# available from the path. This tool is part of Graphviz (see:\n# https://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent\n# Bell Labs. The other options in this section have no effect if this option is\n# set to NO\n# The default value is: NO.\n\nHAVE_DOT               = NO\n\n# The DOT_NUM_THREADS specifies the number of dot invocations Doxygen is allowed\n# to run in parallel. When set to 0 Doxygen will base this on the number of\n# processors available in the system. You can set it explicitly to a value\n# larger than 0 to get control over the balance between CPU load and processing\n# speed.\n# Minimum value: 0, maximum value: 512, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_NUM_THREADS        = 0\n\n# DOT_COMMON_ATTR is common attributes for nodes, edges and labels of\n# subgraphs. When you want a differently looking font in the dot files that\n# Doxygen generates you can specify fontname, fontcolor and fontsize attributes.\n# For details please see <a href=https://graphviz.org/doc/info/attrs.html>Node,\n# Edge and Graph Attributes specification</a> You need to make sure dot is able\n# to find the font, which can be done by putting it in a standard location or by\n# setting the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the\n# directory containing the font. Default graphviz fontsize is 14.\n# The default value is: fontname=Helvetica,fontsize=10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_COMMON_ATTR        = \"fontname=Helvetica,fontsize=10\"\n\n# DOT_EDGE_ATTR is concatenated with DOT_COMMON_ATTR. For elegant style you can\n# add 'arrowhead=open, arrowtail=open, arrowsize=0.5'. <a\n# href=https://graphviz.org/doc/info/arrows.html>Complete documentation about\n# arrows shapes.</a>\n# The default value is: labelfontname=Helvetica,labelfontsize=10.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_EDGE_ATTR          = \"labelfontname=Helvetica,labelfontsize=10\"\n\n# DOT_NODE_ATTR is concatenated with DOT_COMMON_ATTR. For view without boxes\n# around nodes set 'shape=plain' or 'shape=plaintext' <a\n# href=https://www.graphviz.org/doc/info/shapes.html>Shapes specification</a>\n# The default value is: shape=box,height=0.2,width=0.4.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_NODE_ATTR          = \"shape=box,height=0.2,width=0.4\"\n\n# You can set the path where dot can find font specified with fontname in\n# DOT_COMMON_ATTR and others dot attributes.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_FONTPATH           =\n\n# If the CLASS_GRAPH tag is set to YES or GRAPH or BUILTIN then Doxygen will\n# generate a graph for each documented class showing the direct and indirect\n# inheritance relations. In case the CLASS_GRAPH tag is set to YES or GRAPH and\n# HAVE_DOT is enabled as well, then dot will be used to draw the graph. In case\n# the CLASS_GRAPH tag is set to YES and HAVE_DOT is disabled or if the\n# CLASS_GRAPH tag is set to BUILTIN, then the built-in generator will be used.\n# If the CLASS_GRAPH tag is set to TEXT the direct and indirect inheritance\n# relations will be shown as texts / links. Explicit enabling an inheritance\n# graph or choosing a different representation for an inheritance graph of a\n# specific class, can be accomplished by means of the command \\inheritancegraph.\n# Disabling an inheritance graph can be accomplished by means of the command\n# \\hideinheritancegraph.\n# Possible values are: NO, YES, TEXT, GRAPH and BUILTIN.\n# The default value is: YES.\n\nCLASS_GRAPH            = TEXT\n\n# If the COLLABORATION_GRAPH tag is set to YES then Doxygen will generate a\n# graph for each documented class showing the direct and indirect implementation\n# dependencies (inheritance, containment, and class references variables) of the\n# class with other documented classes. Explicit enabling a collaboration graph,\n# when COLLABORATION_GRAPH is set to NO, can be accomplished by means of the\n# command \\collaborationgraph. Disabling a collaboration graph can be\n# accomplished by means of the command \\hidecollaborationgraph.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCOLLABORATION_GRAPH    = YES\n\n# If the GROUP_GRAPHS tag is set to YES then Doxygen will generate a graph for\n# groups, showing the direct groups dependencies. Explicit enabling a group\n# dependency graph, when GROUP_GRAPHS is set to NO, can be accomplished by means\n# of the command \\groupgraph. Disabling a directory graph can be accomplished by\n# means of the command \\hidegroupgraph. See also the chapter Grouping in the\n# manual.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGROUP_GRAPHS           = YES\n\n# If the UML_LOOK tag is set to YES, Doxygen will generate inheritance and\n# collaboration diagrams in a style similar to the OMG's Unified Modeling\n# Language.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nUML_LOOK               = NO\n\n# If the UML_LOOK tag is enabled, the fields and methods are shown inside the\n# class node. If there are many fields or methods and many nodes the graph may\n# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the\n# number of items for each type to make the size more manageable. Set this to 0\n# for no limit. Note that the threshold may be exceeded by 50% before the limit\n# is enforced. So when you set the threshold to 10, up to 15 fields may appear,\n# but if the number exceeds 15, the total amount of fields shown is limited to\n# 10.\n# Minimum value: 0, maximum value: 100, default value: 10.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nUML_LIMIT_NUM_FIELDS   = 10\n\n# If the UML_LOOK tag is enabled, field labels are shown along the edge between\n# two class nodes. If there are many fields and many nodes the graph may become\n# too cluttered. The UML_MAX_EDGE_LABELS threshold limits the number of items to\n# make the size more manageable. Set this to 0 for no limit.\n# Minimum value: 0, maximum value: 100, default value: 10.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nUML_MAX_EDGE_LABELS    = 10\n\n# If the DOT_UML_DETAILS tag is set to NO, Doxygen will show attributes and\n# methods without types and arguments in the UML graphs. If the DOT_UML_DETAILS\n# tag is set to YES, Doxygen will add type and arguments for attributes and\n# methods in the UML graphs. If the DOT_UML_DETAILS tag is set to NONE, Doxygen\n# will not generate fields with class member information in the UML graphs. The\n# class diagrams will look similar to the default class diagrams but using UML\n# notation for the relationships.\n# Possible values are: NO, YES and NONE.\n# The default value is: NO.\n# This tag requires that the tag UML_LOOK is set to YES.\n\nDOT_UML_DETAILS        = NO\n\n# The DOT_WRAP_THRESHOLD tag can be used to set the maximum number of characters\n# to display on a single line. If the actual line length exceeds this threshold\n# significantly it will be wrapped across multiple lines. Some heuristics are\n# applied to avoid ugly line breaks.\n# Minimum value: 0, maximum value: 1000, default value: 17.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_WRAP_THRESHOLD     = 17\n\n# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and\n# collaboration graphs will show the relations between templates and their\n# instances.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nTEMPLATE_RELATIONS     = NO\n\n# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to\n# YES then Doxygen will generate a graph for each documented file showing the\n# direct and indirect include dependencies of the file with other documented\n# files. Explicit enabling an include graph, when INCLUDE_GRAPH is is set to NO,\n# can be accomplished by means of the command \\includegraph. Disabling an\n# include graph can be accomplished by means of the command \\hideincludegraph.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDE_GRAPH          = YES\n\n# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are\n# set to YES then Doxygen will generate a graph for each documented file showing\n# the direct and indirect include dependencies of the file with other documented\n# files. Explicit enabling an included by graph, when INCLUDED_BY_GRAPH is set\n# to NO, can be accomplished by means of the command \\includedbygraph. Disabling\n# an included by graph can be accomplished by means of the command\n# \\hideincludedbygraph.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINCLUDED_BY_GRAPH      = YES\n\n# If the CALL_GRAPH tag is set to YES then Doxygen will generate a call\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable call graphs for selected\n# functions only using the \\callgraph command. Disabling a call graph can be\n# accomplished by means of the command \\hidecallgraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALL_GRAPH             = NO\n\n# If the CALLER_GRAPH tag is set to YES then Doxygen will generate a caller\n# dependency graph for every global function or class method.\n#\n# Note that enabling this option will significantly increase the time of a run.\n# So in most cases it will be better to enable caller graphs for selected\n# functions only using the \\callergraph command. Disabling a caller graph can be\n# accomplished by means of the command \\hidecallergraph.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nCALLER_GRAPH           = NO\n\n# If the GRAPHICAL_HIERARCHY tag is set to YES then Doxygen will graphical\n# hierarchy of all classes instead of a textual one.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGRAPHICAL_HIERARCHY    = YES\n\n# If the DIRECTORY_GRAPH tag is set to YES then Doxygen will show the\n# dependencies a directory has on other directories in a graphical way. The\n# dependency relations are determined by the #include relations between the\n# files in the directories. Explicit enabling a directory graph, when\n# DIRECTORY_GRAPH is set to NO, can be accomplished by means of the command\n# \\directorygraph. Disabling a directory graph can be accomplished by means of\n# the command \\hidedirectorygraph.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDIRECTORY_GRAPH        = YES\n\n# The DIR_GRAPH_MAX_DEPTH tag can be used to limit the maximum number of levels\n# of child directories generated in directory dependency graphs by dot.\n# Minimum value: 1, maximum value: 25, default value: 1.\n# This tag requires that the tag DIRECTORY_GRAPH is set to YES.\n\nDIR_GRAPH_MAX_DEPTH    = 1\n\n# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images\n# generated by dot. For an explanation of the image formats see the section\n# output formats in the documentation of the dot tool (Graphviz (see:\n# https://www.graphviz.org/)).\n#\n# Note the formats svg:cairo and svg:cairo:cairo cannot be used in combination\n# with INTERACTIVE_SVG (the INTERACTIVE_SVG will be set to NO).\n# Possible values are: png, jpg, gif, svg, png:gd, png:gd:gd, png:cairo,\n# png:cairo:gd, png:cairo:cairo, png:cairo:gdiplus, png:gdiplus,\n# png:gdiplus:gdiplus, svg:cairo, svg:cairo:cairo, svg:svg, svg:svg:core,\n# gif:cairo, gif:cairo:gd, gif:cairo:gdiplus, gif:gdiplus, gif:gdiplus:gdiplus,\n# gif:gd, gif:gd:gd, jpg:cairo, jpg:cairo:gd, jpg:cairo:gdiplus, jpg:gd,\n# jpg:gd:gd, jpg:gdiplus and jpg:gdiplus:gdiplus.\n# The default value is: png.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_IMAGE_FORMAT       = png\n\n# If DOT_IMAGE_FORMAT is set to svg or svg:svg or svg:svg:core, then this option\n# can be set to YES to enable generation of interactive SVG images that allow\n# zooming and panning.\n#\n# Note that this requires a modern browser other than Internet Explorer. Tested\n# and working are Firefox, Chrome, Safari, and Opera.\n#\n# Note This option will be automatically disabled when DOT_IMAGE_FORMAT is set\n# to svg:cairo or svg:cairo:cairo.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nINTERACTIVE_SVG        = NO\n\n# The DOT_PATH tag can be used to specify the path where the dot tool can be\n# found. If left blank, it is assumed the dot tool can be found in the path.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_PATH               =\n\n# The DOTFILE_DIRS tag can be used to specify one or more directories that\n# contain dot files that are included in the documentation (see the \\dotfile\n# command).\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOTFILE_DIRS           =\n\n# You can include diagrams made with dia in Doxygen documentation. Doxygen will\n# then run dia to produce the diagram and insert it in the documentation. The\n# DIA_PATH tag allows you to specify the directory where the dia binary resides.\n# If left empty dia is assumed to be found in the default search path.\n\nDIA_PATH               =\n\n# The DIAFILE_DIRS tag can be used to specify one or more directories that\n# contain dia files that are included in the documentation (see the \\diafile\n# command).\n\nDIAFILE_DIRS           =\n\n# When using PlantUML, the PLANTUML_JAR_PATH tag should be used to specify the\n# path where java can find the plantuml.jar file or to the filename of jar file\n# to be used. If left blank, it is assumed PlantUML is not used or called during\n# a preprocessing step. Doxygen will generate a warning when it encounters a\n# \\startuml command in this case and will not generate output for the diagram.\n\nPLANTUML_JAR_PATH      =\n\n# When using PlantUML, the PLANTUML_CFG_FILE tag can be used to specify a\n# configuration file for PlantUML.\n\nPLANTUML_CFG_FILE      =\n\n# When using PlantUML, the specified paths are searched for files specified by\n# the !include statement in a PlantUML block.\n\nPLANTUML_INCLUDE_PATH  =\n\n# The PLANTUMLFILE_DIRS tag can be used to specify one or more directories that\n# contain PlantUml files that are included in the documentation (see the\n# \\plantumlfile command).\n\nPLANTUMLFILE_DIRS      =\n\n# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes\n# that will be shown in the graph. If the number of nodes in a graph becomes\n# larger than this value, Doxygen will truncate the graph, which is visualized\n# by representing a node as a red box. Note that if the number of direct\n# children of the root node in a graph is already larger than\n# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that\n# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.\n# Minimum value: 0, maximum value: 10000, default value: 50.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_GRAPH_MAX_NODES    = 50\n\n# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs\n# generated by dot. A depth value of 3 means that only nodes reachable from the\n# root by following a path via at most 3 edges will be shown. Nodes that lay\n# further from the root node will be omitted. Note that setting this option to 1\n# or 2 may greatly reduce the computation time needed for large code bases. Also\n# note that the size of a graph can be further restricted by\n# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.\n# Minimum value: 0, maximum value: 1000, default value: 0.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nMAX_DOT_GRAPH_DEPTH    = 1000\n\n# Set the DOT_MULTI_TARGETS tag to YES to allow dot to generate multiple output\n# files in one run (i.e. multiple -o and -T options on the command line). This\n# makes dot run faster, but since only newer versions of dot (>1.8.10) support\n# this, this feature is disabled by default.\n# The default value is: NO.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nDOT_MULTI_TARGETS      = NO\n\n# If the GENERATE_LEGEND tag is set to YES Doxygen will generate a legend page\n# explaining the meaning of the various boxes and arrows in the dot generated\n# graphs.\n# Note: This tag requires that UML_LOOK isn't set, i.e. the Doxygen internal\n# graphical representation for inheritance and collaboration diagrams is used.\n# The default value is: YES.\n# This tag requires that the tag HAVE_DOT is set to YES.\n\nGENERATE_LEGEND        = YES\n\n# If the DOT_CLEANUP tag is set to YES, Doxygen will remove the intermediate\n# files that are used to generate the various graphs.\n#\n# Note: This setting is not only used for dot files but also for msc temporary\n# files.\n# The default value is: YES.\n\nDOT_CLEANUP            = YES\n\n# You can define message sequence charts within Doxygen comments using the \\msc\n# command. If the MSCGEN_TOOL tag is left empty (the default), then Doxygen will\n# use a built-in version of mscgen tool to produce the charts. Alternatively,\n# the MSCGEN_TOOL tag can also specify the name an external tool. For instance,\n# specifying prog as the value, Doxygen will call the tool as prog -T\n# <outfile_format> -o <outputfile> <inputfile>. The external tool should support\n# output file formats \"png\", \"eps\", \"svg\", and \"ismap\".\n\nMSCGEN_TOOL            =\n\n# The MSCFILE_DIRS tag can be used to specify one or more directories that\n# contain msc files that are included in the documentation (see the \\mscfile\n# command).\n\nMSCFILE_DIRS           =\n"
  },
  {
    "path": "GPL-LICENSE.txt",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "libstrophe XMPP client library\nCopyright (C) 2005-2009 Collecta, Inc.\n\nThis program is dual licensed under the MIT or GPLv3 licenses.\nPlease the files MIT-LICENSE.txt and GPL-LICENSE.txt for details.\n"
  },
  {
    "path": "MIT-LICENSE.txt",
    "content": "Copyright (c) 2005-2009 Collecta, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "Makefile.am",
    "content": "AUTOMAKE_OPTIONS = subdir-objects\n\nACLOCAL_AMFLAGS = -I m4\n\nCOVERAGE_CFLAGS=@COVERAGE_CFLAGS@\nCOVERAGE_LDFLAGS=@COVERAGE_LDFLAGS@\nCOVERAGE_PRE=@COVERAGE_PRE@\nCOVERAGE_POST=@COVERAGE_POST@\n\nPARSER_CFLAGS=@PARSER_CFLAGS@\nPARSER_LIBS=@PARSER_LIBS@\n\nZLIB_CFLAGS=@ZLIB_CFLAGS@\nZLIB_LIBS=@ZLIB_LIBS@\n\nif TLS_WITH_GNUTLS\nSSL_CFLAGS = @gnutls_CFLAGS@\nSSL_LIBS = @gnutls_LIBS@\nelse\nif !TLS_WITH_SCHANNEL\nSSL_CFLAGS = @openssl_CFLAGS@\nSSL_LIBS = @openssl_LIBS@\nendif\nendif\n\nMINGW_LIBS = @MINGW_LIBS@\n\nRESOLV_CFLAGS = @RESOLV_CFLAGS@\nRESOLV_LIBS = @RESOLV_LIBS@\n\nWARNING_FLAGS = @WARNING_FLAGS@\nSTROPHE_FLAGS = -I$(top_srcdir) $(WARNING_FLAGS)\nSTROPHE_LIBS = $(COVERAGE_PRE) libstrophe.la $(COVERAGE_POST) $(COVERAGE_LDFLAGS)\n\n## Main build targets\nlib_LTLIBRARIES = libstrophe.la\n\nlibstrophe_la_CFLAGS = $(SSL_CFLAGS) $(STROPHE_FLAGS) $(PARSER_CFLAGS) $(RESOLV_CFLAGS) $(COVERAGE_CFLAGS) $(ZLIB_CFLAGS)\nlibstrophe_la_LDFLAGS = $(SSL_LIBS) $(PARSER_LIBS) $(RESOLV_LIBS) $(MINGW_LIBS) $(ZLIB_LIBS) -no-undefined\n# Export only public API\nlibstrophe_la_LDFLAGS += -export-symbols-regex '^xmpp_' -version-info @VERSION_INFO@\n\nlibstrophe_la_SOURCES = \\\n\tsrc/auth.c \\\n\tsrc/conn.c \\\n\tsrc/crypto.c \\\n\tsrc/ctx.c \\\n\tsrc/deprecated.c \\\n\tsrc/event.c \\\n\tsrc/handler.c \\\n\tsrc/hash.c \\\n\tsrc/jid.c \\\n\tsrc/md5.c \\\n\tsrc/rand.c \\\n\tsrc/resolver.c \\\n\tsrc/sasl.c \\\n\tsrc/scram.c \\\n\tsrc/sha1.c \\\n\tsrc/sha256.c \\\n\tsrc/sha512.c \\\n\tsrc/sock.c \\\n\tsrc/stanza.c \\\n\tsrc/tls.c \\\n\tsrc/util.c \\\n\tsrc/uuid.c\nlibstrophe_la_SOURCES += \\\n\tsrc/common.h \\\n\tsrc/hash.h \\\n\tsrc/md5.h \\\n\tsrc/ostypes.h \\\n\tsrc/parser.h \\\n\tsrc/resolver.h \\\n\tsrc/sasl.h \\\n\tsrc/scram.h \\\n\tsrc/sha.h \\\n\tsrc/sha1.h \\\n\tsrc/sha256.h \\\n\tsrc/sha512.h \\\n\tsrc/snprintf.h \\\n\tsrc/sock.h \\\n\tsrc/tls.h \\\n\tsrc/util.h\n\nif NEED_SNPRINTF\nlibstrophe_la_SOURCES += src/snprintf.c\nendif\n\nif DISABLE_COMPRESSION\nlibstrophe_la_SOURCES += src/compression_dummy.c\nelse\nlibstrophe_la_SOURCES += src/compression.c\nendif\n\nif DISABLE_TLS\nlibstrophe_la_SOURCES += src/tls_dummy.c\nelse\nif TLS_WITH_GNUTLS\nlibstrophe_la_SOURCES += src/tls_gnutls.c\nelse\nif TLS_WITH_SCHANNEL\nlibstrophe_la_SOURCES += src/tls_schannel.c\nelse\nlibstrophe_la_SOURCES += src/tls_openssl.c\nendif\nendif\nendif\n\nif PARSER_EXPAT\nlibstrophe_la_SOURCES += src/parser_expat.c\nelse\nlibstrophe_la_SOURCES += src/parser_libxml2.c\nendif\n\ninclude_HEADERS = strophe.h\n\npkgconfig_DATA = libstrophe.pc\n\nEXTRA_DIST = \\\n\t_clang-format \\\n\tDoxyfile \\\n\tGPL-LICENSE.txt \\\n\tLICENSE.txt \\\n\tMIT-LICENSE.txt \\\n\tbootstrap.sh \\\n\tbuild-android.sh \\\n\ttestbuild.sh \\\n\texamples/README.md \\\n\tjni/Android.mk \\\n\tjni/Application.mk \\\n\tm4/ax_valgrind_check.m4 \\\n\ttests/cert.pem \\\n\ttests/cert.pfx \\\n\ttests/cert.emptypass.pfx \\\n\ttests/cert.nopass.pfx \\\n\ttests/key.pem \\\n\ttests/key_encrypted.pem \\\n\ttests/res_query_dump.c\n\nif EXAMPLES\n## Examples\nnoinst_PROGRAMS = \\\n\texamples/active \\\n\texamples/basic \\\n\texamples/bot \\\n\texamples/complex \\\n\texamples/component \\\n\texamples/perf \\\n\texamples/register \\\n\texamples/roster \\\n\texamples/uuid \\\n\texamples/vcard\n\nexamples_active_SOURCES = examples/active.c\nexamples_active_CFLAGS = $(STROPHE_FLAGS)\nexamples_active_LDADD = $(STROPHE_LIBS)\nexamples_basic_SOURCES = examples/basic.c\nexamples_basic_CFLAGS = $(STROPHE_FLAGS)\nexamples_basic_LDADD = $(STROPHE_LIBS)\nexamples_bot_SOURCES = examples/bot.c\nexamples_bot_CFLAGS = $(STROPHE_FLAGS)\nexamples_bot_LDADD = $(STROPHE_LIBS)\nexamples_complex_SOURCES = examples/complex.c\nexamples_complex_CFLAGS = $(STROPHE_FLAGS)\nexamples_complex_LDADD = $(STROPHE_LIBS)\nexamples_component_SOURCES = examples/component.c\nexamples_component_CFLAGS = $(STROPHE_FLAGS)\nexamples_component_LDADD = $(STROPHE_LIBS)\nexamples_perf_SOURCES = examples/perf.c\nexamples_perf_CFLAGS = $(STROPHE_FLAGS)\nexamples_perf_LDADD = $(STROPHE_LIBS)\nexamples_register_SOURCES = examples/register.c\nexamples_register_CFLAGS = $(STROPHE_FLAGS)\nexamples_register_LDADD = $(STROPHE_LIBS)\nexamples_roster_SOURCES = examples/roster.c\nexamples_roster_CFLAGS = $(STROPHE_FLAGS)\nexamples_roster_LDADD = $(STROPHE_LIBS)\nexamples_uuid_SOURCES = examples/uuid.c\nexamples_uuid_CFLAGS = $(STROPHE_FLAGS)\nexamples_uuid_LDADD = $(STROPHE_LIBS)\nexamples_vcard_SOURCES = examples/vcard.c\nexamples_vcard_CFLAGS = $(STROPHE_FLAGS)\nexamples_vcard_LDADD = $(STROPHE_LIBS)\nendif\n\n\n## Tests\nSTATIC_TESTS = \\\n\ttests/check_parser \\\n\ttests/test_hash \\\n\ttests/test_jid \\\n\ttests/test_ctx \\\n\ttests/test_send_queue \\\n\ttests/test_serialize_sm \\\n\ttests/test_string \\\n\ttests/test_resolver\n\nTESTS = \\\n\ttests/test_sha1 \\\n\ttests/test_sha256 \\\n\ttests/test_sha512 \\\n\ttests/test_md5 \\\n\ttests/test_rand \\\n\ttests/test_scram \\\n\ttests/test_base64 \\\n\ttests/test_snprintf \\\n\ttests/test_stanza\n\nif !DISABLE_STATIC\nTESTS += $(STATIC_TESTS)\nendif\n\nif !DISABLE_TLS\nTESTS += tests/test_xmppaddr\nendif\n\ncheck_PROGRAMS = $(TESTS)\n\nif FUZZ\ncheck_PROGRAMS += tests/test_fuzz_parser tests/test_fuzz_resolver\n\ntests_test_fuzz_parser_SOURCES = tests/test_fuzz_parser.c\ntests_test_fuzz_parser_CFLAGS = -fsanitize=fuzzer,address  $(PARSER_CFLAGS) $(STROPHE_FLAGS) \\\n\t-I$(top_srcdir)/src\ntests_test_fuzz_parser_LDADD = $(STROPHE_LIBS)\ntests_test_fuzz_parser_LDFLAGS = -static\n\ntests_test_fuzz_resolver_SOURCES = tests/test_fuzz_resolver.c\ntests_test_fuzz_resolver_CFLAGS = -fsanitize=fuzzer,address  $(resolver_CFLAGS) $(STROPHE_FLAGS) \\\n\t-I$(top_srcdir)/src\ntests_test_fuzz_resolver_LDADD = $(STROPHE_LIBS)\ntests_test_fuzz_resolver_LDFLAGS = -static\nendif\n\ntests_check_parser_SOURCES = tests/check_parser.c tests/test.h\ntests_check_parser_CFLAGS = $(PARSER_CFLAGS) $(STROPHE_FLAGS) \\\n\t-I$(top_srcdir)/src\ntests_check_parser_LDADD = $(STROPHE_LIBS)\ntests_check_parser_LDFLAGS = -static\n\ntests_test_ctx_SOURCES = tests/test_ctx.c\ntests_test_ctx_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\ntests_test_ctx_LDADD = $(STROPHE_LIBS)\ntests_test_ctx_LDFLAGS = -static\n\ntests_test_base64_SOURCES = tests/test_base64.c tests/test.c tests/test.h\ntests_test_base64_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\ntests_test_base64_LDADD = $(STROPHE_LIBS)\ntests_test_base64_LDFLAGS = -static\n\ntests_test_hash_SOURCES = tests/test_hash.c\ntests_test_hash_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\ntests_test_hash_LDADD = $(STROPHE_LIBS)\ntests_test_hash_LDFLAGS = -static\n\ntests_test_jid_SOURCES = tests/test_jid.c\ntests_test_jid_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\ntests_test_jid_LDADD = $(STROPHE_LIBS)\ntests_test_jid_LDFLAGS = -static\n\ntests_test_resolver_SOURCES = tests/test_resolver.c tests/test.h\ntests_test_resolver_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\ntests_test_resolver_LDADD = $(STROPHE_LIBS)\ntests_test_resolver_LDFLAGS = -static\n\ntests_test_rand_SOURCES = tests/test_rand.c tests/test.c src/sha1.c\ntests_test_rand_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\n\ntests_test_scram_SOURCES = tests/test_scram.c tests/test.c src/sha1.c \\\n\tsrc/sha256.c src/sha512.c\ntests_test_scram_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\n\ntests_test_sha1_SOURCES = tests/test_sha1.c src/sha1.c\ntests_test_sha1_CFLAGS = -I$(top_srcdir)/src\n\ntests_test_sha256_SOURCES = tests/test_sha256.c tests/test.c src/sha256.c\ntests_test_sha256_CFLAGS = -I$(top_srcdir)/src\n\ntests_test_sha512_SOURCES = tests/test_sha512.c tests/test.c src/sha512.c\ntests_test_sha512_CFLAGS = -I$(top_srcdir)/src\n\ntests_test_md5_SOURCES = tests/test_md5.c tests/test.c src/md5.c\ntests_test_md5_CFLAGS = -I$(top_srcdir)/src\n\ntests_test_send_queue_SOURCES = tests/test_send_queue.c\ntests_test_send_queue_CFLAGS = -I$(top_srcdir)/src\ntests_test_send_queue_LDADD = $(STROPHE_LIBS)\ntests_test_send_queue_LDFLAGS = -static\n\ntests_test_serialize_sm_SOURCES = tests/test_serialize_sm.c tests/test.c tests/test.h\ntests_test_serialize_sm_CFLAGS = -I$(top_srcdir)/src\ntests_test_serialize_sm_LDADD = $(STROPHE_LIBS)\ntests_test_serialize_sm_LDFLAGS = -static\n\ntests_test_snprintf_SOURCES = tests/test_snprintf.c\ntests_test_snprintf_CFLAGS = -I$(top_srcdir)/src\n\ntests_test_string_SOURCES = tests/test_string.c tests/test.h\ntests_test_string_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\ntests_test_string_LDADD = $(STROPHE_LIBS)\ntests_test_string_LDFLAGS = -static\n\ntests_test_stanza_SOURCES = tests/test_stanza.c tests/test.h\ntests_test_stanza_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\ntests_test_stanza_LDADD = $(STROPHE_LIBS)\ntests_test_stanza_LDFLAGS = -static\n\ntests_test_xmppaddr_SOURCES = tests/test_xmppaddr.c\ntests_test_xmppaddr_CFLAGS = $(STROPHE_FLAGS) -I$(top_srcdir)/src\ntests_test_xmppaddr_LDADD = $(STROPHE_LIBS)\ntests_test_xmppaddr_LDFLAGS = -static\n\nformat:\n\t@echo \"   * run clang-format on all sources\"\n\t@dos2unix -k -q $(top_srcdir)/src/*.[ch] $(top_srcdir)/*.h $(top_srcdir)/tests/*.[ch] $(top_srcdir)/examples/*.c\n\t@clang-format -i $(top_srcdir)/src/*.[ch] $(top_srcdir)/*.h $(top_srcdir)/tests/*.[ch] $(top_srcdir)/examples/*.c\n\nif COVERAGE\nMOSTLYCLEANFILES = src/*.gcno src/*.gcda coverage.info\nclean-local:\n\t-rm -rf coverage/\n\ncoverage: check\n\t@lcov --capture --no-external --directory src -q --output-file coverage.info\n\t@genhtml coverage.info --output-directory coverage -q\nendif\n\nrelease: test-release-all\n\ndist-archives:\n\t$(MAKE) dist\n\t$(MAKE) dist-bzip2\n\t$(MAKE) dist-xz\n\ntest-release: dist\n\t@touch testbuild-$(PACKAGE_VERSION).log && ln -sf testbuild-$(PACKAGE_VERSION).log testbuild.log\n\t@touch testerr-$(PACKAGE_VERSION).log && ln -sf testerr-$(PACKAGE_VERSION).log testerr.log\n\t@mkdir -p test-release && cp $(PACKAGE_TARNAME)-$(PACKAGE_VERSION).tar.* test-release && pushd test-release && \\\n\t\ttar xzf $(PACKAGE_TARNAME)-$(PACKAGE_VERSION).tar.gz  && pushd $(PACKAGE_TARNAME)-$(PACKAGE_VERSION) && ./testbuild.sh && popd && rm -rf $(PACKAGE_TARNAME)-$(PACKAGE_VERSION) && \\\n\t\techo \"Success\" && popd\n\ntest-release-all: dist-archives\n\t@touch testbuild-$(PACKAGE_VERSION).log && ln -sf testbuild-$(PACKAGE_VERSION).log testbuild.log\n\t@mkdir -p test-release && cp $(PACKAGE_TARNAME)-$(PACKAGE_VERSION).tar.* test-release && pushd test-release && \\\n\t\ttar xJf $(PACKAGE_TARNAME)-$(PACKAGE_VERSION).tar.xz  && pushd $(PACKAGE_TARNAME)-$(PACKAGE_VERSION) && ./testbuild.sh && popd && rm -rf $(PACKAGE_TARNAME)-$(PACKAGE_VERSION) && \\\n\t\ttar xjf $(PACKAGE_TARNAME)-$(PACKAGE_VERSION).tar.bz2 && pushd $(PACKAGE_TARNAME)-$(PACKAGE_VERSION) && ./testbuild.sh && popd && rm -rf $(PACKAGE_TARNAME)-$(PACKAGE_VERSION) && \\\n\t\ttar xzf $(PACKAGE_TARNAME)-$(PACKAGE_VERSION).tar.gz  && pushd $(PACKAGE_TARNAME)-$(PACKAGE_VERSION) && ./testbuild.sh && popd && rm -rf $(PACKAGE_TARNAME)-$(PACKAGE_VERSION) && \\\n\t\techo \"Success\" && popd\n\ndocs:\n\t@SRCDIR=$(top_srcdir) doxygen -q $(top_srcdir)/Doxyfile\n\n@VALGRIND_CHECK_RULES@\n\n.PHONY: docs test-release\n"
  },
  {
    "path": "NEWS",
    "content": ""
  },
  {
    "path": "README.markdown",
    "content": "libstrophe [![Build Status](https://github.com/strophe/libstrophe/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/strophe/libstrophe/actions/workflows/main.yml?query=branch%3Amaster+++)\n==========\n\nlibstrophe is a lightweight XMPP client library written in C. It has\nminimal dependencies and is configurable for various environments. It\nruns well on Linux, Unix and Windows based platforms.\n\nlibstrophe is dual licensed under MIT or GPLv3.\n\nBuild Instructions\n------------------\n\nIf you are building from a source control checkout, run:\n\n    ./bootstrap.sh\n\nto generate the `configure` script.\n\nFrom the top-level directory, run the following commands:\n\n    ./configure\n    make\n\nThe public API is defined in `strophe.h` which is in the\ntop-level directory.\n\nThe `examples` directory contains some examples of how to\nuse the library; these may be helpful in addition to the\nAPI documentation\n\nTo install on your system, as root (or using sudo):\n\n    make install\n\nNote, the default install path is `/usr/local/`, to specify\nanother path use the `--prefix` option during configure, e.g.:\n\n    ./configure --prefix=/usr\n\n### Android\n\nRun script `build-android.sh` and follow the instructions. You will\nneed expat sources and android-ndk.\n\n### Code Coverage\n\nIf you want to create a code coverage report, run:\n\n    ./configure --enable-coverage\n    make coverage\n\nThe coverage report can be found in `./coverage/index.html`.\n\n\nRequirements\n------------\n\nlibstrophe requires:\n\n- expat or libxml2 - expat is the default; use `--with-libxml2` to\n  switch\n- openssl or GnuTLS on UNIX systems - openssl is default; use\n  `--with-gnutls` to switch\n\nTo build libstrophe using autotools you will need `autoconf`,\n`automake`, `libtool` and `pkg-config`.\n\nTo run code coverage analysis you will need `gcov` and `lcov`.\n\nInstallation\n------------\n\nlibstrophe package has been added to popular Linux distributions,\nBSD systems and OSX package managers.\n\nDocumentation\n-------------\n\nAPI documentation is inline with the code and conforms to Doxygen\nstandards. You can generate an HTML version of the API documentation\nby running:\n\n    doxygen\n\nor if you have everything configured properly:\n\n    make docs\n\nThen open `docs/html/index.html`.\n\nAn online version of the documentation of the latest release is available on https://strophe.im/libstrophe/\n\nReleases\n--------\n\nReleases are signed with the GPG key with ID `F8ADC1F9A68A7AFF0E2C89E4391A5EFC2D1709DE`.\n\nIt can be found e.g. on https://keys.openpgp.org/\n"
  },
  {
    "path": "TODO",
    "content": ""
  },
  {
    "path": "_clang-format",
    "content": "﻿---\nAlignConsecutiveAssignments: 'false'\nAlignEscapedNewlines: Left\nAllowShortBlocksOnASingleLine: 'true'\nAllowShortFunctionsOnASingleLine: Empty\nAllowShortIfStatementsOnASingleLine: 'false'\nBinPackParameters: 'false'\nBreakBeforeBraces: Linux\nColumnLimit: '80'\nDerivePointerAlignment: 'false'\nIndentGotoLabels: false\nIndentWidth: '4'\nPointerAlignment: Right\nSortIncludes: 'false'\nTabWidth: '4'\nUseTab: Never\n\n...\n"
  },
  {
    "path": "bootstrap.sh",
    "content": "#!/bin/sh\n\n# Some versions of aclocal fail if m4/ doesn't exist\nmkdir -p m4\nautoreconf -i\n"
  },
  {
    "path": "build-android.sh",
    "content": "#!/bin/sh\n\nDIR=`dirname $0`\nEXPAT_PATH=\"$DIR/expat\"\nEXPAT_FILE='lib/expat.h'\n\necho\necho Attention: libstrophe will be built without TLS support. To enable TLS\necho you need to replace \\'src/tls_dummy.c\\' with \\'src/tls_opnessl.c\\' in\necho \\'jni/Android.mk\\', add path to the openssl headers and link your program\necho with libssl and libcrypto.\necho\n\nif [ ! -d $EXPAT_PATH ]; then\n    mkdir $EXPAT_PATH\nfi\n\n# TODO Accept expat tarball as argument and extract it to the right place.\n#      Or download sources from sf.net.\n\nif [ ! -d $EXPAT_PATH/lib -o ! -f \"$EXPAT_PATH/$EXPAT_FILE\" ]; then\n    cat <<EOT\n    Error: expat sources not found.\n\n    Extract expat sources to $EXPAT_PATH. Make sure $EXPAT_PATH/$EXPAT_FILE and\n    other source files exist.\nEOT\n    exit 1\nfi\n\nndk-build -C \"$DIR\" clean || exit 1\nndk-build -C \"$DIR\"       || exit 1\n\necho\necho \"basic example:\"\nls -l \"$DIR\"/libs/*/basic\necho\necho \"libstrophe.a:\"\nls -l \"$DIR\"/obj/local/*/libstrophe.a\n"
  },
  {
    "path": "configure.ac",
    "content": "m4_define([v_maj], [0])\nm4_define([v_min], [14])\nm4_define([v_patch], [0])\nm4_define([project_version], [v_maj.v_min.v_patch])\n\nm4_define([lt_cur], m4_eval(v_maj + v_min))\nm4_define([lt_rev], v_patch)\nm4_define([lt_age], v_min)\n\nAC_INIT([libstrophe], [project_version], [jack@metajack.im])\nAC_CONFIG_MACRO_DIR([m4])\nAM_INIT_AUTOMAKE([foreign])\nLT_INIT([dlopen])\n\nAC_PROG_CC\nAM_PROG_CC_C_O\nPKG_PROG_PKG_CONFIG\n\nAC_CANONICAL_HOST\nAS_CASE([$host_os],\n    [dragonfly*],  [PLATFORM=\"bsd\"],\n    [freebsd*],    [PLATFORM=\"bsd\"],\n    [netbsd*],     [PLATFORM=\"bsd\"],\n    [openbsd*],    [PLATFORM=\"bsd\"],\n    [*nto*|*qnx*], [PLATFORM=\"qnx\"],\n    [*solaris*],   [PLATFORM=\"solaris\"],\n    [*android*],   [PLATFORM=\"android\"],\n    [*haiku*],     [PLATFORM=\"haiku\"],\n    [*mingw*],     [PLATFORM=\"win32\"\n                    MINGW_LIBS=\"-lws2_32\"],\n                   [PLATFORM=\"nix\"])\n\nWARNING_FLAGS=\"-Wall\"\n\nAS_CASE([$PLATFORM],\n    [haiku],   [],\n               [WARNING_FLAGS=\"$WARNING_FLAGS -Wextra\"])\n\nAC_ARG_ENABLE([examples],\n    [AS_HELP_STRING([--disable-examples], [turn off examples])],\n    [case \"${enableval}\" in yes) examples=true ;; no)  examples=false ;; *) AC_MSG_ERROR([bad value ${enableval} for --disable-examples]) ;; esac],[examples=true])\nAM_CONDITIONAL([EXAMPLES], [test x$examples = xtrue])\nAC_ARG_WITH([libxml2],\n    [AS_HELP_STRING([--with-libxml2], [use libxml2 for XML parsing, expat is the default])])\nAC_ARG_WITH([gnutls],\n    [AS_HELP_STRING([--with-gnutls], [use GnuTLS for TLS support, OpenSSL is the default])])\nAC_ARG_WITH([schannel],\n    [AS_HELP_STRING([--with-schannel], [use Windows Schannel for TLS support, OpenSSL is the default])])\nAC_ARG_ENABLE([tls],\n    [AS_HELP_STRING([--disable-tls], [disable TLS support])])\nAC_ARG_ENABLE([cares],\n    [AS_HELP_STRING([--enable-cares], [use c-ares for DNS resolution])])\nAC_ARG_ENABLE([getrandom],\n    [AS_HELP_STRING([--disable-getrandom], [disable usage of the getrandom() system call])])\nAC_ARG_ENABLE([zlib],\n    [AS_HELP_STRING([--disable-zlib], [disable compression support])])\n\nAC_ARG_ENABLE([fuzzing],\n    [AS_HELP_STRING([--enable-fuzzing], [turn on fuzzing test])],\n    [case \"${enableval}\" in yes) fuzzing=true ;; no)  fuzzing=false ;; *) AC_MSG_ERROR([bad value ${enableval} for --enable-fuzzing]) ;; esac],[fuzzing=false])\nAM_CONDITIONAL([FUZZ], [test x$fuzzing = xtrue])\n\nif test \"x$enable_fuzzing\" = \"xyes\" ; then\n    if test \"x$CC\" != \"xclang\" ; then\n        AC_MSG_ERROR([\"You need to set CC=clang to use --enable-fuzzing, used $CC\"])\n    fi\nfi\n\nAC_ARG_ENABLE([coverage],\n    [AS_HELP_STRING([--enable-coverage], [turn on coverage for tests])],\n    [case \"${enableval}\" in yes) coverage=true ;; no)  coverage=false ;; *) AC_MSG_ERROR([bad value ${enableval} for --enable-coverage]) ;; esac],[coverage=false])\nAM_CONDITIONAL([COVERAGE], [test x$coverage = xtrue])\n\nif test \"$enable_coverage\" = \"yes\"; then\n    COVERAGE_CFLAGS=\"--coverage -g\"\n    COVERAGE_LDFLAGS=\"--coverage -lgcov\"\n    COVERAGE_PRE=\"-Wl,--whole-archive\"\n    COVERAGE_POST=\"-Wl,--no-whole-archive\"\nelse\n    COVERAGE_CFLAGS=\"\"\n    COVERAGE_LDFLAGS=\"\"\n    COVERAGE_PRE=\"\"\n    COVERAGE_POST=\"\"\nfi\n\nm4_include([m4/ax_valgrind_check.m4])\nAX_VALGRIND_DFLT([drd], [off])\nAX_VALGRIND_DFLT([helgrind], [off])\nAX_VALGRIND_DFLT([sgcheck], [off])\nAX_VALGRIND_CHECK\n\nAC_SEARCH_LIBS([clock_gettime], [rt], AC_DEFINE(HAVE_CLOCK_GETTIME,1))\nAC_SEARCH_LIBS([socket], [network socket])\nAC_CHECK_FUNCS([snprintf vsnprintf], [], [have_snprintf=no])\n\ndnl Checking for va_copy availability\nAC_MSG_CHECKING([for va_copy])\nAC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <stdarg.h>\nva_list ap1,ap2;]], [[va_copy(ap1,ap2);]])],\nhave_va_copy=yes,\nhave_va_copy=no)\nAC_MSG_RESULT($have_va_copy)\nif test x\"$have_va_copy\" = x\"yes\"; then\n    AC_DEFINE(HAVE_VA_COPY,1,[Whether va_copy() is available])\nelse\n    AC_MSG_CHECKING([for __va_copy])\n    AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include <stdarg.h>\n    va_list ap1,ap2;]], [[__va_copy(ap1,ap2);]])],\n    have___va_copy=yes,\n    have___va_copy=no)\n    AC_MSG_RESULT($have___va_copy)\n    if test x\"$have___va_copy\" = x\"yes\"; then\n        AC_DEFINE(HAVE___VA_COPY,1,[Whether __va_copy() is available])\n    fi\nfi\n\nif test x\"$have_va_copy$have___va_copy\" = x\"nono\"; then\n    dnl Checking whether va_list is an array type\n    AC_MSG_CHECKING([whether va_list is an array type])\n    AC_TRY_COMPILE2([\n    #include <stdarg.h>\n    void a(va_list * ap) {}],[\n    va_list ap1, ap2; a(&ap1); ap2 = (va_list) ap1],[\n      AC_MSG_RESULT(no)],[\n      AC_MSG_RESULT(yes)\n      AC_DEFINE([VA_LIST_IS_ARRAY], [1],[Define if va_list is an array type])])\nfi\n\nif test \"x$enable_tls\" != xno -a \"x$with_gnutls\" = xyes; then\n    PKG_CHECK_MODULES([gnutls], [gnutls],\n        [PC_REQUIRES=\"gnutls ${PC_REQUIRES}\"],\n        [AC_CHECK_HEADER([gnutls/gnutls.h],\n            [\n                gnutls_LIBS=\"-lgnutls\"\n                PC_LIBS=\"${gnutls_LIBS} ${PC_LIBS}\"\n            ],\n            [AC_MSG_ERROR([gnutls not found; gnutls required])]\n        )])\nelif test \"x$enable_tls\" != xno -a \"x$with_schannel\" = xyes; then\n    if test \"x$PLATFORM\" != xwin32; then\n        AC_MSG_ERROR([schannel is only supported on Windows])\n    fi\nelif test \"x$enable_tls\" != xno; then\n    PKG_CHECK_MODULES([openssl], [openssl],\n        [PC_REQUIRES=\"openssl ${PC_REQUIRES}\"],\n        [AC_CHECK_HEADER([openssl/ssl.h],\n            [\n                openssl_LIBS=\"-lssl -lcrypto\"\n                PC_LIBS=\"${openssl_LIBS} ${PC_LIBS}\"\n            ],\n            [AC_MSG_ERROR([openssl not found; openssl required])]\n        )])\nfi\n\nAC_CHECK_FUNCS([getrandom], [], [enable_getrandom=no])\nif test \"$enable_getrandom\" = \"no\"; then\n    AC_DEFINE(DONT_USE_GETRANDOM)\n    AC_MSG_NOTICE([libstrophe will not use the getrandom() system call])\nfi\n\nwith_parser=\"\"\nif test \"x$with_libxml2\" != xyes; then\n    PKG_CHECK_MODULES([expat], [expat >= 2.0.0],\n        [\n            with_parser=\"expat\"\n            PC_REQUIRES=\"expat ${PC_REQUIRES}\"\n        ],\n        [AC_CHECK_HEADER([expat.h],\n            [\n                with_parser=\"expat\"\n                expat_LIBS=\"-lexpat\"\n                PC_LIBS=\"${expat_LIBS} ${PC_LIBS}\"\n            ])\n        ])\nfi\nif test \"x$with_libxml2\" != xno -a \"x$with_parser\" = x; then\n    PKG_CHECK_MODULES([libxml2], [libxml-2.0 >= 2.7],\n        [\n            with_parser=\"libxml2\"\n            PC_REQUIRES=\"libxml-2.0 ${PC_REQUIRES}\"\n        ],\n        [\n            old_CFLAGS=$CFLAGS\n            CFLAGS=\"-I${includedir}/libxml2\"\n            AC_CHECK_HEADER([libxml/parser.h],\n                [\n                    with_parser=\"libxml2\"\n                    libxml2_CFLAGS=\"-I${includedir}/libxml2\"\n                    libxml2_LIBS=\"-lxml2 -lm\"\n                    PC_LIBS=\"${libxml2_LIBS} ${PC_LIBS}\"\n                    PC_CFLAGS=\"${libxml2_CFLAGS} ${PC_CFLAGS}\"\n                ])\n            CFLAGS=$old_CFLAGS\n        ])\nfi\n\nif test \"x$with_parser\" = xlibxml2; then\n    PARSER_CFLAGS=$libxml2_CFLAGS\n    PARSER_LIBS=$libxml2_LIBS\nelif test \"x$with_parser\" = xexpat; then\n    PARSER_CFLAGS=$expat_CFLAGS\n    PARSER_LIBS=$expat_LIBS\nelse\n    AC_MSG_ERROR([no XML parser was found, libstrophe requires expat or libxml2])\nfi\n\nAC_MSG_NOTICE([libstrophe will use the $with_parser XML parser])\n\nif test \"x$enable_cares\" = xyes; then\n    PKG_CHECK_MODULES([libcares], [libcares >= 1.7.0],\n        [\n            PC_REQUIRES=\"libcares ${PC_REQUIRES}\"\n            RESOLV_CFLAGS=$libcares_CFLAGS\n            RESOLV_LIBS=$libcares_LIBS\n            AC_DEFINE([HAVE_CARES])\n        ],\n        [AC_MSG_ERROR([libcares not found])])\n        # TODO: if pkg-config doesn't find, check the library manually\nelse\n\nAS_CASE([$PLATFORM],\n    [bsd],     [RESOLV_LIBS=\"\"],\n    [qnx],     [RESOLV_LIBS=\"-lsocket\"],\n    [solaris], [RESOLV_LIBS=\"-lresolv -lsocket -lnsl\"],\n    [android], [RESOLV_LIBS=\"\"],\n    [haiku],   [RESOLV_LIBS=\"-lnetwork\"],\n    [win32],   [RESOLV_LIBS=\"\"],\n               [RESOLV_LIBS=\"-lresolv\"])\n\nif test \"x$PLATFORM\" != xwin32; then\nLIBS_TMP=\"${LIBS}\"\nLIBS=\"${RESOLV_LIBS}\"\nAC_LINK_IFELSE([AC_LANG_SOURCE([\n        #include <sys/types.h>\n        #include <netinet/in.h>\n        #include <arpa/nameser.h>\n        #include <resolv.h>\n        #include <netdb.h>\n\n        int main() {\n            (void)res_query(NULL, 0, 0, NULL, 0);\n            return 0;\n        }\n    ])],\n    [],\n    [AC_MSG_ERROR([res_query() not found with LIBS=\"${LIBS}\"])])\nLIBS=\"${LIBS_TMP}\"\nPC_LIBS=\"${RESOLV_LIBS} ${PC_LIBS}\"\nfi\n\nfi\n\nif test \"x$enable_zlib\" != xno; then\n    PKG_CHECK_MODULES([zlib], [zlib >= 1.2.0],\n        [\n            PC_REQUIRES=\"zlib ${PC_REQUIRES}\"\n            ZLIB_CFLAGS=$zlib_CFLAGS\n            ZLIB_LIBS=$zlib_LIBS\n            AC_DEFINE([HAVE_ZLIB])\n        ],\n        [AC_MSG_ERROR([zlib not found])])\n        # TODO: if pkg-config doesn't find, check the library manually\nfi\n\nm4_ifdef([PKG_INSTALLDIR], [PKG_INSTALLDIR],\n    [AC_ARG_WITH([pkgconfigdir],\n        [AS_HELP_STRING([--with-pkgconfigdir],\n            [install directory for libstrophe.pc pkg-config file])],\n        [], [with_pkgconfigdir='$(libdir)/pkgconfig'])\n    AC_SUBST([pkgconfigdir], [${with_pkgconfigdir}])])\n\nAM_CONDITIONAL([PARSER_EXPAT], [test x$with_parser != xlibxml2])\nAM_CONDITIONAL([DISABLE_COMPRESSION], [test x$enable_zlib = xno])\nAM_CONDITIONAL([DISABLE_TLS], [test x$enable_tls = xno])\nAM_CONDITIONAL([DISABLE_STATIC], [test x$enable_static = xno])\nAM_CONDITIONAL([NEED_SNPRINTF], [test x$have_snprintf = xno])\nAM_CONDITIONAL([TLS_WITH_GNUTLS], [test x$with_gnutls = xyes])\nAM_CONDITIONAL([TLS_WITH_SCHANNEL], [test x$with_schannel = xyes])\n\n# define while compiling\nAC_DEFINE_UNQUOTED(LIBXMPP_VERSION_MAJOR, [v_maj], [Major version])\nAC_DEFINE_UNQUOTED(LIBXMPP_VERSION_MINOR, [v_min], [Minor version])\n\nVMAJ=v_maj\nVMIN=v_min\nAC_SUBST(VMAJ)\nAC_SUBST(VMIN)\n# define in package-config file\nPC_CFLAGS=\"${PC_CFLAGS} -DLIBXMPP_VERSION_MAJOR=${VMAJ} -DLIBXMPP_VERSION_MINOR=${VMIN}\"\n\n# set the SO version of the installed library\nVERSION_INFO=\"lt_cur:lt_rev:lt_age\"\nAC_SUBST([VERSION_INFO])\n\nAC_SUBST([PC_REQUIRES], [${PC_REQUIRES}])\nAC_SUBST([PC_CFLAGS], [${PC_CFLAGS}])\nAC_SUBST([PC_LIBS], [${PC_LIBS}])\n\nAC_SUBST(COVERAGE_CFLAGS)\nAC_SUBST(COVERAGE_LDFLAGS)\nAC_SUBST(COVERAGE_PRE)\nAC_SUBST(COVERAGE_POST)\nAC_SUBST(MINGW_LIBS)\nAC_SUBST(PARSER_CFLAGS)\nAC_SUBST(PARSER_LIBS)\nAC_SUBST(RESOLV_CFLAGS)\nAC_SUBST(RESOLV_LIBS)\nAC_SUBST(WARNING_FLAGS)\nAC_SUBST(ZLIB_CFLAGS)\nAC_SUBST(ZLIB_LIBS)\nAC_CONFIG_FILES([Makefile libstrophe.pc])\nAC_OUTPUT\n"
  },
  {
    "path": "docs/.keep",
    "content": ""
  },
  {
    "path": "examples/README.md",
    "content": "Build Instructions\n==================\n\nCompile example files with the following gcc flags:\n```\ngcc -o bot bot.c `pkg-config --cflags --libs libstrophe`\n```\n"
  },
  {
    "path": "examples/active.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* active.c\n** libstrophe XMPP client library -- basic usage example\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/* This example demonstrates basic handler functions by printing out\n** active resources on a jabberd 2.x server.  This program requires\n** an admin account on a jabberd 2.x account in order to run.\n*/\n\n#include <stdio.h>\n#include <string.h>\n\n#include <strophe.h>\n\nint handle_reply(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_stanza_t *query, *item;\n    const char *type;\n\n    (void)userdata;\n\n    type = xmpp_stanza_get_type(stanza);\n    if (strcmp(type, \"error\") == 0)\n        fprintf(stderr, \"ERROR: query failed\\n\");\n    else {\n        query = xmpp_stanza_get_child_by_name(stanza, \"query\");\n        printf(\"Active Sessions:\\n\");\n        for (item = xmpp_stanza_get_children(query); item;\n             item = xmpp_stanza_get_next(item))\n            printf(\"\\t %s\\n\", xmpp_stanza_get_attribute(item, \"jid\"));\n        printf(\"END OF LIST\\n\");\n    }\n\n    /* disconnect */\n    xmpp_disconnect(conn);\n\n    return 0;\n}\n\nvoid conn_handler(xmpp_conn_t *conn,\n                  xmpp_conn_event_t status,\n                  int error,\n                  xmpp_stream_error_t *stream_error,\n                  void *userdata)\n{\n    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;\n    xmpp_stanza_t *iq, *query;\n\n    (void)error;\n    (void)stream_error;\n\n    if (status == XMPP_CONN_CONNECT) {\n        fprintf(stderr, \"DEBUG: connected\\n\");\n\n        /* create iq stanza for request */\n        iq = xmpp_iq_new(ctx, \"get\", \"active1\");\n        xmpp_stanza_set_to(iq, \"xxxxxxxxx.com\");\n\n        query = xmpp_stanza_new(ctx);\n        xmpp_stanza_set_name(query, \"query\");\n        xmpp_stanza_set_ns(query, XMPP_NS_DISCO_ITEMS);\n        xmpp_stanza_set_attribute(query, \"node\", \"sessions\");\n\n        xmpp_stanza_add_child(iq, query);\n\n        /* we can release the stanza since it belongs to iq now */\n        xmpp_stanza_release(query);\n\n        /* set up reply handler */\n        xmpp_id_handler_add(conn, handle_reply, \"active1\", ctx);\n\n        /* send out the stanza */\n        xmpp_send(conn, iq);\n\n        /* release the stanza */\n        xmpp_stanza_release(iq);\n    } else {\n        fprintf(stderr, \"DEBUG: disconnected\\n\");\n        xmpp_stop(ctx);\n    }\n}\n\nint main(int argc, char **argv)\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n\n    if (argc != 3) {\n        fprintf(stderr, \"Usage: active <jid> <pass>\\n\\n\");\n        return 1;\n    }\n\n    /* initialize lib */\n    xmpp_initialize();\n\n    /* create a context */\n    ctx = xmpp_ctx_new(NULL, NULL);\n\n    /* create a connection */\n    conn = xmpp_conn_new(ctx);\n\n    /*\n     * also you can disable TLS support or force legacy SSL\n     * connection without STARTTLS\n     *\n     * see xmpp_conn_set_flags() or examples/basic.c\n     */\n\n    /* setup authentication information */\n    xmpp_conn_set_jid(conn, argv[1]);\n    xmpp_conn_set_pass(conn, argv[2]);\n\n    /* initiate connection */\n    xmpp_connect_client(conn, NULL, 0, conn_handler, ctx);\n\n    /* start the event loop */\n    xmpp_run(ctx);\n\n    /* release our connection and context */\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n\n    /* shutdown lib */\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "examples/basic.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* basic.c\n** libstrophe XMPP client library -- basic usage example\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <strophe.h>\n\n/* define a handler for connection events */\nstatic void conn_handler(xmpp_conn_t *conn,\n                         xmpp_conn_event_t status,\n                         int error,\n                         xmpp_stream_error_t *stream_error,\n                         void *userdata)\n{\n    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;\n\n    (void)error;\n    (void)stream_error;\n\n    if (status == XMPP_CONN_CONNECT) {\n        fprintf(stderr, \"DEBUG: connected\\n\");\n        xmpp_disconnect(conn);\n    } else {\n        fprintf(stderr, \"DEBUG: disconnected\\n\");\n        xmpp_stop(ctx);\n    }\n}\n\nstatic void usage(int exit_code)\n{\n    fprintf(stderr,\n            \"Usage: basic [options] [<host> [<port>]]\\n\\n\"\n            \"Options:\\n\"\n            \"  --jid <jid>              The JID to use to authenticate.\\n\"\n            \"  --pass <pass>            The password of the JID.\\n\"\n            \"  --disable-tls            Disable TLS.\\n\"\n            \"  --mandatory-tls          Deny plaintext connection.\\n\"\n            \"  --trust-tls              Trust TLS certificate.\\n\"\n            \"  --legacy-ssl             Use old style SSL.\\n\"\n            \"  --legacy-auth            Allow legacy authentication.\\n\"\n            \"Note: --disable-tls conflicts with --mandatory-tls or \"\n            \"--legacy-ssl\\n\");\n\n    exit(exit_code);\n}\n\nint main(int argc, char **argv)\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    xmpp_log_t *log;\n    char *jid = NULL, *password = NULL, *host = NULL;\n    long flags = 0;\n    int i;\n    unsigned long port = 0;\n\n    /* take a jid and password on the command line */\n    for (i = 1; i < argc; ++i) {\n        if (strcmp(argv[i], \"--help\") == 0)\n            usage(0);\n        else if (strcmp(argv[i], \"--disable-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_DISABLE_TLS;\n        else if (strcmp(argv[i], \"--mandatory-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_MANDATORY_TLS;\n        else if (strcmp(argv[i], \"--trust-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_TRUST_TLS;\n        else if (strcmp(argv[i], \"--legacy-ssl\") == 0)\n            flags |= XMPP_CONN_FLAG_LEGACY_SSL;\n        else if (strcmp(argv[i], \"--legacy-auth\") == 0)\n            flags |= XMPP_CONN_FLAG_LEGACY_AUTH;\n        else if ((strcmp(argv[i], \"--jid\") == 0) && (++i < argc))\n            jid = argv[i];\n        else if ((strcmp(argv[i], \"--pass\") == 0) && (++i < argc))\n            password = argv[i];\n        else\n            break;\n    }\n    if ((!jid) || (argc - i) > 2) {\n        usage(1);\n    }\n\n    if (i < argc)\n        host = argv[i];\n    if (i + 1 < argc)\n        port = strtoul(argv[i + 1], NULL, 0);\n\n    /*\n     * Note, this example doesn't handle errors. Applications should check\n     * return values of non-void functions.\n     */\n\n    /* init library */\n    xmpp_initialize();\n\n    /* pass NULL instead to silence output */\n    log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    /* create a context */\n    ctx = xmpp_ctx_new(NULL, log);\n\n    /* create a connection */\n    conn = xmpp_conn_new(ctx);\n\n    /* configure connection properties (optional) */\n    xmpp_conn_set_flags(conn, flags);\n\n    /* setup authentication information */\n    if (jid)\n        xmpp_conn_set_jid(conn, jid);\n    if (password)\n        xmpp_conn_set_pass(conn, password);\n\n    /* initiate connection */\n    if (xmpp_connect_client(conn, host, port, conn_handler, ctx) == XMPP_EOK) {\n\n        /* enter the event loop -\n           our connect handler will trigger an exit */\n        xmpp_run(ctx);\n    }\n\n    /* release our connection and context */\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n\n    /* final shutdown of the library */\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "examples/bot.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* bot.c\n** libstrophe XMPP client library -- basic usage example\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/* simple bot example\n**\n** This example was provided by Matthew Wild <mwild1@gmail.com>.\n**\n** This bot responds to basic messages and iq version requests.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef _WIN32\n#include <conio.h>\n#include <ctype.h>\n#else\n#include <unistd.h>\n#endif\n\n#include <strophe.h>\n\nstatic int reconnect;\n\nint version_handler(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_stanza_t *reply, *query, *name, *version, *text;\n    const char *ns;\n    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;\n\n    printf(\"Received version request from %s\\n\", xmpp_stanza_get_from(stanza));\n\n    reply = xmpp_stanza_reply(stanza);\n    xmpp_stanza_set_type(reply, \"result\");\n\n    query = xmpp_stanza_new(ctx);\n    xmpp_stanza_set_name(query, \"query\");\n    ns = xmpp_stanza_get_ns(xmpp_stanza_get_children(stanza));\n    if (ns) {\n        xmpp_stanza_set_ns(query, ns);\n    }\n\n    name = xmpp_stanza_new(ctx);\n    xmpp_stanza_set_name(name, \"name\");\n    xmpp_stanza_add_child(query, name);\n    xmpp_stanza_release(name);\n\n    text = xmpp_stanza_new(ctx);\n    xmpp_stanza_set_text(text, \"libstrophe example bot\");\n    xmpp_stanza_add_child(name, text);\n    xmpp_stanza_release(text);\n\n    version = xmpp_stanza_new(ctx);\n    xmpp_stanza_set_name(version, \"version\");\n    xmpp_stanza_add_child(query, version);\n    xmpp_stanza_release(version);\n\n    text = xmpp_stanza_new(ctx);\n    xmpp_stanza_set_text(text, \"1.0\");\n    xmpp_stanza_add_child(version, text);\n    xmpp_stanza_release(text);\n\n    xmpp_stanza_add_child(reply, query);\n    xmpp_stanza_release(query);\n\n    xmpp_send(conn, reply);\n    xmpp_stanza_release(reply);\n    return 1;\n}\n\nstatic int _quit_handler(xmpp_conn_t *conn, void *userdata)\n{\n    (void)userdata;\n    xmpp_disconnect(conn);\n    return 0;\n}\n\nint message_handler(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;\n    xmpp_stanza_t *body, *reply;\n    const char *type;\n    char *intext, *replytext;\n\n    body = xmpp_stanza_get_child_by_name(stanza, \"body\");\n    if (body == NULL)\n        return 1;\n    type = xmpp_stanza_get_type(stanza);\n    if (type != NULL && strcmp(type, \"error\") == 0)\n        return 1;\n\n    intext = xmpp_stanza_get_text(body);\n\n    printf(\"Incoming message from %s: %s\\n\", xmpp_stanza_get_from(stanza),\n           intext);\n\n    reply = xmpp_stanza_reply(stanza);\n    if (xmpp_stanza_get_type(reply) == NULL)\n        xmpp_stanza_set_type(reply, \"chat\");\n\n    if (strcmp(intext, \"quit\") == 0) {\n        replytext = strdup(\"bye!\");\n        xmpp_timed_handler_add(conn, _quit_handler, 500, NULL);\n    } else if (strcmp(intext, \"reconnect\") == 0) {\n        replytext = strdup(\"alright, let's see what happens!\");\n        reconnect = 1;\n        xmpp_timed_handler_add(conn, _quit_handler, 500, NULL);\n    } else {\n        replytext = (char *)malloc(strlen(\" to you too!\") + strlen(intext) + 1);\n        strcpy(replytext, intext);\n        strcat(replytext, \" to you too!\");\n    }\n    xmpp_free(ctx, intext);\n    xmpp_message_set_body(reply, replytext);\n\n    xmpp_send(conn, reply);\n    xmpp_stanza_release(reply);\n    free(replytext);\n\n    return 1;\n}\n\n/* define a handler for connection events */\nvoid conn_handler(xmpp_conn_t *conn,\n                  xmpp_conn_event_t status,\n                  int error,\n                  xmpp_stream_error_t *stream_error,\n                  void *userdata)\n{\n    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;\n\n    (void)error;\n    (void)stream_error;\n\n    if (status == XMPP_CONN_CONNECT) {\n        xmpp_stanza_t *pres;\n        fprintf(stderr, \"DEBUG: connected\\n\");\n        xmpp_handler_add(conn, version_handler, \"jabber:iq:version\", \"iq\", NULL,\n                         ctx);\n        xmpp_handler_add(conn, message_handler, NULL, \"message\", NULL, ctx);\n\n        /* Send initial <presence/> so that we appear online to contacts */\n        pres = xmpp_presence_new(ctx);\n        xmpp_send(conn, pres);\n        xmpp_stanza_release(pres);\n    } else {\n        fprintf(stderr, \"DEBUG: disconnected\\n\");\n        xmpp_stop(ctx);\n    }\n}\n\n#ifdef _WIN32\nstatic char *getpassword(const char *prompt, size_t maxlen)\n{\n    char *b, *buffer = malloc(maxlen);\n    size_t i = 0;\n\n    b = buffer;\n    fputs(prompt, stderr);\n    for (i = 0; i < maxlen; i++, b++) {\n        char c = _getch();\n        if (c == '\\r' || c == '\\n')\n            break;\n        *b = c;\n    }\n    *b = '\\0';\n    fputs(\"\\n\", stderr);\n    return buffer;\n}\n#else\n#define getpassword(prompt, maxlen) getpass(prompt)\n#endif\n\nstatic int\npassword_callback(char *pw, size_t pw_max, xmpp_conn_t *conn, void *userdata)\n{\n    (void)userdata;\n    printf(\"Trying to unlock %s\\n\", xmpp_conn_get_keyfile(conn));\n    char *pass = getpassword(\"Please enter password: \", pw_max);\n    if (!pass)\n        return -1;\n    size_t passlen = strlen(pass);\n    int ret;\n    if (passlen >= pw_max) {\n        ret = -1;\n        goto out;\n    }\n    ret = passlen + 1;\n    memcpy(pw, pass, ret);\nout:\n    memset(pass, 0, passlen);\n    return ret;\n}\n\nstatic void usage(int exit_code)\n{\n    fprintf(stderr,\n            \"Usage: bot [options] <jid> <pass>\\n\\n\"\n            \"Options:\\n\"\n            \"  --jid <jid>              The JID to use to authenticate.\\n\"\n            \"  --pass <pass>            The password of the JID.\\n\"\n            \"  --tls-cert <cert>        Path to client certificate.\\n\"\n            \"  --tls-key <key>          Path to private key or P12 file.\\n\\n\"\n            \"  --tcp-keepalive          Configure TCP keepalive.\\n\"\n            \"  --disable-tls            Disable TLS.\\n\"\n            \"  --mandatory-tls          Deny plaintext connection.\\n\"\n            \"  --trust-tls              Trust TLS certificate.\\n\"\n            \"  --legacy-ssl             Use old style SSL.\\n\"\n            \"  --legacy-auth            Allow legacy authentication.\\n\"\n            \"Note: --disable-tls conflicts with --mandatory-tls or \"\n            \"--legacy-ssl\\n\"\n            \"  --zlib                   Enable compression via zlib.\\n\"\n            \"  --dont-reset             When using zlib, don't do a full-flush \"\n            \"after compression.\\n\");\n\n    exit(exit_code);\n}\n\nint main(int argc, char **argv)\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    xmpp_log_t *log;\n    xmpp_sm_state_t *sm_state = NULL;\n    char *jid = NULL, *password = NULL, *host = NULL, *cert = NULL, *key = NULL;\n    long flags = 0;\n    int i, tcp_keepalive = 0;\n    unsigned long port = 0;\n\n    /* take a jid and password on the command line */\n    for (i = 1; i < argc; ++i) {\n        if (strcmp(argv[i], \"--help\") == 0)\n            usage(0);\n        else if (strcmp(argv[i], \"--disable-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_DISABLE_TLS;\n        else if (strcmp(argv[i], \"--mandatory-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_MANDATORY_TLS;\n        else if (strcmp(argv[i], \"--trust-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_TRUST_TLS;\n        else if (strcmp(argv[i], \"--legacy-ssl\") == 0)\n            flags |= XMPP_CONN_FLAG_LEGACY_SSL;\n        else if (strcmp(argv[i], \"--legacy-auth\") == 0)\n            flags |= XMPP_CONN_FLAG_LEGACY_AUTH;\n        else if (strcmp(argv[i], \"--zlib\") == 0)\n            flags |= XMPP_CONN_FLAG_ENABLE_COMPRESSION;\n        else if (strcmp(argv[i], \"--dont-reset\") == 0)\n            flags |= XMPP_CONN_FLAG_COMPRESSION_DONT_RESET;\n        else if ((strcmp(argv[i], \"--jid\") == 0) && (++i < argc))\n            jid = argv[i];\n        else if ((strcmp(argv[i], \"--pass\") == 0) && (++i < argc))\n            password = argv[i];\n        else if ((strcmp(argv[i], \"--tls-cert\") == 0) && (++i < argc))\n            cert = argv[i];\n        else if ((strcmp(argv[i], \"--tls-key\") == 0) && (++i < argc))\n            key = argv[i];\n        else if (strcmp(argv[i], \"--tcp-keepalive\") == 0)\n            tcp_keepalive = 1;\n        else\n            break;\n    }\n    if ((!jid && !key) || (argc - i) > 2) {\n        usage(1);\n    }\n\n    if (i < argc)\n        host = argv[i];\n    if (i + 1 < argc)\n        port = strtoul(argv[i + 1], NULL, 0);\n\n    /* init library */\n    xmpp_initialize();\n\n    /* pass NULL instead to silence output */\n    log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    /* create a context */\n    ctx = xmpp_ctx_new(NULL, log);\n\ncreate_connection:\n    reconnect = 0;\n    /* create a connection */\n    conn = xmpp_conn_new(ctx);\n\n    /* configure connection properties (optional) */\n    xmpp_conn_set_flags(conn, flags);\n\n    /* ask for a password if key is protected */\n    xmpp_conn_set_password_callback(conn, password_callback, NULL);\n    /* try at max 3 times in case the user enters the password wrong */\n    xmpp_conn_set_password_retries(conn, 3);\n    /* setup authentication information */\n    if (key)\n        xmpp_conn_set_client_cert(conn, cert, key);\n    if (jid)\n        xmpp_conn_set_jid(conn, jid);\n    if (password)\n        xmpp_conn_set_pass(conn, password);\n\n    /* enable TCP keepalive, using canned callback function */\n    if (tcp_keepalive)\n        xmpp_conn_set_sockopt_callback(conn, xmpp_sockopt_cb_keepalive);\n\n    /* set Stream-Mangement state if available */\n    if (sm_state) {\n        xmpp_conn_set_sm_state(conn, sm_state);\n        sm_state = NULL;\n    }\n\n    /* initiate connection */\n    if (xmpp_connect_client(conn, host, port, conn_handler, ctx) == XMPP_EOK) {\n\n        /* enter the event loop -\n           our connect handler will trigger an exit */\n        xmpp_run(ctx);\n    }\n\n    /* save the Stream-Mangement state if we should re-connect */\n    if (reconnect)\n        sm_state = xmpp_conn_get_sm_state(conn);\n\n    /* release our connection */\n    xmpp_conn_release(conn);\n\n    if (reconnect)\n        goto create_connection;\n\n    /* release our context */\n    xmpp_ctx_free(ctx);\n\n    /* final shutdown of the library */\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "examples/complex.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* complex.c\n** libstrophe XMPP client library -- more complex usage example\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifdef _WIN32\n#include <conio.h>\n#include <ctype.h>\n#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <iphlpapi.h>\n#include <mstcpip.h> /* tcp_keepalive */\n#else\n#include <unistd.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/tcp.h>\n#endif\n\n#include <strophe.h>\n\n/* hardcoded TCP keepalive timeout and interval */\n#define KA_TIMEOUT 60\n#define KA_INTERVAL 30\n#define KA_COUNT 3\n#define USER_TIMEOUT 150\n\nstatic void print_tlscert(const xmpp_tlscert_t *cert)\n{\n    const char *name;\n    size_t n;\n    for (n = 0; n < (unsigned)XMPP_CERT_ELEMENT_MAX; ++n) {\n        printf(\"\\t%32s: %s\\n\", xmpp_tlscert_get_description(n),\n               xmpp_tlscert_get_string(cert, n));\n    }\n    n = 0;\n    while ((name = xmpp_tlscert_get_dnsname(cert, n++)) != NULL)\n        printf(\"\\t%32s: %s\\n\", \"dnsName\", name);\n    printf(\"PEM:\\n%s\\n\", xmpp_tlscert_get_pem(cert));\n}\n\n/* define a handler for connection events */\nstatic void conn_handler(xmpp_conn_t *conn,\n                         xmpp_conn_event_t status,\n                         int error,\n                         xmpp_stream_error_t *stream_error,\n                         void *userdata)\n{\n    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;\n    int secured;\n\n    (void)error;\n    (void)stream_error;\n\n    if (status == XMPP_CONN_CONNECT) {\n        fprintf(stderr, \"DEBUG: connected\\n\");\n        secured = xmpp_conn_is_secured(conn);\n        fprintf(stderr, \"DEBUG: connection is %s.\\n\",\n                secured ? \"secured\" : \"NOT secured\");\n        if (secured) {\n            xmpp_tlscert_t *cert = xmpp_conn_get_peer_cert(conn);\n            print_tlscert(cert);\n            xmpp_tlscert_free(cert);\n        }\n        xmpp_disconnect(conn);\n    } else {\n        fprintf(stderr, \"DEBUG: disconnected\\n\");\n        xmpp_stop(ctx);\n    }\n}\n\nstatic int certfail_handler(const xmpp_tlscert_t *cert,\n                            const char *const errormsg)\n{\n    char read_char[16] = {0};\n    printf(\"Received certificate can't be validated!\\n\");\n    printf(\"Reason: %s\\n\", errormsg);\n    print_tlscert(cert);\n    printf(\"Do you agree to connect?\\n[y(es)|n(o)]: \");\n    fflush(stdout);\n    if (fgets(read_char, sizeof(read_char), stdin) == NULL) {\n        printf(\"fgets() failed\\n\");\n        return 0;\n    }\n    printf(\"\\n\");\n    return read_char[0] == 'y' || read_char[0] == 'Y';\n}\n\n#ifdef _WIN32\nstatic char *getpassword(const char *prompt, size_t maxlen)\n{\n    char *b, *buffer = malloc(maxlen);\n    size_t i = 0;\n\n    b = buffer;\n    fputs(prompt, stderr);\n    for (i = 0; i < maxlen; i++, b++) {\n        char c = _getch();\n        if (c == '\\r' || c == '\\n')\n            break;\n        *b = c;\n    }\n    *b = '\\0';\n    fputs(\"\\n\", stderr);\n    return buffer;\n}\n#else\n#define getpassword(prompt, maxlen) getpass(prompt)\n#endif\n\nstatic int\npassword_callback(char *pw, size_t pw_max, xmpp_conn_t *conn, void *userdata)\n{\n    (void)userdata;\n    printf(\"Trying to unlock %s\\n\", xmpp_conn_get_keyfile(conn));\n    char *pass = getpassword(\"Please enter password: \", pw_max);\n    if (!pass)\n        return -1;\n    size_t passlen = strlen(pass);\n    int ret;\n    if (passlen >= pw_max) {\n        ret = -1;\n        goto out;\n    }\n    ret = passlen + 1;\n    memcpy(pw, pass, ret);\nout:\n    memset(pass, 0, passlen);\n    return ret;\n}\n\nstatic int sockopt_cb(xmpp_conn_t *conn, void *socket)\n{\n    int timeout = KA_TIMEOUT;\n    int interval = KA_INTERVAL;\n    int count = KA_COUNT;\n    unsigned int user_timeout = USER_TIMEOUT;\n    int ret;\n    int optval = (timeout && interval) ? 1 : 0;\n\n    (void)conn;\n\n#ifdef _WIN32\n    (void)count;\n    (void)user_timeout;\n\n    SOCKET sock = *((SOCKET *)socket);\n    struct tcp_keepalive ka;\n    DWORD dw = 0;\n\n    ka.onoff = optval;\n    ka.keepalivetime = timeout * 1000;\n    ka.keepaliveinterval = interval * 1000;\n    ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &ka, sizeof(ka), NULL, 0, &dw,\n                   NULL, NULL);\n#else\n    int sock = *((int *)socket);\n\n    fprintf(stderr, \"DEBUG: setting socket options\\n\");\n\n    ret = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));\n    if (ret < 0)\n        return ret;\n\n    if (optval) {\n#ifdef TCP_KEEPIDLE\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &timeout,\n                         sizeof(timeout));\n#elif defined(TCP_KEEPALIVE)\n        /* QNX receives `struct timeval' as argument, but it seems OSX does int\n         */\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPALIVE, &timeout,\n                         sizeof(timeout));\n#endif /* TCP_KEEPIDLE */\n        if (ret < 0)\n            return ret;\n#ifdef TCP_KEEPINTVL\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &interval,\n                         sizeof(interval));\n        if (ret < 0)\n            return ret;\n#endif /* TCP_KEEPINTVL */\n    }\n\n    if (count) {\n#ifdef TCP_KEEPCNT\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(count));\n        if (ret < 0)\n            return ret;\n#endif /* TCP_KEEPCNT */\n    }\n\n    if (user_timeout) {\n#ifdef TCP_USER_TIMEOUT\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_USER_TIMEOUT, &user_timeout,\n                         sizeof(user_timeout));\n        if (ret < 0)\n            return ret;\n#elif defined(TCP_RXT_CONNDROPTIME)\n        int rxt = user_timeout / 1000;\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_RXT_CONNDROPTIME, &rxt,\n                         sizeof(rxt));\n        if (ret < 0)\n            return ret;\n#endif /* TCP_USER_TIMEOUT */\n    }\n#endif /* _WIN32 */\n\n    return ret;\n}\n\nstatic void usage(int exit_code)\n{\n    fprintf(stderr,\n            \"Usage: complex [options] [<host> [<port>]]\\n\\n\"\n            \"Options:\\n\"\n            \"  --jid <jid>              The JID to use to authenticate.\\n\"\n            \"  --pass <pass>            The password of the JID.\\n\"\n            \"  --tls-cert <cert>        Path to client certificate.\\n\"\n            \"  --tls-key <key>          Path to private key or P12 file.\\n\\n\"\n            \"  --capath <path>          Path to an additional CA trust store \"\n            \"(directory).\\n\"\n            \"  --cafile <path>          Path to an additional CA trust store \"\n            \"(single file).\\n\"\n            \"  --disable-tls            Disable TLS.\\n\"\n            \"  --mandatory-tls          Deny plaintext connection.\\n\"\n            \"  --trust-tls              Trust TLS certificate.\\n\"\n            \"  --enable-certfail        Enable certfail handler.\\n\"\n            \"  --legacy-ssl             Use old style SSL.\\n\"\n            \"  --legacy-auth            Allow legacy authentication.\\n\"\n            \"  --zlib                   Enable compression via zlib.\\n\"\n            \"  --dont-reset             When using zlib, don't do a full-flush \"\n            \"after compression.\\n\"\n            \"  --verbose                Increase the verbosity level.\\n\"\n            \"  --tcp-keepalive          Configure TCP keepalive.\\n\\n\"\n            \"Note: --disable-tls conflicts with --mandatory-tls or \"\n            \"--legacy-ssl\\n\");\n\n    exit(exit_code);\n}\n\nint main(int argc, char **argv)\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    xmpp_log_t *log;\n    char *jid = NULL, *password = NULL, *cert = NULL, *key = NULL, *host = NULL,\n         *capath = NULL, *cafile = NULL;\n    long flags = 0;\n    int tcp_keepalive = 0, verbosity = 0, certfail = 0;\n    int i;\n    unsigned long port = 0;\n\n    /* take a jid and password on the command line */\n    for (i = 1; i < argc; ++i) {\n        if (strcmp(argv[i], \"--help\") == 0)\n            usage(0);\n        else if (strcmp(argv[i], \"--disable-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_DISABLE_TLS;\n        else if (strcmp(argv[i], \"--mandatory-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_MANDATORY_TLS;\n        else if (strcmp(argv[i], \"--trust-tls\") == 0)\n            flags |= XMPP_CONN_FLAG_TRUST_TLS;\n        else if (strcmp(argv[i], \"--legacy-ssl\") == 0)\n            flags |= XMPP_CONN_FLAG_LEGACY_SSL;\n        else if (strcmp(argv[i], \"--legacy-auth\") == 0)\n            flags |= XMPP_CONN_FLAG_LEGACY_AUTH;\n        else if (strcmp(argv[i], \"--zlib\") == 0)\n            flags |= XMPP_CONN_FLAG_ENABLE_COMPRESSION;\n        else if (strcmp(argv[i], \"--dont-reset\") == 0)\n            flags |= XMPP_CONN_FLAG_COMPRESSION_DONT_RESET;\n        else if (strcmp(argv[i], \"--verbose\") == 0)\n            verbosity++;\n        else if (strcmp(argv[i], \"--tcp-keepalive\") == 0)\n            tcp_keepalive = 1;\n        else if (strcmp(argv[i], \"--enable-certfail\") == 0)\n            certfail = 1;\n        else if ((strcmp(argv[i], \"--jid\") == 0) && (++i < argc))\n            jid = argv[i];\n        else if ((strcmp(argv[i], \"--pass\") == 0) && (++i < argc))\n            password = argv[i];\n        else if ((strcmp(argv[i], \"--tls-cert\") == 0) && (++i < argc))\n            cert = argv[i];\n        else if ((strcmp(argv[i], \"--tls-key\") == 0) && (++i < argc))\n            key = argv[i];\n        else if ((strcmp(argv[i], \"--capath\") == 0) && (++i < argc))\n            capath = argv[i];\n        else if ((strcmp(argv[i], \"--cafile\") == 0) && (++i < argc))\n            cafile = argv[i];\n        else\n            break;\n    }\n    if ((!jid && !key) || (argc - i) > 2) {\n        usage(1);\n    }\n\n    if (i < argc)\n        host = argv[i];\n    if (i + 1 < argc)\n        port = strtoul(argv[i + 1], NULL, 0);\n\n    /*\n     * Note, this example doesn't handle errors. Applications should check\n     * return values of non-void functions.\n     */\n\n    /* init library */\n    xmpp_initialize();\n\n    /* pass NULL instead to silence output */\n    log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    /* create a context */\n    ctx = xmpp_ctx_new(NULL, log);\n    xmpp_ctx_set_verbosity(ctx, verbosity);\n\n    /* create a connection */\n    conn = xmpp_conn_new(ctx);\n\n    /* configure connection properties (optional) */\n    xmpp_conn_set_flags(conn, flags);\n    /* configure TCP keepalive (optional) */\n    if (tcp_keepalive)\n        xmpp_conn_set_sockopt_callback(conn, sockopt_cb);\n\n    /* ask for a password if key is protected */\n    xmpp_conn_set_password_callback(conn, password_callback, NULL);\n    /* try at max 3 times in case the user enters the password wrong */\n    xmpp_conn_set_password_retries(conn, 3);\n    /* setup authentication information */\n    if (key) {\n        xmpp_conn_set_client_cert(conn, cert, key);\n    }\n    if (jid)\n        xmpp_conn_set_jid(conn, jid);\n    if (password)\n        xmpp_conn_set_pass(conn, password);\n\n    if (certfail)\n        xmpp_conn_set_certfail_handler(conn, certfail_handler);\n    if (capath)\n        xmpp_conn_set_capath(conn, capath);\n    if (cafile)\n        xmpp_conn_set_cafile(conn, cafile);\n\n    /* initiate connection */\n    if (xmpp_connect_client(conn, host, port, conn_handler, ctx) == XMPP_EOK) {\n\n        /* enter the event loop -\n           our connect handler will trigger an exit */\n        xmpp_run(ctx);\n    }\n\n    /* release our connection and context */\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n\n    /* final shutdown of the library */\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "examples/component.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* component.c\n** libstrophe XMPP client library -- external component (XEP-0114) example\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/* This example demonstrates simple connection to a server\n** as an external component. See XEP-0114 for more details.\n** This program requires correctly configured server to run.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n\n#include <strophe.h>\n\n/* define a handler for connection events */\nvoid conn_handler(xmpp_conn_t *conn,\n                  xmpp_conn_event_t status,\n                  int error,\n                  xmpp_stream_error_t *stream_error,\n                  void *userdata)\n{\n    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;\n\n    (void)error;\n    (void)stream_error;\n\n    if (status == XMPP_CONN_CONNECT) {\n        fprintf(stderr, \"DEBUG: connected\\n\");\n        xmpp_disconnect(conn);\n    } else {\n        fprintf(stderr, \"DEBUG: disconnected\\n\");\n        xmpp_stop(ctx);\n    }\n}\n\nint main(int argc, char **argv)\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    xmpp_log_t *log;\n    char *jid, *pass, *host, *port_err = NULL;\n    unsigned short port = 0;\n\n    /* take a jid and password on the command line */\n    if (argc < 4 || argc > 5) {\n        fprintf(stderr, \"Usage: component <jid> <pass> <host> [<port>]\\n\\n\");\n        return 1;\n    }\n\n    jid = argv[1];\n    pass = argv[2];\n    host = argv[3];\n\n    if (argc == 5) {\n        short tmp_port = (short)strtol(argv[4], &port_err, 10);\n        if (tmp_port < 0 || *port_err != '\\0') {\n            fprintf(stderr, \"Invalid value of <port> [%s].\\n\", argv[4]);\n            return 1;\n        }\n        port = (unsigned short)tmp_port;\n    }\n\n    /* init library */\n    xmpp_initialize();\n\n    /* pass NULL instead to silence output */\n    log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    /* create a context */\n    ctx = xmpp_ctx_new(NULL, log);\n\n    /* create a connection */\n    conn = xmpp_conn_new(ctx);\n\n    /* setup authentication information */\n    xmpp_conn_set_jid(conn, jid);\n    xmpp_conn_set_pass(conn, pass);\n\n    /* initiate connection */\n    xmpp_connect_component(conn, host, port, conn_handler, ctx);\n\n    /* enter the event loop -\n       our connect handler will trigger an exit */\n    xmpp_run(ctx);\n\n    /* release our connection and context */\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n\n    /* final shutdown of the library */\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "examples/perf.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* perf.c\n * strophe XMPP client library -- performance measure\n *\n * Copyright (C) 2022 Steffen Jaeckel <jaeckel-floss@eyet-services.de>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/** @file\n *  performance measure\n *\n *  Timing code shamelessly borrowed from libtomcrypt/demos/timing.c\n */\n\n#include <strophe.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdint.h>\n#include <inttypes.h>\n#include <time.h>\n\nstatic void init_timer(void);\nstatic void t_start(void);\nstatic uint64_t t_read(void);\nstatic const char *perf_time_unit;\n\n#define NUM_SAMPLES 1000u\n\nstatic void perf_rand(xmpp_ctx_t *ctx)\n{\n    xmpp_rand_t *rng = xmpp_rand_new(ctx);\n\n    uint64_t t1, t2, t3 = 0;\n    unsigned int n;\n    const size_t alloc_sz = 0x1000u;\n    size_t sz;\n    unsigned char *buf = malloc(alloc_sz);\n\n    /* pre-heat */\n    for (n = 1; n < 4; ++n) {\n        xmpp_rand_bytes(rng, buf, alloc_sz / n);\n    }\n\n    for (sz = 2; sz <= alloc_sz; sz <<= 1) {\n        t2 = 0;\n        for (n = 0; n < NUM_SAMPLES; ++n) {\n\n            t_start();\n            t1 = t_read();\n\n            xmpp_rand_bytes(rng, buf, sz);\n\n            t1 = t_read() - t1;\n            t2 += t1;\n        }\n        t2 /= NUM_SAMPLES;\n        fprintf(stderr, \"Reading %6zu bytes from PRNG took %8\" PRIu64 \" %s\\n\",\n                sz, t2, perf_time_unit);\n        if (t3) {\n            double d3 = (double)t3, d2 = (double)t2;\n            fprintf(stderr, \"    +%.2f%%\\n\",\n                    (d2 - d3) / ((d2 + d3) * 0.5) * 100.);\n        }\n        t3 = t2;\n    }\n    free(buf);\n    xmpp_rand_free(ctx, rng);\n}\n\nint main()\n{\n    /* pass NULL instead to silence output */\n    xmpp_log_t *log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    /* create a context */\n    xmpp_ctx_t *ctx = xmpp_ctx_new(NULL, log);\n\n    init_timer();\n\n    perf_rand(ctx);\n\n    return 0;\n}\n\n#define TIMES 100000\nstatic uint64_t timer, skew = 0;\n\n/* RDTSC from Scott Duplichan */\nstatic uint64_t rdtsc(void)\n{\n#if defined __GNUC__\n#if defined(__i386__) || defined(__x86_64__)\n    /* version from http://www.mcs.anl.gov/~kazutomo/rdtsc.html\n     * the old code always got a warning issued by gcc, clang did not\n     * complain...\n     */\n    unsigned hi, lo;\n    __asm__ __volatile__(\"rdtsc\" : \"=a\"(lo), \"=d\"(hi));\n    return ((uint64_t)lo) | (((uint64_t)hi) << 32);\n#elif defined(__POWERPC__)\n    unsigned long a, b;\n    __asm__ __volatile__(\"mftbu %1 \\nmftb %0\\n\" : \"=r\"(a), \"=r\"(b));\n    return (((uint64_t)b) << 32ULL) | ((uint64_t)a);\n#elif defined(__ia64__) /* gcc-IA64 version */\n    unsigned long result;\n    __asm__ __volatile__(\"mov %0=ar.itc\" : \"=r\"(result)::\"memory\");\n    while (__builtin_expect((int)result == -1, 0))\n        __asm__ __volatile__(\"mov %0=ar.itc\" : \"=r\"(result)::\"memory\");\n    return result;\n#elif defined(__sparc__)\n#if defined(__arch64__)\n    uint64_t a;\n    asm volatile(\"rd %%tick,%0\" : \"=r\"(a));\n    return a;\n#else\n    register unsigned long x, y;\n    __asm__ __volatile__(\"rd %%tick, %0; clruw %0, %1; srlx %0, 32, %0\"\n                         : \"=r\"(x), \"=r\"(y)\n                         : \"0\"(x), \"1\"(y));\n    return ((unsigned long long)x << 32) | y;\n#endif\n#elif defined(__aarch64__)\n    uint64_t CNTVCT_EL0;\n    __asm__ __volatile__(\"mrs %0, cntvct_el0\" : \"=r\"(CNTVCT_EL0));\n    return CNTVCT_EL0;\n#elif defined HAVE_CLOCK_GETTIME\n#define USE_CLOCK_GETTIME\n    struct timespec result;\n    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &result);\n    return result.tv_sec * 1000000000 + result.tv_nsec;\n#else\n    return clock();\n#endif /* __GNUC__ */\n\n/* Microsoft and Intel Windows compilers */\n#elif defined _M_IX86\n    __asm rdtsc\n#elif defined _M_AMD64\n    return __rdtsc();\n#elif defined _M_IA64\n#if defined __INTEL_COMPILER\n#include <ia64intrin.h>\n#endif\n    return __getReg(3116);\n#elif defined HAVE_CLOCK_GETTIME\n#define USE_CLOCK_GETTIME\n    struct timespec result;\n    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &result);\n    return result.tv_sec * 1000000000 + result.tv_nsec;\n#else\n    return clock();\n#endif\n}\n\n#if defined USE_CLOCK_GETTIME\nstatic const char *perf_time_unit = \"ns\";\n#else\nstatic const char *perf_time_unit = \"cycles\";\n#endif\n\nstatic void t_start(void)\n{\n    timer = rdtsc();\n}\n\nstatic uint64_t t_read(void)\n{\n    return rdtsc() - timer;\n}\n\nstatic void init_timer(void)\n{\n    uint64_t c1, c2, t1, t2;\n    unsigned long y1;\n\n    c1 = c2 = (uint64_t)-1;\n    for (y1 = 0; y1 < TIMES * 100; y1++) {\n        t_start();\n        t1 = t_read();\n        t2 = (t_read() - t1) >> 1;\n\n        c1 = (t1 > c1) ? t1 : c1;\n        c2 = (t2 > c2) ? t2 : c2;\n    }\n    skew = c2 - c1;\n    fprintf(stderr, \"Clock Skew: %lu\\n\", (unsigned long)skew);\n}\n"
  },
  {
    "path": "examples/register.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* register.c\n * strophe XMPP client library -- In-band registration (XEP-0077)\n *\n * Copyright (C) 2020 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/*\n * This example uses a \"raw\" connection to establish connection to a server\n * without account. Then it queries server to register new account according\n * to XEP-0077.\n *\n * How to use it. After the application connects and receives instructions\n * from the server, user will be prompted to type information such as\n * username, password, etc. Press enter without typing if you want to skip\n * a field and not to send it to the server.\n *\n * Notice, the example doesn't implement forms. Therefore, it won't work\n * in complicated scenarios.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <strophe.h>\n\ntypedef struct {\n    xmpp_ctx_t *ctx;\n    const char *jid;\n} xmpp_reg_t;\n\n#define FEATURES_TIMEOUT 5000 /* 5 seconds */\n\nstatic void\niq_reg_send_form(xmpp_reg_t *reg, xmpp_conn_t *conn, xmpp_stanza_t *stanza)\n{\n    xmpp_ctx_t *ctx = reg->ctx;\n    xmpp_stanza_t *query;\n    xmpp_stanza_t *next;\n    xmpp_stanza_t *elem;\n    xmpp_stanza_t *text;\n    xmpp_stanza_t *iq;\n    const char *name;\n    size_t len;\n    char buf[256];\n    char *s;\n\n    query = xmpp_stanza_get_child_by_name(stanza, \"query\");\n    if (!query) {\n        xmpp_disconnect(conn);\n        return;\n    }\n\n    next = xmpp_stanza_get_children(query);\n    query = xmpp_stanza_new(ctx);\n    xmpp_stanza_set_name(query, \"query\");\n    xmpp_stanza_set_ns(query, XMPP_NS_REGISTER);\n    while (next) {\n        name = xmpp_stanza_get_name(next);\n        if (name && strcmp(name, \"instructions\") == 0) {\n            s = xmpp_stanza_get_text(next);\n            printf(\"instructions: %s\\n\", s);\n            xmpp_free(ctx, s);\n        } else {\n            printf(\"%s: \", name);\n            s = fgets(buf, sizeof(buf), stdin);\n            if (s != NULL) {\n                len = strlen(s);\n                if (len > 0 && s[len - 1] == '\\n') {\n                    s[len - 1] = '\\0';\n                    --len;\n                }\n                if (len > 0) {\n                    elem = xmpp_stanza_new(ctx);\n                    text = xmpp_stanza_new(ctx);\n                    xmpp_stanza_set_text(text, s);\n                    xmpp_stanza_set_name(elem, name);\n                    xmpp_stanza_add_child(elem, text);\n                    xmpp_stanza_add_child(query, elem);\n                    xmpp_stanza_release(text);\n                    xmpp_stanza_release(elem);\n                }\n            }\n        }\n        next = xmpp_stanza_get_next(next);\n    }\n\n    if (xmpp_stanza_get_children(query) == NULL) {\n        fprintf(stderr, \"DEBUG: nothing to send\\n\");\n        xmpp_disconnect(conn);\n    } else {\n        iq = xmpp_iq_new(ctx, \"set\", \"reg2\");\n        xmpp_stanza_add_child(iq, query);\n        xmpp_stanza_release(query);\n        xmpp_send(conn, iq);\n        xmpp_stanza_release(iq);\n    }\n}\n\nstatic int iq_reg2_cb(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    const char *type;\n\n    (void)userdata;\n\n    type = xmpp_stanza_get_type(stanza);\n    if (!type || strcmp(type, \"error\") == 0) {\n        fprintf(stderr, \"DEBUG: error during registration\\n\");\n        goto quit;\n    }\n\n    if (strcmp(type, \"result\") != 0) {\n        fprintf(stderr, \"DEBUG: expected type 'result', but got %s\\n\", type);\n        goto quit;\n    }\n\n    fprintf(stderr, \"DEBUG: successful registration\\n\");\n\nquit:\n    xmpp_disconnect(conn);\n\n    return 0;\n}\n\nstatic int iq_reg_cb(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_reg_t *reg = (xmpp_reg_t *)userdata;\n    xmpp_stanza_t *registered = NULL;\n    xmpp_stanza_t *query;\n    const char *type;\n\n    type = xmpp_stanza_get_type(stanza);\n    if (!type || strcmp(type, \"error\") == 0) {\n        fprintf(stderr, \"DEBUG: error during registration\\n\");\n        xmpp_disconnect(conn);\n        goto quit;\n    }\n\n    if (strcmp(type, \"result\") != 0) {\n        fprintf(stderr, \"DEBUG: expected type 'result', but got %s\\n\", type);\n        xmpp_disconnect(conn);\n        goto quit;\n    }\n\n    query = xmpp_stanza_get_child_by_name(stanza, \"query\");\n    if (query)\n        registered = xmpp_stanza_get_child_by_name(query, \"registered\");\n    if (registered != NULL) {\n        fprintf(stderr, \"DEBUG: already registered\\n\");\n        xmpp_disconnect(conn);\n        goto quit;\n    }\n    xmpp_id_handler_add(conn, iq_reg2_cb, \"reg2\", reg);\n    iq_reg_send_form(reg, conn, stanza);\n\nquit:\n    return 0;\n}\n\nstatic int\n_handle_error(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    (void)stanza;\n    (void)userdata;\n\n    fprintf(stderr, \"DEBUG: received stream error\\n\");\n    xmpp_disconnect(conn);\n\n    return 0;\n}\n\nstatic int _handle_proceedtls_default(xmpp_conn_t *conn,\n                                      xmpp_stanza_t *stanza,\n                                      void *userdata)\n{\n    const char *name = xmpp_stanza_get_name(stanza);\n\n    (void)userdata;\n\n    if (strcmp(name, \"proceed\") == 0) {\n        fprintf(stderr, \"DEBUG: proceeding with TLS\\n\");\n        if (xmpp_conn_tls_start(conn) == 0) {\n            xmpp_handler_delete(conn, _handle_error);\n            xmpp_conn_open_stream_default(conn);\n        } else {\n            fprintf(stderr, \"DEBUG: TLS failed\\n\");\n            /* failed tls spoils the connection, so disconnect */\n            xmpp_disconnect(conn);\n        }\n    }\n    return 0;\n}\n\nstatic int _handle_missing_features(xmpp_conn_t *conn, void *userdata)\n{\n    (void)userdata;\n\n    fprintf(stderr, \"DEBUG: timeout\\n\");\n    xmpp_disconnect(conn);\n\n    return 0;\n}\n\nstatic int\n_handle_features(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_reg_t *reg = (xmpp_reg_t *)userdata;\n    xmpp_ctx_t *ctx = reg->ctx;\n    xmpp_stanza_t *child;\n    xmpp_stanza_t *iq;\n    char *domain;\n\n    xmpp_timed_handler_delete(conn, _handle_missing_features);\n\n    /* secure connection if possible */\n    child = xmpp_stanza_get_child_by_name(stanza, \"starttls\");\n    if (child && (strcmp(xmpp_stanza_get_ns(child), XMPP_NS_TLS) == 0)) {\n        fprintf(stderr, \"DEBUG: server supports TLS, try to establish\\n\");\n        child = xmpp_stanza_new(ctx);\n        xmpp_stanza_set_name(child, \"starttls\");\n        xmpp_stanza_set_ns(child, XMPP_NS_TLS);\n        xmpp_handler_add(conn, _handle_proceedtls_default, XMPP_NS_TLS, NULL,\n                         NULL, NULL);\n        xmpp_send(conn, child);\n        xmpp_stanza_release(child);\n        return 0;\n    }\n\n    /* check whether server supports in-band registration */\n    child = xmpp_stanza_get_child_by_name(stanza, \"register\");\n    if (child && strcmp(xmpp_stanza_get_ns(child), XMPP_NS_REGISTER) == 0) {\n        fprintf(stderr, \"DEBUG: server doesn't support in-band registration\\n\");\n        xmpp_disconnect(conn);\n        return 0;\n    }\n\n    fprintf(stderr, \"DEBUG: server supports in-band registration\\n\");\n    domain = xmpp_jid_domain(ctx, reg->jid);\n    iq = xmpp_iq_new(ctx, \"get\", \"reg1\");\n    xmpp_stanza_set_to(iq, domain);\n    child = xmpp_stanza_new(ctx);\n    xmpp_stanza_set_name(child, \"query\");\n    xmpp_stanza_set_ns(child, XMPP_NS_REGISTER);\n    xmpp_stanza_add_child(iq, child);\n\n    xmpp_handler_add(conn, iq_reg_cb, XMPP_NS_REGISTER, \"iq\", NULL, reg);\n    xmpp_send(conn, iq);\n\n    xmpp_free(ctx, domain);\n    xmpp_stanza_release(child);\n    xmpp_stanza_release(iq);\n\n    return 0;\n}\n\nstatic void conn_handler(xmpp_conn_t *conn,\n                         xmpp_conn_event_t status,\n                         int error,\n                         xmpp_stream_error_t *stream_error,\n                         void *userdata)\n{\n    xmpp_reg_t *reg = (xmpp_reg_t *)userdata;\n    int secured;\n\n    (void)error;\n    (void)stream_error;\n\n    if (status == XMPP_CONN_RAW_CONNECT) {\n        fprintf(stderr, \"DEBUG: raw connection established\\n\");\n        xmpp_conn_open_stream_default(conn);\n    } else if (status == XMPP_CONN_CONNECT) {\n        fprintf(stderr, \"DEBUG: stream opened\\n\");\n        secured = xmpp_conn_is_secured(conn);\n        fprintf(stderr, \"DEBUG: connection is %s.\\n\",\n                secured ? \"secured\" : \"NOT secured\");\n\n        /* setup handler for stream:error */\n        xmpp_handler_add(conn, _handle_error, XMPP_NS_STREAMS, \"error\", NULL,\n                         NULL);\n\n        /* setup handlers for incoming <stream:features> */\n        xmpp_handler_add(conn, _handle_features, XMPP_NS_STREAMS, \"features\",\n                         NULL, reg);\n        xmpp_timed_handler_add(conn, _handle_missing_features, FEATURES_TIMEOUT,\n                               NULL);\n    } else {\n        fprintf(stderr, \"DEBUG: disconnected\\n\");\n        xmpp_stop(reg->ctx);\n    }\n}\n\nxmpp_reg_t *xmpp_reg_new(void)\n{\n    xmpp_reg_t *reg;\n\n    reg = malloc(sizeof(*reg));\n    if (reg != NULL) {\n        memset(reg, 0, sizeof(*reg));\n    }\n    return reg;\n}\n\nvoid xmpp_reg_release(xmpp_reg_t *reg)\n{\n    free(reg);\n}\n\nint main(int argc, char **argv)\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    xmpp_log_t *log;\n    xmpp_reg_t *reg;\n    const char *jid;\n    const char *host = NULL;\n    char *domain;\n\n    if (argc < 2 || argc > 3) {\n        fprintf(stderr, \"Usage: %s <jid> [<host>]\\n\", argv[0]);\n        return 1;\n    }\n\n    jid = argv[1];\n    if (argc > 2)\n        host = argv[2];\n\n    /*\n     * Note, this example doesn't handle errors. Applications should check\n     * return values of non-void functions.\n     */\n\n    xmpp_initialize();\n    log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    ctx = xmpp_ctx_new(NULL, log);\n    conn = xmpp_conn_new(ctx);\n\n    /* jid can be a jid or domain for \"raw\" connection */\n    domain = xmpp_jid_domain(ctx, jid);\n    xmpp_conn_set_jid(conn, domain);\n    xmpp_free(ctx, domain);\n\n    /* private data */\n    reg = xmpp_reg_new();\n    reg->ctx = ctx;\n    reg->jid = jid;\n\n    xmpp_connect_raw(conn, host, 0, conn_handler, reg);\n    xmpp_run(ctx);\n\n    /* release private data */\n    xmpp_reg_release(reg);\n\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "examples/roster.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* roster.c\n** libstrophe XMPP client library -- handler example\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/* This example demonstrates basic handler functions by printing out\n** the user's roster.\n*/\n\n#include <stdio.h>\n#include <string.h>\n\n#include <strophe.h>\n\nint handle_reply(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_stanza_t *query, *item;\n    const char *type, *name;\n\n    (void)userdata;\n\n    type = xmpp_stanza_get_type(stanza);\n    if (strcmp(type, \"error\") == 0)\n        fprintf(stderr, \"ERROR: query failed\\n\");\n    else {\n        query = xmpp_stanza_get_child_by_name(stanza, \"query\");\n        printf(\"Roster:\\n\");\n        for (item = xmpp_stanza_get_children(query); item;\n             item = xmpp_stanza_get_next(item))\n            if ((name = xmpp_stanza_get_attribute(item, \"name\")))\n                printf(\"\\t %s (%s) sub=%s\\n\", name,\n                       xmpp_stanza_get_attribute(item, \"jid\"),\n                       xmpp_stanza_get_attribute(item, \"subscription\"));\n            else\n                printf(\"\\t %s sub=%s\\n\", xmpp_stanza_get_attribute(item, \"jid\"),\n                       xmpp_stanza_get_attribute(item, \"subscription\"));\n        printf(\"END OF LIST\\n\");\n    }\n\n    /* disconnect */\n    xmpp_disconnect(conn);\n\n    return 0;\n}\n\nvoid conn_handler(xmpp_conn_t *conn,\n                  xmpp_conn_event_t status,\n                  int error,\n                  xmpp_stream_error_t *stream_error,\n                  void *userdata)\n{\n    xmpp_ctx_t *ctx = (xmpp_ctx_t *)userdata;\n    xmpp_stanza_t *iq, *query;\n\n    (void)error;\n    (void)stream_error;\n\n    if (status == XMPP_CONN_CONNECT) {\n        fprintf(stderr, \"DEBUG: connected\\n\");\n\n        /* create iq stanza for request */\n        iq = xmpp_iq_new(ctx, \"get\", \"roster1\");\n\n        query = xmpp_stanza_new(ctx);\n        xmpp_stanza_set_name(query, \"query\");\n        xmpp_stanza_set_ns(query, XMPP_NS_ROSTER);\n\n        xmpp_stanza_add_child(iq, query);\n\n        /* we can release the stanza since it belongs to iq now */\n        xmpp_stanza_release(query);\n\n        /* set up reply handler */\n        xmpp_id_handler_add(conn, handle_reply, \"roster1\", ctx);\n\n        /* send out the stanza */\n        xmpp_send(conn, iq);\n\n        /* release the stanza */\n        xmpp_stanza_release(iq);\n    } else {\n        fprintf(stderr, \"DEBUG: disconnected\\n\");\n        xmpp_stop(ctx);\n    }\n}\n\nint main(int argc, char **argv)\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n\n    if (argc != 3) {\n        fprintf(stderr, \"Usage: roster <jid> <pass>\\n\\n\");\n        return 1;\n    }\n\n    /* initialize lib */\n    xmpp_initialize();\n\n    /* create a context */\n    ctx = xmpp_ctx_new(NULL, NULL);\n\n    /* create a connection */\n    conn = xmpp_conn_new(ctx);\n\n    /*\n     * also you can disable TLS support or force legacy SSL\n     * connection without STARTTLS\n     *\n     * see xmpp_conn_set_flags() or examples/basic.c\n     */\n\n    /* setup authentication information */\n    xmpp_conn_set_jid(conn, argv[1]);\n    xmpp_conn_set_pass(conn, argv[2]);\n\n    /* initiate connection */\n    xmpp_connect_client(conn, NULL, 0, conn_handler, ctx);\n\n    /* start the event loop */\n    xmpp_run(ctx);\n\n    /* release our connection and context */\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n\n    /* shutdown lib */\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "examples/uuid.c",
    "content": "#include <stdio.h>\n#include <strophe.h>\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    char *uuid;\n    int rc = 0;\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n\n    uuid = xmpp_uuid_gen(ctx);\n    if (uuid != NULL) {\n        printf(\"%s\\n\", uuid);\n        xmpp_free(ctx, uuid);\n    } else {\n        fprintf(stderr, \"Couldn't allocate memory.\\n\");\n        rc = 1;\n    }\n\n    xmpp_ctx_free(ctx);\n    return rc;\n}\n"
  },
  {
    "path": "examples/vcard.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* vcard.c\n * strophe XMPP client library -- vCard example\n *\n * Copyright (C) 2016 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n#include <assert.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <strophe.h>\n#ifndef _WIN32\n#include <libgen.h> /* basename */\n#else\n#define strtok_r strtok_s\n#define basename(x) \"vcard\"\n#endif\n\ntypedef struct {\n    xmpp_ctx_t *ctx;\n    const char *recipient;\n    const char *img_path;\n} vcard_t;\n\ntypedef void (*vcard_cb_t)(vcard_t *, xmpp_stanza_t *);\n\n#define REQ_TIMEOUT 5000\n#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))\n\nstatic void vcard_photo(vcard_t *vc, xmpp_stanza_t *stanza)\n{\n    xmpp_stanza_t *tmp;\n    char *s;\n    char *tok;\n    char *saveptr = NULL;\n    char *copy;\n    unsigned char *img;\n    size_t img_size;\n    size_t written;\n    FILE *fd;\n\n    tmp = xmpp_stanza_get_child_by_name(stanza, \"TYPE\");\n    assert(tmp != NULL);\n    s = xmpp_stanza_get_text(tmp);\n    assert(s != NULL);\n    printf(\"PHOTO: %s, saving to file %s\\n\", s, vc->img_path);\n    xmpp_free(vc->ctx, s);\n\n    tmp = xmpp_stanza_get_child_by_name(stanza, \"BINVAL\");\n    assert(tmp != NULL);\n    s = xmpp_stanza_get_text(tmp);\n    assert(s != NULL);\n\n    /* remove \\n and \\r */\n    copy = (char *)malloc(strlen(s) + 1);\n    assert(copy != NULL);\n    copy[0] = '\\0';\n    tok = strtok_r(s, \"\\n\\r\", &saveptr);\n    while (tok != NULL) {\n        strcat(copy, tok);\n        tok = strtok_r(NULL, \"\\n\\r\", &saveptr);\n    }\n\n    xmpp_base64_decode_bin(vc->ctx, copy, strlen(copy), &img, &img_size);\n    assert(img != NULL);\n\n    fd = fopen(vc->img_path, \"w\");\n    assert(fd != NULL);\n    written = fwrite(img, 1, img_size, fd);\n    if (written < img_size)\n        printf(\"Saving photo failed\\n\");\n    fclose(fd);\n\n    free(copy);\n    xmpp_free(vc->ctx, s);\n    xmpp_free(vc->ctx, img);\n}\n\nstatic void\nvcard_print_string(vcard_t *vc, xmpp_stanza_t *stanza, const char *info)\n{\n    char *s = xmpp_stanza_get_text(stanza);\n\n    assert(s != NULL);\n    printf(\"%s: %s\\n\", info, s);\n    xmpp_free(vc->ctx, s);\n}\n\nstatic void vcard_bday(vcard_t *vc, xmpp_stanza_t *stanza)\n{\n    vcard_print_string(vc, stanza, \"Birthday\");\n}\n\nstatic void vcard_desc(vcard_t *vc, xmpp_stanza_t *stanza)\n{\n    vcard_print_string(vc, stanza, \"Description\");\n}\n\nstatic void vcard_email(vcard_t *vc, xmpp_stanza_t *stanza)\n{\n    xmpp_stanza_t *userid = xmpp_stanza_get_child_by_name(stanza, \"USERID\");\n\n    if (userid != NULL)\n        vcard_print_string(vc, userid, \"E-mail\");\n}\n\nstatic void vcard_fn(vcard_t *vc, xmpp_stanza_t *stanza)\n{\n    vcard_print_string(vc, stanza, \"Full name\");\n}\n\nstatic void vcard_name(vcard_t *vc, xmpp_stanza_t *stanza)\n{\n    xmpp_stanza_t *name = xmpp_stanza_get_child_by_name(stanza, \"GIVEN\");\n    xmpp_stanza_t *family = xmpp_stanza_get_child_by_name(stanza, \"FAMILY\");\n\n    if (name != NULL)\n        vcard_print_string(vc, name, \"Given name\");\n    if (family != NULL)\n        vcard_print_string(vc, family, \"Family name\");\n}\n\nstatic void vcard_nick(vcard_t *vc, xmpp_stanza_t *stanza)\n{\n    vcard_print_string(vc, stanza, \"Nickname\");\n}\n\nstatic void vcard_url(vcard_t *vc, xmpp_stanza_t *stanza)\n{\n    vcard_print_string(vc, stanza, \"URL\");\n}\n\nstatic vcard_cb_t vcard_cb_get(xmpp_stanza_t *stanza)\n{\n    vcard_cb_t cb = NULL;\n    const char *tag;\n    size_t i;\n\n    static struct {\n        const char *tag;\n        vcard_cb_t cb;\n    } vcard_tbl[] = {\n        {\"PHOTO\", vcard_photo},   {\"BDAY\", vcard_bday}, {\"DESC\", vcard_desc},\n        {\"EMAIL\", vcard_email},   {\"FN\", vcard_fn},     {\"N\", vcard_name},\n        {\"NICKNAME\", vcard_nick}, {\"URL\", vcard_url},\n    };\n\n    tag = xmpp_stanza_get_name(stanza);\n    if (tag == NULL)\n        goto exit;\n\n    for (i = 0; i < ARRAY_SIZE(vcard_tbl); ++i) {\n        if (strcmp(tag, vcard_tbl[i].tag) == 0) {\n            cb = vcard_tbl[i].cb;\n            break;\n        }\n    }\n\nexit:\n    return cb;\n}\n\nstatic int timedout(xmpp_conn_t *conn, void *userdata)\n{\n    (void)userdata;\n\n    fprintf(stderr, \"Timeout reached.\\n\");\n    xmpp_disconnect(conn);\n\n    return 0;\n}\n\nstatic int recv_vcard(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    vcard_t *vc = userdata;\n    vcard_cb_t cb;\n    xmpp_stanza_t *child;\n    char *s;\n    size_t s_size;\n    int rc;\n\n    printf(\"Received vCard.\\n\\n\");\n\n    child = xmpp_stanza_get_child_by_name(stanza, \"error\");\n    if (child != NULL) {\n        rc = xmpp_stanza_to_text(child, &s, &s_size);\n        assert(rc == XMPP_EOK);\n        printf(\"Error returned: %s.\\n\", s);\n        xmpp_free(vc->ctx, s);\n        goto exit;\n    }\n\n    child = xmpp_stanza_get_child_by_name(stanza, \"vCard\");\n    assert(child != NULL);\n    child = xmpp_stanza_get_children(child);\n    while (child != NULL) {\n        cb = vcard_cb_get(child);\n        if (cb != NULL)\n            cb(vc, child);\n        child = xmpp_stanza_get_next(child);\n    }\n\nexit:\n    xmpp_disconnect(conn);\n\n    return 0;\n}\n\nstatic void send_vcard_req(xmpp_conn_t *conn, const char *to, const char *id)\n{\n    printf(\"Requesting vCard from %s.\\n\", to);\n    xmpp_send_raw_string(conn,\n                         \"<iq from='%s' to='%s' type='get' id='%s'>\"\n                         \"<vCard xmlns='vcard-temp'/></iq>\",\n                         xmpp_conn_get_bound_jid(conn), to, id);\n}\n\nstatic void conn_handler(xmpp_conn_t *conn,\n                         xmpp_conn_event_t status,\n                         int error,\n                         xmpp_stream_error_t *stream_error,\n                         void *userdata)\n{\n    vcard_t *vc = userdata;\n\n    if (status == XMPP_CONN_CONNECT) {\n        send_vcard_req(conn, vc->recipient, \"vc1\");\n        xmpp_id_handler_add(conn, recv_vcard, \"vc1\", vc);\n        xmpp_timed_handler_add(conn, timedout, REQ_TIMEOUT, NULL);\n    } else {\n        if (error != 0)\n            fprintf(stderr, \"Disconnected with error=%d.\\n\", error);\n        if (stream_error != NULL)\n            fprintf(stderr, \"Stream error type=%d text=%s.\\n\",\n                    stream_error->type, stream_error->text);\n        xmpp_stop(vc->ctx);\n    }\n}\n\nint main(int argc, char **argv)\n{\n    xmpp_log_t *log;\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    const char *jid;\n    const char *pass;\n    char *prog;\n    vcard_t vcard;\n\n    if (argc < 4 || argc > 5) {\n        prog = argc > 0 ? strdup(argv[0]) : NULL;\n        printf(\"Usage: %s <login-jid> <password> <recipient-jid> \"\n               \"[image-file]\\n\\n\",\n               prog == NULL ? \"vcard\" : basename(prog));\n        printf(\"If vCard contains a photo it will be stored to \"\n               \"image-file. If you don't provide the image-file \"\n               \"default filename will be generated.\\n\");\n        free(prog);\n        return 1;\n    }\n\n    jid = argv[1];\n    pass = argv[2];\n    vcard.recipient = argv[3];\n    vcard.img_path = argc > 4 ? argv[4] : \"vcard.jpg\";\n\n    xmpp_initialize();\n    log = xmpp_get_default_logger(XMPP_LEVEL_INFO);\n    ctx = xmpp_ctx_new(NULL, log);\n    conn = xmpp_conn_new(ctx);\n    xmpp_conn_set_jid(conn, jid);\n    xmpp_conn_set_pass(conn, pass);\n    vcard.ctx = ctx;\n    xmpp_connect_client(conn, NULL, 0, conn_handler, &vcard);\n    xmpp_run(ctx);\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "jni/Android.mk",
    "content": "LOCAL_PATH:= $(call my-dir)\n\n#\n# examples/basic\n#\n\ninclude $(CLEAR_VARS)\nLOCAL_MODULE := basic\nLOCAL_CFLAGS :=\nLOCAL_C_INCLUDES := \\\n\t$(LOCAL_PATH)/..\n\nLOCAL_SRC_FILES := \\\n\t../examples/basic.c\n\nLOCAL_STATIC_LIBRARIES := libstrophe libexpat\n\ninclude $(BUILD_EXECUTABLE)\n\n#\n# libstrohe (static library)\n#\n\ninclude $(CLEAR_VARS)\nLOCAL_MODULE := libstrophe\nLOCAL_CFLAGS := -DHAVE_DECL_VA_COPY\nLOCAL_C_INCLUDES := \\\n\t$(LOCAL_PATH)/.. \\\n\t$(LOCAL_PATH)/../src \\\n\t$(LOCAL_PATH)/../expat/lib\n\nLOCAL_SRC_FILES := \\\n\t../src/auth.c \\\n\t../src/conn.c \\\n\t../src/crypto.c \\\n\t../src/ctx.c \\\n\t../src/event.c \\\n\t../src/handler.c \\\n\t../src/hash.c \\\n\t../src/jid.c \\\n\t../src/md5.c \\\n\t../src/parser_expat.c \\\n\t../src/rand.c \\\n\t../src/resolver.c \\\n\t../src/sasl.c \\\n\t../src/scram.c \\\n\t../src/sha1.c \\\n\t../src/sha256.c \\\n\t../src/sha512.c \\\n\t../src/snprintf.c \\\n\t../src/sock.c \\\n\t../src/stanza.c \\\n\t../src/tls_dummy.c \\\n\t../src/util.c \\\n\t../src/uuid.c\n\nLOCAL_STATIC_LIBRARIES := libstrophe\n\ninclude $(BUILD_STATIC_LIBRARY)\n\n#\n# expat\n#\n\ninclude $(CLEAR_VARS)\nLOCAL_MODULE := libexpat\nLOCAL_CFLAGS := -DHAVE_MEMMOVE -DXML_DEV_URANDOM\n#LOCAL_C_INCLUDES := \\\n#\t$(LOCAL_PATH)/expat\n\nLOCAL_SRC_FILES := \\\n\t../expat/lib/xmlparse.c \\\n\t../expat/lib/xmlrole.c \\\n\t../expat/lib/xmltok.c \\\n\t../expat/lib/xmltok_impl.c \\\n\t../expat/lib/xmltok_ns.c\n\nLOCAL_STATIC_LIBRARIES := libexpat\n\ninclude $(BUILD_STATIC_LIBRARY)\n"
  },
  {
    "path": "jni/Application.mk",
    "content": "APP_ABI := armeabi-v7a arm64-v8a\nAPP_PLATFORM := android-19\n"
  },
  {
    "path": "libstrophe.pc.in",
    "content": "prefix=@prefix@\nexec_prefix=@exec_prefix@\nlibdir=@libdir@\nincludedir=@includedir@\n\nName: libstrophe\nDescription: A simple, lightweight C library for writing XMPP clients\nURL: https://strophe.im/libstrophe/\nVersion: @VERSION@\nRequires:\nRequires.private: @PC_REQUIRES@\nLibs: -L${libdir} -lstrophe\nLibs.private: @PC_LIBS@\nCflags: -I${includedir} @PC_CFLAGS@\n"
  },
  {
    "path": "m4/ac_try_compile2.m4",
    "content": "dnl Like AC_TRY_EVAL but also errors out if the compiler generates\ndnl _any_ output. Some compilers might issue warnings which we want\ndnl to catch.\nAC_DEFUN([AC_TRY_EVAL2],\n[{ (eval echo configure:__oline__: \\\"[$]$1\\\") 1>&AS_MESSAGE_LOG_FD; dnl\n(eval [$]$1) 2>&AS_MESSAGE_LOG_FD; _out=`eval [$]$1 2>&1` && test \"x$_out\" = x; }])\n\ndnl Like AC_TRY_COMPILE but calls AC_TRY_EVAL2 instead of AC_TRY_EVAL\nAC_DEFUN([AC_TRY_COMPILE2],\n[cat > conftest.$ac_ext <<EOF\n[#]line __oline__ \"configure\"\n#include \"confdefs.h\"\n[$1]\nint main(void) {\n[$2]\n; return 0; }\nEOF\nif AC_TRY_EVAL2(ac_compile); then\n  ifelse([$3], , :, [rm -rf conftest*\n  $3])\nelse\n  echo \"configure: failed program was:\" >&AS_MESSAGE_LOG_FD\n  cat conftest.$ac_ext >&AS_MESSAGE_LOG_FD\nifelse([$4], , , [  rm -rf conftest*\n  $4\n])dnl\nfi\nrm -f conftest*])\n"
  },
  {
    "path": "m4/ax_valgrind_check.m4",
    "content": "# ===========================================================================\n#    https://www.gnu.org/software/autoconf-archive/ax_valgrind_check.html\n# ===========================================================================\n#\n# SYNOPSIS\n#\n#   AX_VALGRIND_DFLT(memcheck|helgrind|drd|sgcheck, on|off)\n#   AX_VALGRIND_CHECK()\n#\n# DESCRIPTION\n#\n#   AX_VALGRIND_CHECK checks whether Valgrind is present and, if so, allows\n#   running `make check` under a variety of Valgrind tools to check for\n#   memory and threading errors.\n#\n#   Defines VALGRIND_CHECK_RULES which should be substituted in your\n#   Makefile; and $enable_valgrind which can be used in subsequent configure\n#   output. VALGRIND_ENABLED is defined and substituted, and corresponds to\n#   the value of the --enable-valgrind option, which defaults to being\n#   enabled if Valgrind is installed and disabled otherwise. Individual\n#   Valgrind tools can be disabled via --disable-valgrind-<tool>, the\n#   default is configurable via the AX_VALGRIND_DFLT command or is to use\n#   all commands not disabled via AX_VALGRIND_DFLT. All AX_VALGRIND_DFLT\n#   calls must be made before the call to AX_VALGRIND_CHECK.\n#\n#   If unit tests are written using a shell script and automake's\n#   LOG_COMPILER system, the $(VALGRIND) variable can be used within the\n#   shell scripts to enable Valgrind, as described here:\n#\n#     https://www.gnu.org/software/gnulib/manual/html_node/Running-self_002dtests-under-valgrind.html\n#\n#   Usage example:\n#\n#   configure.ac:\n#\n#     AX_VALGRIND_DFLT([sgcheck], [off])\n#     AX_VALGRIND_CHECK\n#\n#   in each Makefile.am with tests:\n#\n#     @VALGRIND_CHECK_RULES@\n#     VALGRIND_SUPPRESSIONS_FILES = my-project.supp\n#     EXTRA_DIST = my-project.supp\n#\n#   This results in a \"check-valgrind\" rule being added. Running `make\n#   check-valgrind` in that directory will recursively run the module's test\n#   suite (`make check`) once for each of the available Valgrind tools (out\n#   of memcheck, helgrind and drd) while the sgcheck will be skipped unless\n#   enabled again on the commandline with --enable-valgrind-sgcheck. The\n#   results for each check will be output to test-suite-$toolname.log. The\n#   target will succeed if there are zero errors and fail otherwise.\n#\n#   Alternatively, a \"check-valgrind-$TOOL\" rule will be added, for $TOOL in\n#   memcheck, helgrind, drd and sgcheck. These are useful because often only\n#   some of those tools can be ran cleanly on a codebase.\n#\n#   The macro supports running with and without libtool.\n#\n# LICENSE\n#\n#   Copyright (c) 2014, 2015, 2016 Philip Withnall <philip.withnall@collabora.co.uk>\n#\n#   Copying and distribution of this file, with or without modification, are\n#   permitted in any medium without royalty provided the copyright notice\n#   and this notice are preserved.  This file is offered as-is, without any\n#   warranty.\n\n#serial 23\n\ndnl Configured tools\nm4_define([valgrind_tool_list], [[memcheck], [helgrind], [drd], [sgcheck]])\nm4_set_add_all([valgrind_exp_tool_set], [sgcheck])\nm4_foreach([vgtool], [valgrind_tool_list],\n           [m4_define([en_dflt_valgrind_]vgtool, [on])])\n\nAC_DEFUN([AX_VALGRIND_DFLT],[\n\tm4_define([en_dflt_valgrind_$1], [$2])\n])dnl\n\nAC_DEFUN([AX_VALGRIND_CHECK],[\n\tAM_EXTRA_RECURSIVE_TARGETS([check-valgrind])\n\tm4_foreach([vgtool], [valgrind_tool_list],\n\t\t[AM_EXTRA_RECURSIVE_TARGETS([check-valgrind-]vgtool)])\n\n\tdnl Check for --enable-valgrind\n\tAC_ARG_ENABLE([valgrind],\n\t              [AS_HELP_STRING([--enable-valgrind], [Whether to enable Valgrind on the unit tests])],\n\t              [enable_valgrind=$enableval],[enable_valgrind=])\n\n\tAS_IF([test \"$enable_valgrind\" != \"no\"],[\n\t\t# Check for Valgrind.\n\t\tAC_CHECK_PROG([VALGRIND],[valgrind],[valgrind])\n\t\tAS_IF([test \"$VALGRIND\" = \"\"],[\n\t\t\tAS_IF([test \"$enable_valgrind\" = \"yes\"],[\n\t\t\t\tAC_MSG_ERROR([Could not find valgrind; either install it or reconfigure with --disable-valgrind])\n\t\t\t],[\n\t\t\t\tenable_valgrind=no\n\t\t\t])\n\t\t],[\n\t\t\tenable_valgrind=yes\n\t\t])\n\t])\n\n\tAM_CONDITIONAL([VALGRIND_ENABLED],[test \"$enable_valgrind\" = \"yes\"])\n\tAC_SUBST([VALGRIND_ENABLED],[$enable_valgrind])\n\n\t# Check for Valgrind tools we care about.\n\t[valgrind_enabled_tools=]\n\tm4_foreach([vgtool],[valgrind_tool_list],[\n\t\tAC_ARG_ENABLE([valgrind-]vgtool,\n\t\t    m4_if(m4_defn([en_dflt_valgrind_]vgtool),[off],dnl\n[AS_HELP_STRING([--enable-valgrind-]vgtool, [Whether to use ]vgtool[ during the Valgrind tests])],dnl\n[AS_HELP_STRING([--disable-valgrind-]vgtool, [Whether to skip ]vgtool[ during the Valgrind tests])]),\n\t\t              [enable_valgrind_]vgtool[=$enableval],\n\t\t              [enable_valgrind_]vgtool[=])\n\t\tAS_IF([test \"$enable_valgrind\" = \"no\"],[\n\t\t\tenable_valgrind_]vgtool[=no],\n\t\t      [test \"$enable_valgrind_]vgtool[\" ]dnl\nm4_if(m4_defn([en_dflt_valgrind_]vgtool), [off], [= \"yes\"], [!= \"no\"]),[\n\t\t\tAC_CACHE_CHECK([for Valgrind tool ]vgtool,\n\t\t\t               [ax_cv_valgrind_tool_]vgtool,[\n\t\t\t\tax_cv_valgrind_tool_]vgtool[=no\n\t\t\t\tm4_set_contains([valgrind_exp_tool_set],vgtool,\n\t\t\t\t    [m4_define([vgtoolx],[exp-]vgtool)],\n\t\t\t\t    [m4_define([vgtoolx],vgtool)])\n\t\t\t\tAS_IF([`$VALGRIND --tool=]vgtoolx[ --help >/dev/null 2>&1`],[\n\t\t\t\t\tax_cv_valgrind_tool_]vgtool[=yes\n\t\t\t\t])\n\t\t\t])\n\t\t\tAS_IF([test \"$ax_cv_valgrind_tool_]vgtool[\" = \"no\"],[\n\t\t\t\tAS_IF([test \"$enable_valgrind_]vgtool[\" = \"yes\"],[\n\t\t\t\t\tAC_MSG_ERROR([Valgrind does not support ]vgtool[; reconfigure with --disable-valgrind-]vgtool)\n\t\t\t\t],[\n\t\t\t\t\tenable_valgrind_]vgtool[=no\n\t\t\t\t])\n\t\t\t],[\n\t\t\t\tenable_valgrind_]vgtool[=yes\n\t\t\t])\n\t\t])\n\t\tAS_IF([test \"$enable_valgrind_]vgtool[\" = \"yes\"],[\n\t\t\tvalgrind_enabled_tools=\"$valgrind_enabled_tools ]m4_bpatsubst(vgtool,[^exp-])[\"\n\t\t])\n\t\tAC_SUBST([ENABLE_VALGRIND_]vgtool,[$enable_valgrind_]vgtool)\n\t])\n\tAC_SUBST([valgrind_tools],[\"]m4_join([ ], valgrind_tool_list)[\"])\n\tAC_SUBST([valgrind_enabled_tools],[$valgrind_enabled_tools])\n\n[VALGRIND_CHECK_RULES='\n# Valgrind check\n#\n# Optional:\n#  - VALGRIND_SUPPRESSIONS_FILES: Space-separated list of Valgrind suppressions\n#    files to load. (Default: empty)\n#  - VALGRIND_FLAGS: General flags to pass to all Valgrind tools.\n#    (Default: --num-callers=30)\n#  - VALGRIND_$toolname_FLAGS: Flags to pass to Valgrind $toolname (one of:\n#    memcheck, helgrind, drd, sgcheck). (Default: various)\n\n# Optional variables\nVALGRIND_SUPPRESSIONS ?= $(addprefix --suppressions=,$(VALGRIND_SUPPRESSIONS_FILES))\nVALGRIND_FLAGS ?= --num-callers=30\nVALGRIND_memcheck_FLAGS ?= --leak-check=full --show-reachable=no\nVALGRIND_helgrind_FLAGS ?= --history-level=approx\nVALGRIND_drd_FLAGS ?=\nVALGRIND_sgcheck_FLAGS ?=\n\n# Internal use\nvalgrind_log_files = $(addprefix test-suite-,$(addsuffix .log,$(valgrind_tools)))\n\nvalgrind_memcheck_flags = --tool=memcheck $(VALGRIND_memcheck_FLAGS)\nvalgrind_helgrind_flags = --tool=helgrind $(VALGRIND_helgrind_FLAGS)\nvalgrind_drd_flags = --tool=drd $(VALGRIND_drd_FLAGS)\nvalgrind_sgcheck_flags = --tool=exp-sgcheck $(VALGRIND_sgcheck_FLAGS)\n\nvalgrind_quiet = $(valgrind_quiet_$(V))\nvalgrind_quiet_ = $(valgrind_quiet_$(AM_DEFAULT_VERBOSITY))\nvalgrind_quiet_0 = --quiet\nvalgrind_v_use   = $(valgrind_v_use_$(V))\nvalgrind_v_use_  = $(valgrind_v_use_$(AM_DEFAULT_VERBOSITY))\nvalgrind_v_use_0 = @echo \"  USE   \" $(patsubst check-valgrind-%-local,%,$''@):;\n\n# Support running with and without libtool.\nifneq ($(LIBTOOL),)\nvalgrind_lt = $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=execute\nelse\nvalgrind_lt =\nendif\n\n# Use recursive makes in order to ignore errors during check\ncheck-valgrind-local:\nifeq ($(VALGRIND_ENABLED),yes)\n\t$(A''M_V_at)$(MAKE) $(AM_MAKEFLAGS) -k \\\n\t\t$(foreach tool, $(valgrind_enabled_tools), check-valgrind-$(tool))\nelse\n\t@echo \"Need to reconfigure with --enable-valgrind\"\nendif\n\n# Valgrind running\nVALGRIND_TESTS_ENVIRONMENT = \\\n\t$(TESTS_ENVIRONMENT) \\\n\tenv VALGRIND=$(VALGRIND) \\\n\tG_SLICE=always-malloc,debug-blocks \\\n\tG_DEBUG=fatal-warnings,fatal-criticals,gc-friendly\n\nVALGRIND_LOG_COMPILER = \\\n\t$(valgrind_lt) \\\n\t$(VALGRIND) $(VALGRIND_SUPPRESSIONS) --error-exitcode=1 $(VALGRIND_FLAGS)\n\ndefine valgrind_tool_rule\ncheck-valgrind-$(1)-local:\nifeq ($$(VALGRIND_ENABLED)-$$(ENABLE_VALGRIND_$(1)),yes-yes)\nifneq ($$(TESTS),)\n\t$$(valgrind_v_use)$$(MAKE) check-TESTS \\\n\t\tTESTS_ENVIRONMENT=\"$$(VALGRIND_TESTS_ENVIRONMENT)\" \\\n\t\tLOG_COMPILER=\"$$(VALGRIND_LOG_COMPILER)\" \\\n\t\tLOG_FLAGS=\"$$(valgrind_$(1)_flags)\" \\\n\t\tTEST_SUITE_LOG=test-suite-$(1).log\nendif\nelse ifeq ($$(VALGRIND_ENABLED),yes)\n\t@echo \"Need to reconfigure with --enable-valgrind-$(1)\"\nelse\n\t@echo \"Need to reconfigure with --enable-valgrind\"\nendif\nendef\n\n$(foreach tool,$(valgrind_tools),$(eval $(call valgrind_tool_rule,$(tool))))\n\nA''M_DISTCHECK_CONFIGURE_FLAGS ?=\nA''M_DISTCHECK_CONFIGURE_FLAGS += --disable-valgrind\n\nMOSTLYCLEANFILES ?=\nMOSTLYCLEANFILES += $(valgrind_log_files)\n\n.PHONY: check-valgrind $(addprefix check-valgrind-,$(valgrind_tools))\n']\n\n\tAC_SUBST([VALGRIND_CHECK_RULES])\n\tm4_ifdef([_AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE([VALGRIND_CHECK_RULES])])\n])"
  },
  {
    "path": "src/auth.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* auth.c\n** strophe XMPP client library -- auth functions and handlers\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express or\n**  implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Authentication function and handlers.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"sasl.h\"\n#include \"sha1.h\"\n\n#ifdef _MSC_VER\n#define strcasecmp _stricmp\n#endif\n\n/* TODO: these should configurable at runtime on a per connection basis  */\n\n#ifndef FEATURES_TIMEOUT\n/** @def FEATURES_TIMEOUT\n *  Time to wait for &lt;stream:features/&gt; stanza.\n */\n#define FEATURES_TIMEOUT 15000 /* 15 seconds */\n#endif\n#ifndef BIND_TIMEOUT\n/** @def BIND_TIMEOUT\n *  Time to wait for &lt;bind/&gt; stanza reply.\n */\n#define BIND_TIMEOUT 15000 /* 15 seconds */\n#endif\n#ifndef SESSION_TIMEOUT\n/** @def SESSION_TIMEOUT\n *  Time to wait for &lt;session/&gt; stanza reply.\n */\n#define SESSION_TIMEOUT 15000 /* 15 seconds */\n#endif\n#ifndef LEGACY_TIMEOUT\n/** @def LEGACY_TIMEOUT\n *  Time to wait for legacy authentication to complete.\n */\n#define LEGACY_TIMEOUT 15000 /* 15 seconds */\n#endif\n#ifndef HANDSHAKE_TIMEOUT\n/** @def HANDSHAKE_TIMEOUT\n *  Time to wait for component authentication to complete\n */\n#define HANDSHAKE_TIMEOUT 15000 /* 15 seconds */\n#endif\n\nstatic void _auth(xmpp_conn_t *conn);\nstatic void _auth_legacy(xmpp_conn_t *conn);\nstatic void _handle_open_compress(xmpp_conn_t *conn);\nstatic void _handle_open_sasl(xmpp_conn_t *conn);\nstatic void _handle_open_tls(xmpp_conn_t *conn);\n\nstatic int _handle_component_auth(xmpp_conn_t *conn);\nstatic int _handle_component_hs_response(xmpp_conn_t *conn,\n                                         xmpp_stanza_t *stanza,\n                                         void *userdata);\n\nstatic int\n_handle_features_sasl(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata);\nstatic int _handle_features_compress(xmpp_conn_t *conn,\n                                     xmpp_stanza_t *stanza,\n                                     void *userdata);\nstatic int\n_handle_sasl_result(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata);\nstatic int _handle_digestmd5_challenge(xmpp_conn_t *conn,\n                                       xmpp_stanza_t *stanza,\n                                       void *userdata);\nstatic int _handle_digestmd5_rspauth(xmpp_conn_t *conn,\n                                     xmpp_stanza_t *stanza,\n                                     void *userdata);\nstatic int _handle_scram_challenge(xmpp_conn_t *conn,\n                                   xmpp_stanza_t *stanza,\n                                   void *userdata);\nstruct scram_user_data;\nstatic int _make_scram_init_msg(struct scram_user_data *scram);\n\nstatic int _handle_missing_features_sasl(xmpp_conn_t *conn, void *userdata);\nstatic int _handle_missing_bind(xmpp_conn_t *conn, void *userdata);\nstatic int\n_handle_bind(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata);\nstatic int\n_handle_session(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata);\nstatic int _handle_missing_session(xmpp_conn_t *conn, void *userdata);\nstatic int _handle_missing_handshake(xmpp_conn_t *conn, void *userdata);\nstatic int _handle_sm(xmpp_conn_t *const conn,\n                      xmpp_stanza_t *const stanza,\n                      void *const userdata);\n\n/* stream:error handler */\nstatic int\n_handle_error(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_stanza_t *child;\n    const char *name;\n\n    UNUSED(userdata);\n\n    /* free old stream error if it's still there */\n    if (conn->stream_error) {\n        xmpp_stanza_release(conn->stream_error->stanza);\n        if (conn->stream_error->text)\n            strophe_free(conn->ctx, conn->stream_error->text);\n        strophe_free(conn->ctx, conn->stream_error);\n    }\n\n    /* create stream error structure */\n    conn->stream_error = (xmpp_stream_error_t *)strophe_alloc(\n        conn->ctx, sizeof(xmpp_stream_error_t));\n\n    conn->stream_error->text = NULL;\n    conn->stream_error->type = XMPP_SE_UNDEFINED_CONDITION;\n\n    if (conn->stream_error) {\n        child = xmpp_stanza_get_children(stanza);\n        do {\n            const char *ns = NULL;\n\n            if (child) {\n                ns = xmpp_stanza_get_ns(child);\n            }\n\n            if (ns && strcmp(ns, XMPP_NS_STREAMS_IETF) == 0) {\n                name = xmpp_stanza_get_name(child);\n                if (strcmp(name, \"text\") == 0) {\n                    if (conn->stream_error->text)\n                        strophe_free(conn->ctx, conn->stream_error->text);\n                    conn->stream_error->text = xmpp_stanza_get_text(child);\n                } else if (strcmp(name, \"bad-format\") == 0)\n                    conn->stream_error->type = XMPP_SE_BAD_FORMAT;\n                else if (strcmp(name, \"bad-namespace-prefix\") == 0)\n                    conn->stream_error->type = XMPP_SE_BAD_NS_PREFIX;\n                else if (strcmp(name, \"conflict\") == 0)\n                    conn->stream_error->type = XMPP_SE_CONFLICT;\n                else if (strcmp(name, \"connection-timeout\") == 0)\n                    conn->stream_error->type = XMPP_SE_CONN_TIMEOUT;\n                else if (strcmp(name, \"host-gone\") == 0)\n                    conn->stream_error->type = XMPP_SE_HOST_GONE;\n                else if (strcmp(name, \"host-unknown\") == 0)\n                    conn->stream_error->type = XMPP_SE_HOST_UNKNOWN;\n                else if (strcmp(name, \"improper-addressing\") == 0)\n                    conn->stream_error->type = XMPP_SE_IMPROPER_ADDR;\n                else if (strcmp(name, \"internal-server-error\") == 0)\n                    conn->stream_error->type = XMPP_SE_INTERNAL_SERVER_ERROR;\n                else if (strcmp(name, \"invalid-from\") == 0)\n                    conn->stream_error->type = XMPP_SE_INVALID_FROM;\n                else if (strcmp(name, \"invalid-id\") == 0)\n                    conn->stream_error->type = XMPP_SE_INVALID_ID;\n                else if (strcmp(name, \"invalid-namespace\") == 0)\n                    conn->stream_error->type = XMPP_SE_INVALID_NS;\n                else if (strcmp(name, \"invalid-xml\") == 0)\n                    conn->stream_error->type = XMPP_SE_INVALID_XML;\n                else if (strcmp(name, \"not-authorized\") == 0)\n                    conn->stream_error->type = XMPP_SE_NOT_AUTHORIZED;\n                else if (strcmp(name, \"policy-violation\") == 0)\n                    conn->stream_error->type = XMPP_SE_POLICY_VIOLATION;\n                else if (strcmp(name, \"remote-connection-failed\") == 0)\n                    conn->stream_error->type = XMPP_SE_REMOTE_CONN_FAILED;\n                else if (strcmp(name, \"resource-constraint\") == 0)\n                    conn->stream_error->type = XMPP_SE_RESOURCE_CONSTRAINT;\n                else if (strcmp(name, \"restricted-xml\") == 0)\n                    conn->stream_error->type = XMPP_SE_RESTRICTED_XML;\n                else if (strcmp(name, \"see-other-host\") == 0)\n                    conn->stream_error->type = XMPP_SE_SEE_OTHER_HOST;\n                else if (strcmp(name, \"system-shutdown\") == 0)\n                    conn->stream_error->type = XMPP_SE_SYSTEM_SHUTDOWN;\n                else if (strcmp(name, \"undefined-condition\") == 0)\n                    conn->stream_error->type = XMPP_SE_UNDEFINED_CONDITION;\n                else if (strcmp(name, \"unsupported-encoding\") == 0)\n                    conn->stream_error->type = XMPP_SE_UNSUPPORTED_ENCODING;\n                else if (strcmp(name, \"unsupported-stanza-type\") == 0)\n                    conn->stream_error->type = XMPP_SE_UNSUPPORTED_STANZA_TYPE;\n                else if (strcmp(name, \"unsupported-version\") == 0)\n                    conn->stream_error->type = XMPP_SE_UNSUPPORTED_VERSION;\n                else if (strcmp(name, \"xml-not-well-formed\") == 0)\n                    conn->stream_error->type = XMPP_SE_XML_NOT_WELL_FORMED;\n            }\n        } while ((child = xmpp_stanza_get_next(child)));\n\n        conn->stream_error->stanza = xmpp_stanza_clone(stanza);\n    }\n\n    return 1;\n}\n\n/* stream:features handlers */\nstatic int _handle_missing_features(xmpp_conn_t *conn, void *userdata)\n{\n    UNUSED(userdata);\n\n    strophe_debug(conn->ctx, \"xmpp\", \"didn't get stream features\");\n\n    /* legacy auth will be attempted */\n    _auth(conn);\n\n    return 0;\n}\n\ntypedef void (*text_handler)(xmpp_conn_t *conn, const char *text);\nstatic void _foreach_child(xmpp_conn_t *conn,\n                           xmpp_stanza_t *parent,\n                           const char *name,\n                           text_handler hndl)\n{\n    xmpp_stanza_t *children;\n    for (children = xmpp_stanza_get_children(parent); children;\n         children = xmpp_stanza_get_next(children)) {\n        const char *child_name = xmpp_stanza_get_name(children);\n        if (child_name && strcmp(child_name, name) == 0) {\n            char *text = xmpp_stanza_get_text(children);\n            if (text == NULL)\n                continue;\n\n            hndl(conn, text);\n\n            strophe_free(conn->ctx, text);\n        }\n    }\n}\n\nstatic void _handle_sasl_children(xmpp_conn_t *conn, const char *text)\n{\n    if (strcasecmp(text, \"PLAIN\") == 0) {\n        conn->sasl_support |= SASL_MASK_PLAIN;\n    } else if (strcasecmp(text, \"EXTERNAL\") == 0 &&\n               (conn->tls_client_cert || conn->tls_client_key)) {\n        conn->sasl_support |= SASL_MASK_EXTERNAL;\n    } else if (strcasecmp(text, \"DIGEST-MD5\") == 0) {\n        conn->sasl_support |= SASL_MASK_DIGESTMD5;\n    } else if (strcasecmp(text, \"ANONYMOUS\") == 0) {\n        conn->sasl_support |= SASL_MASK_ANONYMOUS;\n    } else {\n        size_t n;\n        for (n = 0; n < scram_algs_num; ++n) {\n            if (strcasecmp(text, scram_algs[n]->scram_name) == 0) {\n                conn->sasl_support |= scram_algs[n]->mask;\n                break;\n            }\n        }\n    }\n}\n\nstatic int\n_handle_features(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_stanza_t *child;\n\n    UNUSED(userdata);\n\n    /* remove the handler that detects missing stream:features */\n    xmpp_timed_handler_delete(conn, _handle_missing_features);\n\n    /* check for TLS */\n    if (!conn->secured) {\n        if (!conn->tls_disabled) {\n            if (xmpp_stanza_get_child_by_name_and_ns(stanza, \"starttls\",\n                                                     XMPP_NS_TLS)) {\n                conn->tls_support = 1;\n            }\n        } else {\n            conn->tls_support = 0;\n        }\n    }\n\n    /* check for SASL */\n    child = xmpp_stanza_get_child_by_name_and_ns(stanza, \"mechanisms\",\n                                                 XMPP_NS_SASL);\n    if (child) {\n        _foreach_child(conn, child, \"mechanism\", _handle_sasl_children);\n    }\n\n    /* Disable PLAIN when other secure mechanisms are supported */\n    if (conn->sasl_support & ~(SASL_MASK_PLAIN | SASL_MASK_ANONYMOUS))\n        conn->sasl_support &= ~SASL_MASK_PLAIN;\n\n    _auth(conn);\n\n    return 0;\n}\n\n/* returns the correct auth id for a component or a client.\n * returned string must be freed by caller */\nstatic char *_get_authid(xmpp_conn_t *conn)\n{\n    char *authid = NULL;\n\n    if (conn->type == XMPP_CLIENT) {\n        /* authid is the node portion of jid */\n        if (!conn->jid)\n            return NULL;\n        authid = xmpp_jid_node(conn->ctx, conn->jid);\n    }\n\n    return authid;\n}\n\nstatic int _handle_proceedtls_default(xmpp_conn_t *conn,\n                                      xmpp_stanza_t *stanza,\n                                      void *userdata)\n{\n    const char *name;\n\n    UNUSED(userdata);\n\n    name = xmpp_stanza_get_name(stanza);\n    strophe_debug(conn->ctx, \"xmpp\", \"handle proceedtls called for %s\", name);\n\n    if (strcmp(name, \"proceed\") == 0) {\n        strophe_debug(conn->ctx, \"xmpp\", \"proceeding with TLS\");\n\n        if (conn_tls_start(conn) == 0) {\n            conn_prepare_reset(conn, _handle_open_tls);\n            conn_open_stream(conn);\n        } else {\n            /* failed tls spoils the connection, so disconnect */\n            xmpp_disconnect(conn);\n        }\n    }\n\n    return 0;\n}\n\nstatic int\n_handle_sasl_result(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    const char *name;\n\n    name = xmpp_stanza_get_name(stanza);\n\n    /* the server should send a <success> or <failure> stanza */\n    if (strcmp(name, \"failure\") == 0) {\n        strophe_debug(conn->ctx, \"xmpp\", \"SASL %s auth failed\",\n                      (char *)userdata);\n\n        /* fall back to next auth method */\n        _auth(conn);\n    } else if (strcmp(name, \"success\") == 0) {\n        /* SASL auth successful, we need to restart the stream */\n        strophe_debug(conn->ctx, \"xmpp\", \"SASL %s auth successful\",\n                      (char *)userdata);\n\n        /* reset parser */\n        conn_prepare_reset(conn, conn->compression.allowed\n                                     ? _handle_open_compress\n                                     : _handle_open_sasl);\n\n        /* send stream tag */\n        conn_open_stream(conn);\n    } else {\n        /* got unexpected reply */\n        strophe_error(conn->ctx, \"xmpp\",\n                      \"Got unexpected reply to SASL %s authentication.\",\n                      (char *)userdata);\n        xmpp_disconnect(conn);\n    }\n\n    return 0;\n}\n\n/* handle the challenge phase of digest auth */\nstatic int _handle_digestmd5_challenge(xmpp_conn_t *conn,\n                                       xmpp_stanza_t *stanza,\n                                       void *userdata)\n{\n    char *text;\n    char *response;\n    xmpp_stanza_t *auth, *authdata;\n    const char *name;\n\n    UNUSED(userdata);\n\n    name = xmpp_stanza_get_name(stanza);\n    strophe_debug(conn->ctx, \"xmpp\",\n                  \"handle digest-md5 (challenge) called for %s\", name);\n\n    if (strcmp(name, \"challenge\") == 0) {\n        text = xmpp_stanza_get_text(stanza);\n        response = sasl_digest_md5(conn->ctx, text, conn->jid, conn->pass);\n        if (!response) {\n            disconnect_mem_error(conn);\n            return 0;\n        }\n        strophe_free(conn->ctx, text);\n\n        auth = xmpp_stanza_new(conn->ctx);\n        if (!auth) {\n            disconnect_mem_error(conn);\n            return 0;\n        }\n        xmpp_stanza_set_name(auth, \"response\");\n        xmpp_stanza_set_ns(auth, XMPP_NS_SASL);\n\n        authdata = xmpp_stanza_new(conn->ctx);\n        if (!authdata) {\n            disconnect_mem_error(conn);\n            return 0;\n        }\n\n        xmpp_stanza_set_text(authdata, response);\n        strophe_free(conn->ctx, response);\n\n        xmpp_stanza_add_child_ex(auth, authdata, 0);\n\n        handler_add(conn, _handle_digestmd5_rspauth, XMPP_NS_SASL, NULL, NULL,\n                    NULL);\n\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n\n    } else {\n        return _handle_sasl_result(conn, stanza, \"DIGEST-MD5\");\n    }\n\n    /* remove ourselves */\n    return 0;\n}\n\n/* handle the rspauth phase of digest auth */\nstatic int _handle_digestmd5_rspauth(xmpp_conn_t *conn,\n                                     xmpp_stanza_t *stanza,\n                                     void *userdata)\n{\n    xmpp_stanza_t *auth;\n    const char *name;\n\n    UNUSED(userdata);\n\n    name = xmpp_stanza_get_name(stanza);\n    strophe_debug(conn->ctx, \"xmpp\",\n                  \"handle digest-md5 (rspauth) called for %s\", name);\n\n    if (strcmp(name, \"challenge\") == 0) {\n        /* assume it's an rspauth response */\n        auth = xmpp_stanza_new(conn->ctx);\n        if (!auth) {\n            disconnect_mem_error(conn);\n            return 0;\n        }\n        xmpp_stanza_set_name(auth, \"response\");\n        xmpp_stanza_set_ns(auth, XMPP_NS_SASL);\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n    } else {\n        return _handle_sasl_result(conn, stanza, \"DIGEST-MD5\");\n    }\n\n    return 1;\n}\n\nstruct scram_user_data {\n    xmpp_conn_t *conn;\n    int sasl_plus;\n    char *scram_init;\n    char *channel_binding;\n    const char *first_bare;\n    const struct hash_alg *alg;\n};\n\n/* handle the challenge phase of SCRAM-SHA-1 auth */\nstatic int _handle_scram_challenge(xmpp_conn_t *conn,\n                                   xmpp_stanza_t *stanza,\n                                   void *userdata)\n{\n    char *text;\n    char *response;\n    xmpp_stanza_t *auth;\n    xmpp_stanza_t *authdata;\n    const char *name;\n    char *challenge;\n    struct scram_user_data *scram_ctx = (struct scram_user_data *)userdata;\n    int rc;\n\n    name = xmpp_stanza_get_name(stanza);\n    strophe_debug(conn->ctx, \"xmpp\", \"handle %s (challenge) called for %s\",\n                  scram_ctx->alg->scram_name, name);\n\n    if (strcmp(name, \"challenge\") == 0) {\n        text = xmpp_stanza_get_text(stanza);\n        if (!text)\n            goto err;\n\n        challenge = xmpp_base64_decode_str(conn->ctx, text, strlen(text));\n        strophe_free(conn->ctx, text);\n        if (!challenge)\n            goto err;\n\n        response =\n            sasl_scram(conn->ctx, scram_ctx->alg, scram_ctx->channel_binding,\n                       challenge, scram_ctx->first_bare, conn->jid, conn->pass);\n        strophe_free(conn->ctx, challenge);\n        if (!response)\n            goto err;\n\n        auth = xmpp_stanza_new(conn->ctx);\n        if (!auth)\n            goto err_free_response;\n        xmpp_stanza_set_name(auth, \"response\");\n        xmpp_stanza_set_ns(auth, XMPP_NS_SASL);\n\n        authdata = xmpp_stanza_new(conn->ctx);\n        if (!authdata)\n            goto err_release_auth;\n        xmpp_stanza_set_text(authdata, response);\n        strophe_free(conn->ctx, response);\n\n        xmpp_stanza_add_child_ex(auth, authdata, 0);\n\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n\n        rc = 1; /* Keep handler */\n    } else {\n        /*\n         * Free scram_ctx after calling _handle_sasl_result(). If authentication\n         * fails, we want to try other mechanism which may be different SCRAM\n         * mechanism. If we freed scram_ctx before the function, _auth() would\n         * be able to allocate new scram_ctx object with the same address and\n         * handler_add() would consider new SCRAM handler as duplicate, because\n         * current handler is not removed yet. As result, libstrophe wouldn't\n         * handle incoming challenge stanza.\n         */\n        rc = _handle_sasl_result(conn, stanza,\n                                 (void *)scram_ctx->alg->scram_name);\n        strophe_free_and_null(conn->ctx, scram_ctx->channel_binding);\n        strophe_free_and_null(conn->ctx, scram_ctx->scram_init);\n        strophe_free(conn->ctx, scram_ctx);\n    }\n\n    return rc;\n\nerr_release_auth:\n    xmpp_stanza_release(auth);\nerr_free_response:\n    strophe_free(conn->ctx, response);\nerr:\n    strophe_free_and_null(conn->ctx, scram_ctx->channel_binding);\n    strophe_free_and_null(conn->ctx, scram_ctx->scram_init);\n    strophe_free(conn->ctx, scram_ctx);\n    disconnect_mem_error(conn);\n    return 0;\n}\n\nstatic int _make_scram_init_msg(struct scram_user_data *scram)\n{\n    xmpp_conn_t *conn = scram->conn;\n    xmpp_ctx_t *ctx = conn->ctx;\n    const void *binding_data;\n    const char *binding_type;\n    char *node, *message;\n    size_t message_len, binding_type_len = 0, binding_data_len;\n    int l, is_secured = xmpp_conn_is_secured(conn);\n    /* This buffer must be able to hold:\n     * \"p=<10 bytes binding type>,,<36 bytes binding data>\"\n     * + alignment */\n    char buf[56];\n\n    if (scram->sasl_plus) {\n        if (!is_secured) {\n            strophe_error(\n                ctx, \"xmpp\",\n                \"SASL: Server requested a -PLUS variant to authenticate, \"\n                \"but the connection is not secured. This is an error on \"\n                \"the server side we can't do anything about.\");\n            return -1;\n        }\n        if (tls_init_channel_binding(conn->tls, &binding_type,\n                                     &binding_type_len)) {\n            return -1;\n        }\n        /* directly account for the '=' char in 'p=<binding-type>' */\n        binding_type_len += 1;\n    }\n\n    node = xmpp_jid_node(ctx, conn->jid);\n    if (!node) {\n        return -1;\n    }\n    /* 32 bytes nonce is enough */\n    xmpp_rand_nonce(ctx->rand, buf, 33);\n    message_len = strlen(node) + strlen(buf) + 8 + binding_type_len + 1;\n    message = strophe_alloc(ctx, message_len);\n    if (!message) {\n        goto err_node;\n    }\n    /* increase length to account for 'y,,', 'n,,' or 'p,,'.\n     * In the 'p' case the '=' sign has already been accounted for above.\n     */\n    binding_type_len += 3;\n    if (scram->sasl_plus) {\n        l = strophe_snprintf(message, message_len, \"p=%s,,n=%s,r=%s\",\n                             binding_type, node, buf);\n    } else {\n        l = strophe_snprintf(message, message_len, \"%c,,n=%s,r=%s\",\n                             is_secured ? 'y' : 'n', node, buf);\n    }\n    if (l < 0 || (size_t)l >= message_len) {\n        goto err_msg;\n    }\n    if (binding_type_len > sizeof(buf)) {\n        goto err_msg;\n    }\n    /* Make `first_bare` point to the 'n' of 'n=<node>' of the\n     * client-first-message */\n    scram->first_bare = message + binding_type_len;\n    memcpy(buf, message, binding_type_len);\n    if (scram->sasl_plus) {\n        binding_data =\n            tls_get_channel_binding_data(conn->tls, &binding_data_len);\n        if (!binding_data) {\n            goto err_msg;\n        }\n        if (binding_data_len > sizeof(buf) - binding_type_len) {\n            strophe_error(ctx, \"xmpp\", \"Channel binding data is too long (%zu)\",\n                          binding_data_len);\n            goto err_msg;\n        }\n        memcpy(&buf[binding_type_len], binding_data, binding_data_len);\n        binding_type_len += binding_data_len;\n    }\n    scram->channel_binding =\n        xmpp_base64_encode(ctx, (void *)buf, binding_type_len);\n    memset(buf, 0, binding_type_len);\n    strophe_free(ctx, node);\n    scram->scram_init = message;\n\n    return 0;\n\nerr_msg:\n    strophe_free(ctx, message);\nerr_node:\n    strophe_free(ctx, node);\n    return -1;\n}\n\nstatic xmpp_stanza_t *_make_starttls(xmpp_conn_t *conn)\n{\n    xmpp_stanza_t *starttls;\n\n    /* build start stanza */\n    starttls = xmpp_stanza_new(conn->ctx);\n    if (starttls) {\n        xmpp_stanza_set_name(starttls, \"starttls\");\n        xmpp_stanza_set_ns(starttls, XMPP_NS_TLS);\n    }\n\n    return starttls;\n}\n\nstatic xmpp_stanza_t *_make_sasl_auth(xmpp_conn_t *conn, const char *mechanism)\n{\n    xmpp_stanza_t *auth;\n\n    /* build auth stanza */\n    auth = xmpp_stanza_new(conn->ctx);\n    if (auth) {\n        xmpp_stanza_set_name(auth, \"auth\");\n        xmpp_stanza_set_ns(auth, XMPP_NS_SASL);\n        xmpp_stanza_set_attribute(auth, \"mechanism\", mechanism);\n    }\n\n    return auth;\n}\n\n/* authenticate the connection\n * this may get called multiple times.  if any auth method fails,\n * this will get called again until one auth method succeeds or every\n * method fails\n */\nstatic void _auth(xmpp_conn_t *conn)\n{\n    xmpp_stanza_t *auth;\n    xmpp_stanza_t *authdata;\n    struct scram_user_data *scram_ctx;\n    char *authid;\n    char *str;\n    int anonjid;\n\n    /* if there is no node in conn->jid, we assume anonymous connect */\n    str = xmpp_jid_node(conn->ctx, conn->jid);\n    if (str == NULL) {\n        anonjid = 1;\n    } else {\n        strophe_free(conn->ctx, str);\n        anonjid = 0;\n    }\n\n    if (conn->tls_support) {\n        tls_t *tls = tls_new(conn);\n\n        /* If we couldn't init tls, it isn't there, so go on */\n        if (!tls) {\n            conn->tls_support = 0;\n            _auth(conn);\n            return;\n        } else {\n            tls_free(tls);\n        }\n\n        auth = _make_starttls(conn);\n\n        if (!auth) {\n            disconnect_mem_error(conn);\n            return;\n        }\n\n        handler_add(conn, _handle_proceedtls_default, XMPP_NS_TLS, NULL, NULL,\n                    NULL);\n\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n\n        /* TLS was tried, unset flag */\n        conn->tls_support = 0;\n        /* _auth() will be called later */\n        return;\n    }\n\n    if (conn->tls_mandatory && !xmpp_conn_is_secured(conn)) {\n        strophe_error(conn->ctx, \"xmpp\",\n                      \"TLS is not supported, but set as \"\n                      \"mandatory for this connection\");\n        conn_disconnect(conn);\n        return;\n    }\n\n    if (anonjid && (conn->sasl_support & SASL_MASK_ANONYMOUS)) {\n        /* some crap here */\n        auth = _make_sasl_auth(conn, \"ANONYMOUS\");\n        if (!auth) {\n            disconnect_mem_error(conn);\n            return;\n        }\n\n        handler_add(conn, _handle_sasl_result, XMPP_NS_SASL, NULL, NULL,\n                    \"ANONYMOUS\");\n\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n\n        /* SASL ANONYMOUS was tried, unset flag */\n        conn->sasl_support &= ~SASL_MASK_ANONYMOUS;\n    } else if (conn->sasl_support & SASL_MASK_EXTERNAL) {\n        /* more crap here */\n        auth = _make_sasl_auth(conn, \"EXTERNAL\");\n        if (!auth) {\n            disconnect_mem_error(conn);\n            return;\n        }\n\n        authdata = xmpp_stanza_new(conn->ctx);\n        if (!authdata) {\n            xmpp_stanza_release(auth);\n            disconnect_mem_error(conn);\n            return;\n        }\n        str = tls_id_on_xmppaddr(conn, 0);\n        if (!str || (tls_id_on_xmppaddr_num(conn) == 1 &&\n                     strcmp(str, conn->jid) == 0)) {\n            xmpp_stanza_set_text(authdata, \"=\");\n        } else {\n            strophe_free(conn->ctx, str);\n            str = xmpp_base64_encode(conn->ctx, (void *)conn->jid,\n                                     strlen(conn->jid));\n            if (!str) {\n                xmpp_stanza_release(authdata);\n                xmpp_stanza_release(auth);\n                disconnect_mem_error(conn);\n                return;\n            }\n            xmpp_stanza_set_text(authdata, str);\n        }\n        strophe_free(conn->ctx, str);\n\n        xmpp_stanza_add_child_ex(auth, authdata, 0);\n\n        handler_add(conn, _handle_sasl_result, XMPP_NS_SASL, NULL, NULL,\n                    \"EXTERNAL\");\n\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n\n        /* SASL EXTERNAL was tried, unset flag */\n        conn->sasl_support &= ~SASL_MASK_EXTERNAL;\n    } else if (anonjid) {\n        strophe_error(conn->ctx, \"auth\",\n                      \"No node in JID, and SASL ANONYMOUS unsupported.\");\n        xmpp_disconnect(conn);\n    } else if (conn->pass == NULL) {\n        strophe_error(\n            conn->ctx, \"auth\",\n            \"Password hasn't been set, and SASL ANONYMOUS unsupported.\");\n        xmpp_disconnect(conn);\n    } else if (conn->sasl_support & SASL_MASK_SCRAM) {\n        size_t n;\n        scram_ctx = strophe_alloc(conn->ctx, sizeof(*scram_ctx));\n        memset(scram_ctx, 0, sizeof(*scram_ctx));\n        for (n = 0; n < scram_algs_num; ++n) {\n            if (conn->sasl_support & scram_algs[n]->mask) {\n                scram_ctx->alg = scram_algs[n];\n                break;\n            }\n        }\n\n        auth = _make_sasl_auth(conn, scram_ctx->alg->scram_name);\n        if (!auth) {\n            disconnect_mem_error(conn);\n            return;\n        }\n\n        scram_ctx->conn = conn;\n        scram_ctx->sasl_plus =\n            scram_ctx->alg->mask & SASL_MASK_SCRAM_PLUS ? 1 : 0;\n        if (_make_scram_init_msg(scram_ctx)) {\n            strophe_free(conn->ctx, scram_ctx);\n            xmpp_stanza_release(auth);\n            disconnect_mem_error(conn);\n            return;\n        }\n\n        str = xmpp_base64_encode(conn->ctx,\n                                 (unsigned char *)scram_ctx->scram_init,\n                                 strlen(scram_ctx->scram_init));\n        if (!str) {\n            strophe_free(conn->ctx, scram_ctx->scram_init);\n            strophe_free(conn->ctx, scram_ctx);\n            xmpp_stanza_release(auth);\n            disconnect_mem_error(conn);\n            return;\n        }\n\n        authdata = xmpp_stanza_new(conn->ctx);\n        if (!authdata) {\n            strophe_free(conn->ctx, str);\n            strophe_free(conn->ctx, scram_ctx->scram_init);\n            strophe_free(conn->ctx, scram_ctx);\n            xmpp_stanza_release(auth);\n            disconnect_mem_error(conn);\n            return;\n        }\n        xmpp_stanza_set_text(authdata, str);\n        strophe_free(conn->ctx, str);\n        xmpp_stanza_add_child_ex(auth, authdata, 0);\n\n        handler_add(conn, _handle_scram_challenge, XMPP_NS_SASL, NULL, NULL,\n                    (void *)scram_ctx);\n\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n\n        /* SASL algorithm was tried, unset flag */\n        conn->sasl_support &= ~scram_ctx->alg->mask;\n    } else if (conn->sasl_support & SASL_MASK_DIGESTMD5) {\n        auth = _make_sasl_auth(conn, \"DIGEST-MD5\");\n        if (!auth) {\n            disconnect_mem_error(conn);\n            return;\n        }\n\n        handler_add(conn, _handle_digestmd5_challenge, XMPP_NS_SASL, NULL, NULL,\n                    NULL);\n\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n\n        /* SASL DIGEST-MD5 was tried, unset flag */\n        conn->sasl_support &= ~SASL_MASK_DIGESTMD5;\n    } else if (conn->sasl_support & SASL_MASK_PLAIN) {\n        auth = _make_sasl_auth(conn, \"PLAIN\");\n        if (!auth) {\n            disconnect_mem_error(conn);\n            return;\n        }\n        authdata = xmpp_stanza_new(conn->ctx);\n        if (!authdata) {\n            disconnect_mem_error(conn);\n            return;\n        }\n        authid = _get_authid(conn);\n        if (!authid) {\n            disconnect_mem_error(conn);\n            return;\n        }\n        str = sasl_plain(conn->ctx, authid, conn->pass);\n        if (!str) {\n            disconnect_mem_error(conn);\n            return;\n        }\n        xmpp_stanza_set_text(authdata, str);\n        strophe_free(conn->ctx, str);\n        strophe_free(conn->ctx, authid);\n\n        xmpp_stanza_add_child_ex(auth, authdata, 0);\n\n        handler_add(conn, _handle_sasl_result, XMPP_NS_SASL, NULL, NULL,\n                    \"PLAIN\");\n\n        send_stanza(conn, auth, XMPP_QUEUE_STROPHE);\n\n        /* SASL PLAIN was tried */\n        conn->sasl_support &= ~SASL_MASK_PLAIN;\n    } else if (conn->type == XMPP_CLIENT && conn->auth_legacy_enabled) {\n        /* legacy client authentication */\n        _auth_legacy(conn);\n    } else {\n        strophe_error(conn->ctx, \"auth\",\n                      \"Cannot authenticate with known methods\");\n        xmpp_disconnect(conn);\n    }\n}\n\nstatic void _stream_negotiation_success(xmpp_conn_t *conn)\n{\n    tls_clear_password_cache(conn);\n    conn->stream_negotiation_completed = 1;\n    /* call connection handler */\n    conn->conn_handler(conn, XMPP_CONN_CONNECT, 0, NULL, conn->userdata);\n}\n\n/** Set up handlers at stream start.\n *  This function is called internally to Strophe for handling the opening\n *  of an XMPP stream.  It's called by the parser when a stream is opened\n *  or reset, and adds the initial handlers for <stream:error/> and\n *  <stream:features/>.  This function is not intended for use outside\n *  of Strophe.\n *\n *  @param conn a Strophe connection object\n */\nvoid auth_handle_open(xmpp_conn_t *conn)\n{\n    /* reset all timed handlers */\n    handler_reset_timed(conn, 0);\n\n    /* setup handler for stream:error, we will keep this handler\n     * for reopened streams until connection is disconnected */\n    handler_add(conn, _handle_error, XMPP_NS_STREAMS, \"error\", NULL, NULL);\n\n    /* setup handlers for incoming <stream:features> */\n    handler_add(conn, _handle_features, XMPP_NS_STREAMS, \"features\", NULL,\n                NULL);\n    handler_add_timed(conn, _handle_missing_features, FEATURES_TIMEOUT, NULL);\n}\n\n/* called when stream:stream tag received after TLS establishment */\nstatic void _handle_open_tls(xmpp_conn_t *conn)\n{\n    /* setup handlers for incoming <stream:features> */\n    handler_add(conn, _handle_features, XMPP_NS_STREAMS, \"features\", NULL,\n                NULL);\n    handler_add_timed(conn, _handle_missing_features, FEATURES_TIMEOUT, NULL);\n}\n\n/* called when stream:stream tag received after SASL auth */\nstatic void _handle_open_sasl(xmpp_conn_t *conn)\n{\n    strophe_debug(conn->ctx, \"xmpp\", \"Reopened stream successfully.\");\n\n    /* setup stream:features handlers */\n    handler_add(conn, _handle_features_sasl, XMPP_NS_STREAMS, \"features\", NULL,\n                NULL);\n    handler_add_timed(conn, _handle_missing_features_sasl, FEATURES_TIMEOUT,\n                      NULL);\n}\n\n/* called when stream:stream tag received after compression has been enabled */\nstatic void _handle_open_compress(xmpp_conn_t *conn)\n{\n    strophe_debug(conn->ctx, \"xmpp\", \"Reopened stream successfully.\");\n\n    /* setup stream:features handlers */\n    handler_add(conn, _handle_features_compress, XMPP_NS_STREAMS, \"features\",\n                NULL, NULL);\n    handler_add_timed(conn, _handle_missing_features, FEATURES_TIMEOUT, NULL);\n}\n\nstatic int _do_bind(xmpp_conn_t *conn, xmpp_stanza_t *bind)\n{\n    xmpp_stanza_t *iq, *res, *text;\n    char *resource;\n\n    /* setup response handlers */\n    handler_add_id(conn, _handle_bind, \"_xmpp_bind1\", NULL);\n    handler_add_timed(conn, _handle_missing_bind, BIND_TIMEOUT, NULL);\n\n    /* send bind request */\n    iq = xmpp_iq_new(conn->ctx, \"set\", \"_xmpp_bind1\");\n    if (!iq) {\n        xmpp_stanza_release(bind);\n        disconnect_mem_error(conn);\n        return 0;\n    }\n\n    /* request a specific resource if we have one */\n    resource = xmpp_jid_resource(conn->ctx, conn->jid);\n    if ((resource != NULL) && (strlen(resource) == 0)) {\n        /* jabberd2 doesn't handle an empty resource */\n        strophe_free(conn->ctx, resource);\n        resource = NULL;\n    }\n\n    /* if we have a resource to request, do it. otherwise the\n       server will assign us one */\n    if (resource) {\n        res = xmpp_stanza_new(conn->ctx);\n        if (!res) {\n            xmpp_stanza_release(bind);\n            xmpp_stanza_release(iq);\n            disconnect_mem_error(conn);\n            return 0;\n        }\n        xmpp_stanza_set_name(res, \"resource\");\n        text = xmpp_stanza_new(conn->ctx);\n        if (!text) {\n            xmpp_stanza_release(res);\n            xmpp_stanza_release(bind);\n            xmpp_stanza_release(iq);\n            disconnect_mem_error(conn);\n            return 0;\n        }\n        xmpp_stanza_set_text(text, resource);\n        xmpp_stanza_add_child_ex(res, text, 0);\n        xmpp_stanza_add_child_ex(bind, res, 0);\n        strophe_free(conn->ctx, resource);\n    }\n\n    xmpp_stanza_add_child_ex(iq, bind, 0);\n\n    /* send bind request */\n    send_stanza(conn, iq, XMPP_QUEUE_STROPHE);\n    return 0;\n}\n\nstatic int _handle_compress_result(xmpp_conn_t *const conn,\n                                   xmpp_stanza_t *const stanza,\n                                   void *const userdata)\n{\n    const char *name = xmpp_stanza_get_name(stanza);\n\n    UNUSED(userdata);\n\n    if (!name)\n        return 0;\n    if (strcmp(name, \"compressed\") == 0) {\n        /* Stream compression enabled, we need to restart the stream */\n        strophe_debug(conn->ctx, \"xmpp\", \"Stream compression enabled\");\n\n        /* reset parser */\n        conn_prepare_reset(conn, _handle_open_sasl);\n\n        /* make compression effective */\n        compression_init(conn);\n\n        /* send stream tag */\n        conn_open_stream(conn);\n    }\n    return 0;\n}\n\nstatic int _handle_features_compress(xmpp_conn_t *conn,\n                                     xmpp_stanza_t *stanza,\n                                     void *userdata)\n{\n    const char *compress = \"<compress xmlns='\" XMPP_NS_COMPRESSION\n                           \"'><method>zlib</method></compress>\";\n    xmpp_stanza_t *child;\n\n    /* remove missing features handler */\n    xmpp_timed_handler_delete(conn, _handle_missing_features);\n\n    /* check for compression */\n    child = xmpp_stanza_get_child_by_name_and_ns(stanza, \"compression\",\n                                                 XMPP_NS_FEATURE_COMPRESSION);\n    if (conn->compression.allowed && child) {\n        _foreach_child(conn, child, \"method\",\n                       compression_handle_feature_children);\n    }\n\n    if (conn->compression.supported) {\n        send_raw(conn, compress, strlen(compress), XMPP_QUEUE_STROPHE, NULL);\n        handler_add(conn, _handle_compress_result, XMPP_NS_COMPRESSION, NULL,\n                    NULL, NULL);\n    } else {\n        return _handle_features_sasl(conn, stanza, userdata);\n    }\n\n    return 0;\n}\n\nstatic int\n_handle_features_sasl(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_stanza_t *bind, *session;\n    xmpp_stanza_t *resume;\n    char h[11];\n\n    UNUSED(userdata);\n\n    /* Remove missing features handler */\n    xmpp_timed_handler_delete(conn, _handle_missing_features_sasl);\n\n    /* Check whether resource binding is required */\n    bind = xmpp_stanza_get_child_by_name_and_ns(stanza, \"bind\", XMPP_NS_BIND);\n    if (bind) {\n        conn->bind_required = 1;\n        bind = xmpp_stanza_copy(bind);\n        if (!bind) {\n            disconnect_mem_error(conn);\n            return 0;\n        }\n    } else {\n        conn->bind_required = 0;\n    }\n\n    /* Check whether session establishment is required.\n     *\n     * The mechanism is deprecated, but we still support it.\n     *\n     * RFC3921 contains Ch. 3 \"Session Establishment\".\n     *\n     * RFC6121 removes this and explains in Ch. 1.4:\n     * \"Interoperability Note: [...] Implementation and deployment experience\n     * has shown that this additional step is unnecessary. [...]\" */\n    session = xmpp_stanza_get_child_by_name_and_ns(stanza, \"session\",\n                                                   XMPP_NS_SESSION);\n    if (session) {\n        conn->session_required =\n            xmpp_stanza_get_child_by_name(session, \"optional\") == NULL;\n    }\n\n    /* Check stream-management support */\n    if (xmpp_stanza_get_child_by_name_and_ns(stanza, \"sm\", XMPP_NS_SM)) {\n        conn->sm_state->sm_support = 1;\n    }\n\n    /* We are expecting either <bind/> and optionally <session/> since this is a\n       XMPP style connection or we <resume/> the previous session */\n\n    /* Check whether we can <resume/> the previous session */\n    if (!conn->sm_disable && conn->sm_state->can_resume &&\n        conn->sm_state->previd && conn->sm_state->bound_jid) {\n        resume = xmpp_stanza_new(conn->ctx);\n        if (!resume) {\n            disconnect_mem_error(conn);\n            return 0;\n        }\n        conn->sm_state->bind = bind;\n        conn->sm_state->resume = 1;\n        xmpp_stanza_set_name(resume, \"resume\");\n        xmpp_stanza_set_ns(resume, XMPP_NS_SM);\n        xmpp_stanza_set_attribute(resume, \"previd\", conn->sm_state->previd);\n        strophe_snprintf(h, sizeof(h), \"%u\", conn->sm_state->sm_handled_nr);\n        xmpp_stanza_set_attribute(resume, \"h\", h);\n        send_stanza(conn, resume, XMPP_QUEUE_SM_STROPHE);\n        handler_add(conn, _handle_sm, XMPP_NS_SM, NULL, NULL, NULL);\n    }\n    /* if bind is required, go ahead and start it */\n    else if (conn->bind_required) {\n        /* bind resource */\n        _do_bind(conn, bind);\n    } else {\n        /* can't bind, disconnect */\n        if (bind) {\n            xmpp_stanza_release(bind);\n        }\n        strophe_error(conn->ctx, \"xmpp\",\n                      \"Stream features does not allow \"\n                      \"resource bind.\");\n        xmpp_disconnect(conn);\n    }\n\n    return 0;\n}\n\nstatic int _handle_missing_features_sasl(xmpp_conn_t *conn, void *userdata)\n{\n    UNUSED(userdata);\n\n    strophe_error(conn->ctx, \"xmpp\",\n                  \"Did not receive stream features \"\n                  \"after SASL authentication.\");\n    xmpp_disconnect(conn);\n    return 0;\n}\n\nstatic void _session_start(xmpp_conn_t *conn)\n{\n    xmpp_stanza_t *session;\n    xmpp_stanza_t *iq = xmpp_iq_new(conn->ctx, \"set\", \"_xmpp_session1\");\n    if (!iq) {\n        disconnect_mem_error(conn);\n        return;\n    }\n\n    session = xmpp_stanza_new(conn->ctx);\n    if (!session) {\n        xmpp_stanza_release(iq);\n        disconnect_mem_error(conn);\n        return;\n    }\n\n    /* setup response handlers */\n    handler_add_id(conn, _handle_session, \"_xmpp_session1\", NULL);\n    handler_add_timed(conn, _handle_missing_session, SESSION_TIMEOUT, NULL);\n\n    xmpp_stanza_set_name(session, \"session\");\n    xmpp_stanza_set_ns(session, XMPP_NS_SESSION);\n\n    xmpp_stanza_add_child_ex(iq, session, 0);\n\n    /* send session establishment request */\n    send_stanza(conn, iq, XMPP_QUEUE_STROPHE);\n}\n\nstatic void _sm_enable(xmpp_conn_t *conn)\n{\n    xmpp_stanza_t *enable = xmpp_stanza_new(conn->ctx);\n    if (!enable) {\n        disconnect_mem_error(conn);\n        return;\n    }\n    xmpp_stanza_set_name(enable, \"enable\");\n    xmpp_stanza_set_ns(enable, XMPP_NS_SM);\n    if (!conn->sm_state->dont_request_resume)\n        xmpp_stanza_set_attribute(enable, \"resume\", \"true\");\n    handler_add(conn, _handle_sm, XMPP_NS_SM, NULL, NULL, NULL);\n    send_stanza(conn, enable, XMPP_QUEUE_SM_STROPHE);\n    conn->sm_state->sm_sent_nr = 0;\n    conn->sm_state->sm_enabled = 1;\n    trigger_sm_callback(conn);\n}\n\nstatic int\n_handle_bind(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    const char *type;\n    xmpp_stanza_t *binding, *jid_stanza;\n\n    UNUSED(userdata);\n\n    /* delete missing bind handler */\n    xmpp_timed_handler_delete(conn, _handle_missing_bind);\n\n    /* server has replied to bind request */\n    type = xmpp_stanza_get_type(stanza);\n    if (type && strcmp(type, \"error\") == 0) {\n        strophe_error(conn->ctx, \"xmpp\", \"Binding failed.\");\n        xmpp_disconnect(conn);\n    } else if (type && strcmp(type, \"result\") == 0) {\n        binding = xmpp_stanza_get_child_by_name(stanza, \"bind\");\n        strophe_debug(conn->ctx, \"xmpp\", \"Bind successful.\");\n\n        if (binding) {\n            jid_stanza = xmpp_stanza_get_child_by_name(binding, \"jid\");\n            if (jid_stanza) {\n                conn->bound_jid = xmpp_stanza_get_text(jid_stanza);\n            }\n        }\n\n        /* establish a session if required */\n        if (conn->session_required) {\n            _session_start(conn);\n        }\n        /* send enable directly after the bind request */\n        else if (conn->sm_state->sm_support && !conn->sm_disable) {\n            _sm_enable(conn);\n        }\n        /* if there's no xmpp session required and we didn't try to enable\n         * stream-management, we're done here and the stream-negotiation was\n         * successful\n         */\n        else {\n            _stream_negotiation_success(conn);\n        }\n    } else {\n        strophe_error(conn->ctx, \"xmpp\", \"Server sent malformed bind reply.\");\n        xmpp_disconnect(conn);\n    }\n\n    return 0;\n}\n\nstatic int _handle_missing_bind(xmpp_conn_t *conn, void *userdata)\n{\n    UNUSED(userdata);\n\n    strophe_error(conn->ctx, \"xmpp\", \"Server did not reply to bind request.\");\n    xmpp_disconnect(conn);\n    return 0;\n}\n\nstatic int\n_handle_session(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    const char *type;\n\n    UNUSED(userdata);\n\n    /* delete missing session handler */\n    xmpp_timed_handler_delete(conn, _handle_missing_session);\n\n    /* server has replied to the session request */\n    type = xmpp_stanza_get_type(stanza);\n    if (type && strcmp(type, \"error\") == 0) {\n        strophe_error(conn->ctx, \"xmpp\", \"Session establishment failed.\");\n        xmpp_disconnect(conn);\n    } else if (type && strcmp(type, \"result\") == 0) {\n        strophe_debug(conn->ctx, \"xmpp\", \"Session establishment successful.\");\n        if (conn->sm_state->sm_support && !conn->sm_disable) {\n            _sm_enable(conn);\n        } else {\n            _stream_negotiation_success(conn);\n        }\n    } else {\n        strophe_error(conn->ctx, \"xmpp\",\n                      \"Server sent malformed session reply.\");\n        xmpp_disconnect(conn);\n    }\n\n    return 0;\n}\n\nstatic int _handle_missing_session(xmpp_conn_t *conn, void *userdata)\n{\n    UNUSED(userdata);\n\n    strophe_error(conn->ctx, \"xmpp\",\n                  \"Server did not reply to session request.\");\n    xmpp_disconnect(conn);\n    return 0;\n}\n\nstatic int _handle_missing_legacy(xmpp_conn_t *conn, void *userdata)\n{\n    UNUSED(userdata);\n\n    strophe_error(conn->ctx, \"xmpp\",\n                  \"Server did not reply to legacy \"\n                  \"authentication request.\");\n    xmpp_disconnect(conn);\n    return 0;\n}\n\nstatic int _get_h_attribute(xmpp_stanza_t *stanza, unsigned long *ul_h)\n{\n    const char *h = xmpp_stanza_get_attribute(stanza, \"h\");\n    if (!h || string_to_ul(h, ul_h)) {\n        strophe_error(\n            stanza->ctx, \"xmpp\",\n            \"SM error: failed parsing 'h', \\\"%s\\\" got converted to %llu.\",\n            STR_MAYBE_NULL(h), *ul_h);\n        return -1;\n    }\n    return 0;\n}\n\nstatic void _sm_queue_cleanup(xmpp_conn_t *conn, unsigned long ul_h)\n{\n    xmpp_send_queue_t *e;\n    while ((e = peek_queue_front(&conn->sm_state->sm_queue))) {\n        if (e->sm_h >= ul_h)\n            break;\n        e = pop_queue_front(&conn->sm_state->sm_queue);\n        strophe_free(conn->ctx, queue_element_free(conn->ctx, e));\n    }\n}\n\nstatic void _sm_queue_resend(xmpp_conn_t *conn)\n{\n    xmpp_send_queue_t *e;\n    while ((e = pop_queue_front(&conn->sm_state->sm_queue))) {\n        /* Re-send what was already sent out and is still in the\n         * SM queue (i.e. it hasn't been ACK'ed by the server)\n         */\n        strophe_debug_verbose(2, conn->ctx, \"conn\", \"SM_Q_RESEND: %p, h=%lu\", e,\n                              e->sm_h);\n        send_raw(conn, e->data, e->len, e->owner, NULL);\n        strophe_free(conn->ctx, queue_element_free(conn->ctx, e));\n    }\n}\n\nstatic int _handle_sm(xmpp_conn_t *const conn,\n                      xmpp_stanza_t *const stanza,\n                      void *const userdata)\n{\n    xmpp_stanza_t *failed_cause, *bind = NULL;\n    const char *name, *id, *previd, *resume, *cause;\n    unsigned long ul_h = 0;\n\n    UNUSED(userdata);\n\n    name = xmpp_stanza_get_name(stanza);\n    if (!name)\n        goto err_sm;\n\n    if (strcmp(name, \"enabled\") == 0) {\n        conn->sm_state->sm_handled_nr = 0;\n        resume = xmpp_stanza_get_attribute(stanza, \"resume\");\n        if (resume && (strcasecmp(resume, \"true\") || strcmp(resume, \"1\"))) {\n            id = xmpp_stanza_get_attribute(stanza, \"id\");\n            if (!id) {\n                strophe_error(conn->ctx, \"xmpp\",\n                              \"SM error: server said it can resume, but \"\n                              \"didn't provide an ID.\");\n                name = NULL;\n                goto err_sm;\n            }\n            conn->sm_state->can_resume = 1;\n            conn->sm_state->id = strophe_strdup(conn->ctx, id);\n        }\n        /* We maybe have stuff in the SM queue if we tried to resume, but the\n         * server doesn't remember all details of our session, but the `h` was\n         * still available.\n         */\n        _sm_queue_resend(conn);\n        _stream_negotiation_success(conn);\n    } else if (strcmp(name, \"resumed\") == 0) {\n        previd = xmpp_stanza_get_attribute(stanza, \"previd\");\n        if (!previd || strcmp(previd, conn->sm_state->previd)) {\n            strophe_error(conn->ctx, \"xmpp\",\n                          \"SM error: previd didn't match, ours is \\\"%s\\\".\",\n                          conn->sm_state->previd);\n            name = NULL;\n            goto err_sm;\n        }\n        if (_get_h_attribute(stanza, &ul_h)) {\n            name = NULL;\n            goto err_sm;\n        }\n        conn->sm_state->sm_enabled = 1;\n        conn->sm_state->id = conn->sm_state->previd;\n        conn->sm_state->previd = NULL;\n        conn->bound_jid = conn->sm_state->bound_jid;\n        conn->sm_state->bound_jid = NULL;\n        if (conn->sm_state->sm_queue.head)\n            conn->sm_state->sm_sent_nr = conn->sm_state->sm_queue.head->sm_h;\n        else\n            conn->sm_state->sm_sent_nr = ul_h;\n        _sm_queue_cleanup(conn, ul_h);\n        _sm_queue_resend(conn);\n        strophe_debug(conn->ctx, \"xmpp\", \"Session resumed successfully.\");\n        _stream_negotiation_success(conn);\n    } else if (strcmp(name, \"failed\") == 0) {\n        name = NULL;\n        conn->sm_state->sm_enabled = 0;\n\n        failed_cause =\n            xmpp_stanza_get_child_by_ns(stanza, XMPP_NS_STANZAS_IETF);\n        if (!failed_cause)\n            goto err_sm;\n\n        cause = xmpp_stanza_get_name(failed_cause);\n        if (!cause)\n            goto err_sm;\n\n        if (!strcmp(cause, \"item-not-found\")) {\n            if (conn->sm_state->resume) {\n                /* It's no error if there's no `h` attribute included\n                 * but if there is, it gives a hint at what the server\n                 * already received.\n                 */\n                if (!_get_h_attribute(stanza, &ul_h)) {\n                    /* In cases there's no `h` included, drop all elements. */\n                    ul_h = (unsigned long)-1;\n                }\n                _sm_queue_cleanup(conn, ul_h);\n            }\n        } else if (!strcmp(cause, \"feature-not-implemented\")) {\n            conn->sm_state->resume = 0;\n            conn->sm_state->can_resume = 0;\n            /* remember that the server reports having support\n             * for resumption, but actually it doesn't ...\n             */\n            conn->sm_state->dont_request_resume = 1;\n        }\n        bind = conn->sm_state->bind;\n        conn->sm_state->bind = NULL;\n        reset_sm_state(conn->sm_state);\n        _do_bind(conn, bind);\n    } else {\n        /* unknown stanza received */\n        name = NULL;\n    }\n\n    trigger_sm_callback(conn);\n\nerr_sm:\n    if (!name) {\n        char *err = \"Couldn't convert stanza to text!\";\n        char *buf;\n        size_t buflen;\n        switch (xmpp_stanza_to_text(stanza, &buf, &buflen)) {\n        case XMPP_EOK:\n            break;\n        case XMPP_EMEM:\n            disconnect_mem_error(conn);\n            return 0;\n        default:\n            buf = err;\n            break;\n        }\n        strophe_warn(conn->ctx, \"xmpp\", \"SM error: Stanza received was: %s\",\n                     buf);\n        if (buf != err)\n            strophe_free(conn->ctx, buf);\n        /* Don't disable for <failure> cases, they're no hard errors */\n        conn->sm_state->sm_enabled = bind != NULL;\n    }\n    return 0;\n}\n\nstatic int\n_handle_legacy(xmpp_conn_t *conn, xmpp_stanza_t *stanza, void *userdata)\n{\n    const char *type;\n    const char *name;\n\n    UNUSED(userdata);\n\n    /* delete missing handler */\n    xmpp_timed_handler_delete(conn, _handle_missing_legacy);\n\n    /* server responded to legacy auth request */\n    type = xmpp_stanza_get_type(stanza);\n    name = xmpp_stanza_get_name(stanza);\n    if (!type || strcmp(name, \"iq\") != 0) {\n        strophe_error(conn->ctx, \"xmpp\",\n                      \"Server sent us an unexpected response \"\n                      \"to legacy authentication request.\");\n        xmpp_disconnect(conn);\n    } else if (strcmp(type, \"error\") == 0) {\n        /* legacy client auth failed, no more fallbacks */\n        strophe_error(conn->ctx, \"xmpp\",\n                      \"Legacy client authentication failed.\");\n        xmpp_disconnect(conn);\n    } else if (strcmp(type, \"result\") == 0) {\n        /* auth succeeded */\n        strophe_debug(conn->ctx, \"xmpp\", \"Legacy auth succeeded.\");\n\n        _stream_negotiation_success(conn);\n    } else {\n        strophe_error(conn->ctx, \"xmpp\",\n                      \"Server sent us a legacy authentication \"\n                      \"response with a bad type.\");\n        xmpp_disconnect(conn);\n    }\n\n    return 0;\n}\n\nstatic void _auth_legacy(xmpp_conn_t *conn)\n{\n    xmpp_stanza_t *iq;\n    xmpp_stanza_t *authdata;\n    xmpp_stanza_t *query;\n    xmpp_stanza_t *child;\n    char *str;\n\n    strophe_debug(conn->ctx, \"auth\", \"Legacy authentication request\");\n\n    iq = xmpp_iq_new(conn->ctx, \"set\", \"_xmpp_auth1\");\n    if (!iq)\n        goto err;\n\n    query = xmpp_stanza_new(conn->ctx);\n    if (!query)\n        goto err_free;\n    xmpp_stanza_set_name(query, \"query\");\n    xmpp_stanza_set_ns(query, XMPP_NS_AUTH);\n    xmpp_stanza_add_child_ex(iq, query, 0);\n\n    child = xmpp_stanza_new(conn->ctx);\n    if (!child)\n        goto err_free;\n    xmpp_stanza_set_name(child, \"username\");\n    xmpp_stanza_add_child_ex(query, child, 0);\n\n    authdata = xmpp_stanza_new(conn->ctx);\n    if (!authdata)\n        goto err_free;\n    str = xmpp_jid_node(conn->ctx, conn->jid);\n    if (!str) {\n        xmpp_stanza_release(authdata);\n        goto err_free;\n    }\n    xmpp_stanza_set_text(authdata, str);\n    strophe_free(conn->ctx, str);\n    xmpp_stanza_add_child_ex(child, authdata, 0);\n\n    child = xmpp_stanza_new(conn->ctx);\n    if (!child)\n        goto err_free;\n    xmpp_stanza_set_name(child, \"password\");\n    xmpp_stanza_add_child_ex(query, child, 0);\n\n    authdata = xmpp_stanza_new(conn->ctx);\n    if (!authdata)\n        goto err_free;\n    xmpp_stanza_set_text(authdata, conn->pass);\n    xmpp_stanza_add_child_ex(child, authdata, 0);\n\n    child = xmpp_stanza_new(conn->ctx);\n    if (!child)\n        goto err_free;\n    xmpp_stanza_set_name(child, \"resource\");\n    xmpp_stanza_add_child_ex(query, child, 0);\n\n    authdata = xmpp_stanza_new(conn->ctx);\n    if (!authdata)\n        goto err_free;\n    str = xmpp_jid_resource(conn->ctx, conn->jid);\n    if (str) {\n        xmpp_stanza_set_text(authdata, str);\n        strophe_free(conn->ctx, str);\n    } else {\n        xmpp_stanza_release(authdata);\n        xmpp_stanza_release(iq);\n        strophe_error(conn->ctx, \"auth\",\n                      \"Cannot authenticate without resource\");\n        xmpp_disconnect(conn);\n        return;\n    }\n    xmpp_stanza_add_child_ex(child, authdata, 0);\n\n    handler_add_id(conn, _handle_legacy, \"_xmpp_auth1\", NULL);\n    handler_add_timed(conn, _handle_missing_legacy, LEGACY_TIMEOUT, NULL);\n\n    send_stanza(conn, iq, XMPP_QUEUE_STROPHE);\n    return;\n\nerr_free:\n    xmpp_stanza_release(iq);\nerr:\n    disconnect_mem_error(conn);\n}\n\nvoid auth_handle_component_open(xmpp_conn_t *conn)\n{\n    int rc;\n\n    /* reset all timed handlers */\n    handler_reset_timed(conn, 0);\n\n    handler_add(conn, _handle_error, XMPP_NS_STREAMS, \"error\", NULL, NULL);\n    handler_add(conn, _handle_component_hs_response, NULL, \"handshake\", NULL,\n                NULL);\n    handler_add_timed(conn, _handle_missing_handshake, HANDSHAKE_TIMEOUT, NULL);\n\n    rc = _handle_component_auth(conn);\n    if (rc != 0) {\n        strophe_error(conn->ctx, \"auth\", \"Component authentication failed.\");\n        xmpp_disconnect(conn);\n    }\n}\n\n/* Will compute SHA1 and authenticate the component to the server */\nint _handle_component_auth(xmpp_conn_t *conn)\n{\n    uint8_t md_value[SHA1_DIGEST_SIZE];\n    SHA1_CTX mdctx;\n    char *digest;\n    size_t i;\n\n    if (conn->stream_id == NULL) {\n        strophe_error(conn->ctx, \"auth\",\n                      \"Received no stream id from the server.\");\n        return XMPP_EINT;\n    }\n\n    /* Feed the session id and passphrase to the algorithm.\n     * We need to compute SHA1(session_id + passphrase)\n     */\n    crypto_SHA1_Init(&mdctx);\n    crypto_SHA1_Update(&mdctx, (uint8_t *)conn->stream_id,\n                       strlen(conn->stream_id));\n    crypto_SHA1_Update(&mdctx, (uint8_t *)conn->pass, strlen(conn->pass));\n    crypto_SHA1_Final(&mdctx, md_value);\n\n    digest = strophe_alloc(conn->ctx, 2 * sizeof(md_value) + 1);\n    if (digest) {\n        /* convert the digest into string representation */\n        for (i = 0; i < sizeof(md_value); i++)\n            strophe_snprintf(digest + i * 2, 3, \"%02x\", md_value[i]);\n        digest[2 * sizeof(md_value)] = '\\0';\n\n        strophe_debug(conn->ctx, \"auth\", \"Digest: %s, len: %d\", digest,\n                      strlen(digest));\n\n        /* Send the digest to the server */\n        send_raw_string(conn, \"<handshake xmlns='%s'>%s</handshake>\",\n                        XMPP_NS_COMPONENT, digest);\n        strophe_debug(conn->ctx, \"auth\",\n                      \"Sent component handshake to the server.\");\n        strophe_free(conn->ctx, digest);\n    } else {\n        strophe_debug(conn->ctx, \"auth\",\n                      \"Couldn't allocate memory for component \"\n                      \"handshake digest.\");\n        return XMPP_EMEM;\n    }\n\n    return 0;\n}\n\n/* Check if the received stanza is <handshake/> and set auth to true\n * and fire connection handler.\n */\nint _handle_component_hs_response(xmpp_conn_t *conn,\n                                  xmpp_stanza_t *stanza,\n                                  void *userdata)\n{\n    const char *name;\n\n    UNUSED(userdata);\n\n    xmpp_timed_handler_delete(conn, _handle_missing_handshake);\n\n    name = xmpp_stanza_get_name(stanza);\n    if (strcmp(name, \"handshake\") != 0) {\n        char *msg;\n        size_t msg_size;\n        xmpp_stanza_to_text(stanza, &msg, &msg_size);\n        if (msg) {\n            strophe_debug(conn->ctx, \"auth\", \"Handshake failed: %s\", msg);\n            strophe_free(conn->ctx, msg);\n        }\n        xmpp_disconnect(conn);\n        return XMPP_EINT;\n    } else {\n        _stream_negotiation_success(conn);\n    }\n\n    /* We don't need this handler anymore, return 0 so it can be deleted\n     * from the list of handlers.\n     */\n    return 0;\n}\n\nint _handle_missing_handshake(xmpp_conn_t *conn, void *userdata)\n{\n    UNUSED(userdata);\n\n    strophe_error(conn->ctx, \"xmpp\",\n                  \"Server did not reply to handshake request.\");\n    xmpp_disconnect(conn);\n    return 0;\n}\n\nvoid auth_handle_open_raw(xmpp_conn_t *conn)\n{\n    handler_reset_timed(conn, 0);\n    /* user handlers are not called before stream negotiation has completed. */\n    _stream_negotiation_success(conn);\n}\n\nvoid auth_handle_open_stub(xmpp_conn_t *conn)\n{\n    strophe_warn(conn->ctx, \"auth\", \"Stub callback is called.\");\n}\n"
  },
  {
    "path": "src/common.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* common.h\n** strophe XMPP client library -- internal common structures\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express or\n**  implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Internally used functions and structures.\n */\n\n#ifndef __LIBSTROPHE_COMMON_H__\n#define __LIBSTROPHE_COMMON_H__\n\n#include <stdio.h>\n#include <stdarg.h>\n\n#include \"strophe.h\"\n#include \"ostypes.h\"\n#include \"sock.h\"\n#include \"tls.h\"\n#include \"hash.h\"\n#include \"util.h\"\n#include \"parser.h\"\n#include \"snprintf.h\"\n\n/** Define your own `STROPHE_STATIC_ASSERT` if your compiler doesn't support one\n * of the below ones or define as noop if your compiler provides no replacement.\n */\n#if !defined(STROPHE_STATIC_ASSERT)\n#if (__STDC_VERSION__ >= 202000L)\n#define STROPHE_STATIC_ASSERT(cond, msg) static_assert(cond, msg)\n#else\n#define STROPHE_STATIC_ASSERT(cond, msg) _Static_assert(cond, msg)\n#endif\n#endif\n\n/** handlers **/\n#if (__STDC_VERSION__ >= 202000L)\ntypedef void *xmpp_void_handler;\n#else\ntypedef int (*xmpp_void_handler)();\n#endif\n\ntypedef struct _xmpp_handlist_t xmpp_handlist_t;\nstruct _xmpp_handlist_t {\n    /* common members */\n    int user_handler;\n    xmpp_void_handler handler;\n    void *userdata;\n    int enabled; /* handlers are added disabled and enabled after the\n                  * handler chain is processed to prevent stanzas from\n                  * getting processed by newly added handlers */\n    xmpp_handlist_t *next;\n\n    union {\n        /* timed handlers */\n        struct {\n            unsigned long period;\n            uint64_t last_stamp;\n        };\n        /* id handlers */\n        struct {\n            char *id;\n        };\n        /* normal handlers */\n        struct {\n            char *ns;\n            char *name;\n            char *type;\n        };\n    } u;\n};\n\n/** run-time context **/\n\ntypedef enum {\n    XMPP_LOOP_NOTSTARTED,\n    XMPP_LOOP_RUNNING,\n    XMPP_LOOP_QUIT\n} xmpp_loop_status_t;\n\ntypedef struct _xmpp_connlist_t {\n    xmpp_conn_t *conn;\n    struct _xmpp_connlist_t *next;\n} xmpp_connlist_t;\n\nstruct _xmpp_ctx_t {\n    const xmpp_mem_t *mem;\n    const xmpp_log_t *log;\n    int verbosity;\n\n    xmpp_rand_t *rand;\n    xmpp_loop_status_t loop_status;\n    xmpp_connlist_t *connlist;\n    xmpp_handlist_t *timed_handlers;\n\n    unsigned long timeout;\n};\n\n/* convenience functions for accessing the context */\nvoid *strophe_alloc(const xmpp_ctx_t *ctx, size_t size);\nvoid *strophe_realloc(const xmpp_ctx_t *ctx, void *p, size_t size);\nchar *strophe_strdup(const xmpp_ctx_t *ctx, const char *s);\nchar *strophe_strndup(const xmpp_ctx_t *ctx, const char *s, size_t len);\nvoid strophe_free(const xmpp_ctx_t *ctx, void *p);\n#define strophe_free_and_null(ctx, p) \\\n    do {                              \\\n        if (p) {                      \\\n            strophe_free(ctx, (p));   \\\n            (p) = NULL;               \\\n        }                             \\\n    } while (0)\n\n/* wrappers for xmpp_log at specific levels */\nvoid strophe_error(const xmpp_ctx_t *ctx,\n                   const char *area,\n                   const char *fmt,\n                   ...);\nvoid strophe_warn(const xmpp_ctx_t *ctx,\n                  const char *area,\n                  const char *fmt,\n                  ...);\nvoid strophe_info(const xmpp_ctx_t *ctx,\n                  const char *area,\n                  const char *fmt,\n                  ...);\nvoid strophe_debug(const xmpp_ctx_t *ctx,\n                   const char *area,\n                   const char *fmt,\n                   ...);\nvoid strophe_debug_verbose(\n    int level, const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...);\n\nvoid strophe_log_internal(const xmpp_ctx_t *ctx,\n                          xmpp_log_level_t level,\n                          const char *area,\n                          const char *fmt,\n                          va_list ap);\n\n#if defined(__OpenBSD__)\n#define STR_MAYBE_NULL(p) (p) ? (p) : \"(null)\"\n#else\n#define STR_MAYBE_NULL(p) (p)\n#endif\n\n/** connection **/\n\n/* opaque connection object */\ntypedef enum {\n    XMPP_STATE_DISCONNECTED,\n    XMPP_STATE_CONNECTING,\n    XMPP_STATE_CONNECTED\n} xmpp_conn_state_t;\n\ntypedef enum {\n    XMPP_QUEUE_STROPHE = 0x1,\n    XMPP_QUEUE_USER = 0x2,\n    XMPP_QUEUE_SM = 0x800,\n    XMPP_QUEUE_SM_STROPHE = XMPP_QUEUE_SM | XMPP_QUEUE_STROPHE,\n} xmpp_send_queue_owner_t;\n\ntypedef struct _xmpp_send_queue_t xmpp_send_queue_t;\nstruct _xmpp_send_queue_t {\n    char *data;\n    size_t len;\n    size_t written;\n    int wip;\n    xmpp_send_queue_owner_t owner;\n    void *userdata;\n    uint32_t sm_h;\n\n    xmpp_send_queue_t *prev, *next;\n};\n\n#define UNUSED(x) ((void)(x))\n\n#define MAX_DOMAIN_LEN 256\n\n#define SASL_MASK_PLAIN (1 << 0)\n#define SASL_MASK_DIGESTMD5 (1 << 1)\n#define SASL_MASK_ANONYMOUS (1 << 2)\n#define SASL_MASK_SCRAMSHA1 (1 << 3)\n#define SASL_MASK_SCRAMSHA256 (1 << 4)\n#define SASL_MASK_SCRAMSHA512 (1 << 5)\n#define SASL_MASK_EXTERNAL (1 << 6)\n#define SASL_MASK_SCRAMSHA1_PLUS (1 << 7)\n#define SASL_MASK_SCRAMSHA256_PLUS (1 << 8)\n#define SASL_MASK_SCRAMSHA512_PLUS (1 << 9)\n\n#define SASL_MASK_SCRAM_PLUS                                 \\\n    (SASL_MASK_SCRAMSHA1_PLUS | SASL_MASK_SCRAMSHA256_PLUS | \\\n     SASL_MASK_SCRAMSHA512_PLUS)\n#define SASL_MASK_SCRAM_WEAK \\\n    (SASL_MASK_SCRAMSHA1 | SASL_MASK_SCRAMSHA256 | SASL_MASK_SCRAMSHA512)\n#define SASL_MASK_SCRAM (SASL_MASK_SCRAM_PLUS | SASL_MASK_SCRAM_WEAK)\n\nenum {\n    XMPP_PORT_CLIENT = 5222,\n    XMPP_PORT_CLIENT_LEGACY_SSL = 5223,\n    XMPP_PORT_COMPONENT = 5347,\n};\n\ntypedef void (*xmpp_open_handler)(xmpp_conn_t *conn);\n\ntypedef struct {\n    xmpp_send_queue_t *head, *tail;\n} xmpp_queue_t;\n\nstruct _xmpp_sm_t {\n    xmpp_ctx_t *ctx;\n    int sm_support;\n    int sm_enabled;\n    int can_resume, resume, dont_request_resume;\n    xmpp_queue_t sm_queue;\n    int r_sent;\n    uint32_t sm_handled_nr;\n    uint32_t sm_sent_nr;\n    char *id, *previd, *bound_jid;\n    xmpp_stanza_t *bind;\n};\n\nstruct conn_interface {\n    int (*read)(struct conn_interface *intf, void *buff, size_t len);\n    int (*write)(struct conn_interface *intf, const void *buff, size_t len);\n    int (*flush)(struct conn_interface *intf);\n    int (*pending)(struct conn_interface *intf);\n    int (*get_error)(struct conn_interface *intf);\n    int (*error_is_recoverable)(struct conn_interface *intf, int err);\n    xmpp_conn_t *conn;\n};\n\nint conn_interface_write(struct conn_interface *intf,\n                         const void *buff,\n                         size_t len);\nint conn_int_nop(struct conn_interface *intf);\n\nint compression_init(xmpp_conn_t *conn);\nvoid compression_free(xmpp_conn_t *conn);\nvoid compression_handle_feature_children(xmpp_conn_t *conn, const char *text);\n\nstruct _xmpp_conn_t {\n    struct conn_interface intf;\n\n    unsigned int ref;\n    xmpp_ctx_t *ctx;\n    xmpp_conn_type_t type;\n    int is_raw;\n\n    xmpp_conn_state_t state;\n    uint64_t timeout_stamp;\n    int error;\n    xmpp_stream_error_t *stream_error;\n\n    xmpp_sock_t *xsock;\n    sock_t sock;\n    int ka_timeout;  /* TCP keepalive timeout */\n    int ka_interval; /* TCP keepalive interval */\n    int ka_count;    /* TCP keepalive count */\n\n    tls_t *tls;\n    int tls_support;\n    int tls_disabled;\n    int tls_mandatory;\n    int tls_legacy_ssl;\n    int tls_trust;\n    char *tls_cafile;\n    char *tls_capath;\n    char *tls_client_cert;\n    char *tls_client_key;\n    int tls_failed;   /* set when tls fails, so we don't try again */\n    int sasl_support; /* if true, field is a bitfield of supported\n                         mechanisms */\n    int auth_legacy_enabled;\n    int secured; /* set when stream is secured with TLS */\n    xmpp_certfail_handler certfail_handler;\n    xmpp_password_callback password_callback;\n    void *password_callback_userdata;\n    struct {\n        char pass[1024];\n        unsigned char fname_hash[XMPP_SHA1_DIGEST_SIZE];\n        size_t passlen, fnamelen;\n    } password_cache;\n    unsigned int password_retries;\n\n    /* if server returns <bind/> or <session/> we must do them */\n    int bind_required;\n    int session_required;\n    int sm_disable;\n    xmpp_sm_state_t *sm_state;\n\n    struct {\n        struct xmpp_compression *state;\n        int allowed, supported, dont_reset;\n    } compression;\n\n    char *lang;\n    char *domain;\n    char *jid;\n    char *pass;\n    char *bound_jid;\n    char *stream_id;\n\n    /* send queue and parameters */\n    int blocking_send;\n    int send_queue_max;\n    int send_queue_len;\n    int send_queue_user_len;\n    xmpp_send_queue_t *send_queue_head;\n    xmpp_send_queue_t *send_queue_tail;\n\n    /* xml parser */\n    int reset_parser;\n    parser_t *parser;\n\n    /* timeouts */\n    unsigned int connect_timeout;\n\n    /* event handlers */\n\n    /* stream open handler */\n    xmpp_open_handler open_handler;\n\n    /* user handlers only get called after the stream negotiation has completed\n     */\n    int stream_negotiation_completed;\n\n    /* connection events handler */\n    xmpp_conn_handler conn_handler;\n    void *userdata;\n\n    /* other handlers */\n    xmpp_handlist_t *timed_handlers;\n    hash_t *id_handlers;\n    xmpp_handlist_t *handlers;\n    xmpp_sockopt_callback sockopt_cb;\n    xmpp_sm_callback sm_callback;\n    void *sm_callback_ctx;\n};\n\nvoid conn_disconnect(xmpp_conn_t *conn);\nvoid conn_disconnect_clean(xmpp_conn_t *conn);\nvoid conn_established(xmpp_conn_t *conn);\nvoid conn_open_stream(xmpp_conn_t *conn);\nint conn_tls_start(xmpp_conn_t *conn);\nvoid conn_prepare_reset(xmpp_conn_t *conn, xmpp_open_handler handler);\nvoid conn_parser_reset(xmpp_conn_t *conn);\n\ntypedef enum {\n    XMPP_STANZA_UNKNOWN,\n    XMPP_STANZA_TEXT,\n    XMPP_STANZA_TAG\n} xmpp_stanza_type_t;\n\nstruct _xmpp_stanza_t {\n    int ref;\n    xmpp_ctx_t *ctx;\n\n    xmpp_stanza_type_t type;\n\n    xmpp_stanza_t *prev;\n    xmpp_stanza_t *next;\n    xmpp_stanza_t *children;\n    xmpp_stanza_t *parent;\n\n    char *data;\n\n    hash_t *attributes;\n};\n\n/* handler management */\nvoid handler_fire_stanza(xmpp_conn_t *conn, xmpp_stanza_t *stanza);\nuint64_t handler_fire_timed(xmpp_ctx_t *ctx);\nvoid handler_reset_timed(xmpp_conn_t *conn, int user_only);\nvoid handler_add_timed(xmpp_conn_t *conn,\n                       xmpp_timed_handler handler,\n                       unsigned long period,\n                       void *userdata);\nvoid handler_add_id(xmpp_conn_t *conn,\n                    xmpp_handler handler,\n                    const char *id,\n                    void *userdata);\nvoid handler_add(xmpp_conn_t *conn,\n                 xmpp_handler handler,\n                 const char *ns,\n                 const char *name,\n                 const char *type,\n                 void *userdata);\nvoid handler_system_delete_all(xmpp_conn_t *conn);\n\n/* utility functions */\nvoid trigger_sm_callback(xmpp_conn_t *conn);\nvoid reset_sm_state(xmpp_sm_state_t *sm_state);\nvoid disconnect_mem_error(xmpp_conn_t *conn);\n\n/* auth functions */\nvoid auth_handle_open(xmpp_conn_t *conn);\nvoid auth_handle_component_open(xmpp_conn_t *conn);\nvoid auth_handle_open_raw(xmpp_conn_t *conn);\nvoid auth_handle_open_stub(xmpp_conn_t *conn);\n\n/* queue functions */\nvoid add_queue_back(xmpp_queue_t *queue, xmpp_send_queue_t *item);\nxmpp_send_queue_t *peek_queue_front(xmpp_queue_t *queue);\nxmpp_send_queue_t *pop_queue_front(xmpp_queue_t *queue);\nchar *queue_element_free(xmpp_ctx_t *ctx, xmpp_send_queue_t *e);\n\n/* send functions */\nvoid send_raw(xmpp_conn_t *conn,\n              const char *data,\n              size_t len,\n              xmpp_send_queue_owner_t owner,\n              void *userdata);\n/* this is a bit special as it will always mark the sent string as\n * owned by libstrophe\n */\nvoid send_raw_string(xmpp_conn_t *conn, const char *fmt, ...);\nvoid send_stanza(xmpp_conn_t *conn,\n                 xmpp_stanza_t *stanza,\n                 xmpp_send_queue_owner_t owner);\n\n#endif /* __LIBSTROPHE_COMMON_H__ */\n"
  },
  {
    "path": "src/compression.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* compression.c\n** strophe XMPP client library -- XEP-0138 Stream Compression\n**\n** Copyright (C) 2024 Steffen Jaeckel <jaeckel-floss@eyet-services.de>\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  XEP-0138 Stream Compression.\n */\n#include <zlib.h>\n#include <string.h>\n#include <errno.h>\n\n#include \"common.h\"\n#ifdef _MSC_VER\n#define strcasecmp _stricmp\n#endif\n\n#ifndef STROPHE_COMPRESSION_BUFFER_SIZE\n/** Max buffer size for compressed data (send & receive). */\n#define STROPHE_COMPRESSION_BUFFER_SIZE 4096\n#endif\n\nstruct zlib_compression {\n    void *buffer, *buffer_end;\n    z_stream stream;\n};\n\nstruct xmpp_compression {\n    xmpp_conn_t *conn;\n    struct zlib_compression compression, decompression;\n    struct conn_interface next;\n};\n\nstatic int _conn_decompress(struct xmpp_compression *comp,\n                            size_t c_len,\n                            void *buff,\n                            size_t len)\n{\n    if (comp->decompression.stream.next_in == NULL) {\n        comp->decompression.stream.next_in = comp->decompression.buffer;\n        comp->decompression.buffer_end =\n            comp->decompression.stream.next_in + c_len;\n        comp->decompression.stream.avail_in = c_len;\n    } else if (c_len) {\n        strophe_error(comp->conn->ctx, \"zlib\",\n                      \"_conn_decompress() called with c_len=%zu\", c_len);\n    }\n    comp->decompression.stream.next_out = buff;\n    comp->decompression.stream.avail_out = len;\n    int ret = inflate(&comp->decompression.stream, Z_SYNC_FLUSH);\n    switch (ret) {\n    case Z_STREAM_END:\n    case Z_OK:\n        if (comp->decompression.buffer_end ==\n            comp->decompression.stream.next_in)\n            comp->decompression.stream.next_in = NULL;\n        return comp->decompression.stream.next_out - (Bytef *)buff;\n    case Z_BUF_ERROR:\n        break;\n    default:\n        strophe_error(comp->conn->ctx, \"zlib\", \"inflate error %d\", ret);\n        comp->conn->error = ret;\n        conn_disconnect(comp->conn);\n        break;\n    }\n    return 0;\n}\n\nstatic int compression_read(struct conn_interface *intf, void *buff, size_t len)\n{\n    xmpp_conn_t *conn = intf->conn;\n    struct xmpp_compression *comp = conn->compression.state;\n    void *dbuff = buff;\n    size_t dlen = len;\n    if (comp->decompression.stream.next_in != NULL) {\n        return _conn_decompress(comp, 0, buff, len);\n    }\n    dbuff = comp->decompression.buffer;\n    dlen = STROPHE_COMPRESSION_BUFFER_SIZE;\n    int ret = comp->next.read(intf, dbuff, dlen);\n    if (ret > 0) {\n        return _conn_decompress(comp, ret, buff, len);\n    }\n    return ret;\n}\n\nstatic int _try_compressed_write_to_network(xmpp_conn_t *conn, int force)\n{\n    struct xmpp_compression *comp = conn->compression.state;\n    int ret = 0;\n    ptrdiff_t len =\n        comp->compression.stream.next_out - (Bytef *)comp->compression.buffer;\n    int buffer_full =\n        comp->compression.stream.next_out == comp->compression.buffer_end;\n    if ((buffer_full || force) && len > 0) {\n        ret = conn_interface_write(&comp->next, comp->compression.buffer, len);\n        if (ret < 0)\n            return ret;\n        comp->compression.stream.next_out = comp->compression.buffer;\n        comp->compression.stream.avail_out = STROPHE_COMPRESSION_BUFFER_SIZE;\n    }\n    return ret;\n}\n\nstatic int\n_compression_write(xmpp_conn_t *conn, const void *buff, size_t len, int flush)\n{\n    int ret;\n    const void *buff_end = (const char *)buff + len;\n    struct xmpp_compression *comp = conn->compression.state;\n    comp->compression.stream.next_in = (Bytef *)buff;\n    comp->compression.stream.avail_in = len;\n    do {\n        ret = _try_compressed_write_to_network(conn, 0);\n        if (ret < 0) {\n            return ret;\n        }\n\n        ret = deflate(&comp->compression.stream, flush);\n        if (ret == Z_STREAM_END) {\n            break;\n        }\n        if (flush && ret == Z_BUF_ERROR) {\n            break;\n        }\n        if (ret != Z_OK) {\n            strophe_error(conn->ctx, \"zlib\", \"deflate error %d\", ret);\n            conn->error = ret;\n            conn_disconnect(conn);\n            return ret;\n        }\n        ret = comp->compression.stream.next_in - (Bytef *)buff;\n    } while (comp->compression.stream.next_in < (Bytef *)buff_end);\n    if (flush) {\n        ret = _try_compressed_write_to_network(conn, 1);\n        if (ret < 0) {\n            return ret;\n        }\n    }\n    return ret;\n}\n\nstatic int\ncompression_write(struct conn_interface *intf, const void *buff, size_t len)\n{\n    return _compression_write(intf->conn, buff, len, Z_NO_FLUSH);\n}\n\nstatic int compression_flush(struct conn_interface *intf)\n{\n    xmpp_conn_t *conn = intf->conn;\n    struct xmpp_compression *comp = conn->compression.state;\n    return _compression_write(conn, comp->compression.buffer, 0,\n                              conn->compression.dont_reset ? Z_SYNC_FLUSH\n                                                           : Z_FULL_FLUSH);\n}\n\nstatic int compression_pending(struct conn_interface *intf)\n{\n    xmpp_conn_t *conn = intf->conn;\n    struct xmpp_compression *comp = conn->compression.state;\n    return comp->decompression.stream.next_in != NULL ||\n           comp->next.pending(intf);\n}\n\nstatic int compression_get_error(struct conn_interface *intf)\n{\n    struct conn_interface *next = &intf->conn->compression.state->next;\n    return next->get_error(next);\n}\n\nstatic int compression_is_recoverable(struct conn_interface *intf, int err)\n{\n    struct conn_interface *next = &intf->conn->compression.state->next;\n    return next->error_is_recoverable(next, err);\n}\n\nstatic const struct conn_interface compression_intf = {\n    compression_read,\n    compression_write,\n    compression_flush,\n    compression_pending,\n    compression_get_error,\n    compression_is_recoverable,\n    NULL,\n};\n\nstatic void *_zlib_alloc(void *opaque, unsigned int items, unsigned int size)\n{\n    size_t sz = items * size;\n    /* Poor man's multiplication overflow check */\n    if (sz < items || sz < size)\n        return NULL;\n    return strophe_alloc(opaque, sz);\n}\n\nstatic void _init_zlib_compression(xmpp_ctx_t *ctx, struct zlib_compression *s)\n{\n    s->buffer = strophe_alloc(ctx, STROPHE_COMPRESSION_BUFFER_SIZE);\n    s->buffer_end = (char *)s->buffer + STROPHE_COMPRESSION_BUFFER_SIZE;\n\n    s->stream.opaque = ctx;\n    s->stream.zalloc = _zlib_alloc;\n    s->stream.zfree = (free_func)strophe_free;\n}\n\nint compression_init(xmpp_conn_t *conn)\n{\n    if (!conn->compression.allowed || !conn->compression.supported)\n        return -1;\n    conn->compression.state =\n        strophe_alloc(conn->ctx, sizeof(*conn->compression.state));\n    struct xmpp_compression *comp = conn->compression.state;\n    memset(comp, 0, sizeof(*comp));\n\n    comp->conn = conn;\n\n    comp->next = conn->intf;\n    conn->intf = compression_intf;\n    conn->intf.conn = conn;\n\n    _init_zlib_compression(conn->ctx, &comp->compression);\n\n    comp->compression.stream.next_out = comp->compression.buffer;\n    comp->compression.stream.avail_out = STROPHE_COMPRESSION_BUFFER_SIZE;\n    int ret = deflateInit(&comp->compression.stream, Z_DEFAULT_COMPRESSION);\n    if (ret != Z_OK) {\n        strophe_free_and_null(conn->ctx, comp->compression.buffer);\n        conn->error = ret;\n        conn_disconnect(conn);\n        return ret;\n    }\n\n    _init_zlib_compression(conn->ctx, &comp->decompression);\n\n    ret = inflateInit(&comp->decompression.stream);\n    if (ret != Z_OK) {\n        strophe_free_and_null(conn->ctx, comp->decompression.buffer);\n        conn->error = ret;\n        conn_disconnect(conn);\n        return ret;\n    }\n    return 0;\n}\n\nvoid compression_free(xmpp_conn_t *conn)\n{\n    struct xmpp_compression *comp = conn->compression.state;\n    if (!comp)\n        return;\n    if (comp->compression.buffer) {\n        deflateEnd(&comp->compression.stream);\n        strophe_free_and_null(conn->ctx, comp->compression.buffer);\n    }\n    if (comp->decompression.buffer) {\n        inflateEnd(&comp->decompression.stream);\n        strophe_free_and_null(conn->ctx, comp->decompression.buffer);\n    }\n}\n\nvoid compression_handle_feature_children(xmpp_conn_t *conn, const char *text)\n{\n    if (strcasecmp(text, \"zlib\") == 0) {\n        conn->compression.supported = 1;\n    }\n}\n"
  },
  {
    "path": "src/compression_dummy.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* compression_dummy.c\n** strophe XMPP client library -- Dummy Compression\n**\n** Copyright (C) 2024 Steffen Jaeckel <jaeckel-floss@eyet-services.de>\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Dummy Compression.\n */\n#include <strings.h>\n#include <errno.h>\n\n#include \"common.h\"\n\nint compression_init(xmpp_conn_t *conn)\n{\n    conn->compression.supported = 0;\n    return -1;\n}\n\nvoid compression_free(xmpp_conn_t *conn)\n{\n    UNUSED(conn);\n}\n\nvoid compression_handle_feature_children(xmpp_conn_t *conn, const char *text)\n{\n    UNUSED(text);\n    conn->compression.supported = 0;\n}\n"
  },
  {
    "path": "src/conn.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* conn.c\n** strophe XMPP client library -- connection object functions\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Connection management.\n */\n\n/** @defgroup Connections Connection management\n *  These functions manage a connection object.\n *\n *  A part of those functions is listed under the \\ref TLS section.\n */\n\n#include <errno.h>\n#if !defined(_MSC_VER) && !defined(_WIN32)\n#include <netinet/in.h>\n#endif\n#include <stdarg.h>\n#include <string.h>\n#include <limits.h>\n\n#include \"strophe.h\"\n\n#include \"common.h\"\n#include \"util.h\"\n#include \"parser.h\"\n\n#ifndef DEFAULT_SEND_QUEUE_MAX\n/** @def DEFAULT_SEND_QUEUE_MAX\n *  The default maximum send queue size.  This is currently unused.\n */\n#define DEFAULT_SEND_QUEUE_MAX 64\n#endif\n#ifndef DISCONNECT_TIMEOUT\n/** @def DISCONNECT_TIMEOUT\n *  The time to wait (in milliseconds) for graceful disconnection to\n *  complete before the connection is reset.  The default is 2 seconds.\n */\n#define DISCONNECT_TIMEOUT 2000 /* 2 seconds */\n#endif\n#ifndef CONNECT_TIMEOUT\n/** @def CONNECT_TIMEOUT\n *  The time to wait (in milliseconds) for a connection attempt to succeed\n *  or error.  The default is 5 seconds.\n */\n#define CONNECT_TIMEOUT 5000 /* 5 seconds */\n#endif\n\n#ifndef KEEPALIVE_TIMEOUT\n/** @def KEEPALIVE_TIMEOUT\n *  The time (in seconds) the connection needs to remain idle before TCP starts\n *  sending keepalive probes, if the socket option SO_KEEPALIVE has been set on\n *  this socket.\n *  c.f. `TCP_KEEPIDLE` in `man 7 tcp` for linux, FreeBSD and some others or\n *  `TCP_KEEPALIVE` on MacOS.\n */\n#define KEEPALIVE_TIMEOUT 60\n#endif\n#ifndef KEEPALIVE_INTERVAL\n/** @def KEEPALIVE_INTERVAL\n *  The time (in seconds) between individual keepalive probes.\n *  c.f. `TCP_KEEPINTVL` in `man 7 tcp`\n */\n#define KEEPALIVE_INTERVAL 30\n#endif\n#ifndef KEEPALIVE_COUNT\n/** @def KEEPALIVE_COUNT\n *  The maximum number of keepalive probes TCP should send before dropping the\n *  connection.\n *  c.f. `TCP_KEEPCNT` in `man 7 tcp`\n */\n#define KEEPALIVE_COUNT 3\n#endif\n\nstatic int _is_connected(xmpp_conn_t *conn, xmpp_send_queue_owner_t owner);\nstatic int _disconnect_cleanup(xmpp_conn_t *conn, void *userdata);\nstatic void _reset_sm_state_for_reconnect(xmpp_conn_t *conn);\nstatic char *_conn_build_stream_tag(xmpp_conn_t *conn,\n                                    char **attributes,\n                                    size_t attributes_len);\nstatic int _conn_open_stream_with_attributes(xmpp_conn_t *conn,\n                                             char **attributes,\n                                             size_t attributes_len);\nstatic void _conn_attributes_new(xmpp_conn_t *conn,\n                                 char **attrs,\n                                 char ***attributes,\n                                 size_t *attributes_len);\nstatic void _conn_attributes_destroy(xmpp_conn_t *conn,\n                                     char **attributes,\n                                     size_t attributes_len);\nstatic void _handle_stream_start(char *name, char **attrs, void *userdata);\nstatic void _handle_stream_end(char *name, void *userdata);\nstatic void _handle_stream_stanza(xmpp_stanza_t *stanza, void *userdata);\nstatic void _conn_sm_handle_stanza(xmpp_conn_t *const conn,\n                                   xmpp_stanza_t *stanza);\nstatic unsigned short _conn_default_port(xmpp_conn_t *conn,\n                                         xmpp_conn_type_t type);\nstatic void _conn_reset(xmpp_conn_t *conn);\nstatic int _conn_connect(xmpp_conn_t *conn,\n                         const char *domain,\n                         xmpp_conn_type_t type,\n                         xmpp_conn_handler callback,\n                         void *userdata);\nstatic void _send_valist(xmpp_conn_t *conn,\n                         const char *fmt,\n                         va_list ap,\n                         xmpp_send_queue_owner_t owner);\nstatic int _send_raw(xmpp_conn_t *conn,\n                     char *data,\n                     size_t len,\n                     xmpp_send_queue_owner_t owner,\n                     void *userdata);\n\nvoid xmpp_send_error(xmpp_conn_t *conn, xmpp_error_type_t type, char *text)\n{\n    xmpp_stanza_t *error = xmpp_error_new(conn->ctx, type, text);\n\n    send_stanza(conn, error, XMPP_QUEUE_STROPHE);\n}\n\n/** Create a new Strophe connection object.\n *\n *  @param ctx a Strophe context object\n *\n *  @return a Strophe connection object or NULL on an error\n *\n *  @ingroup Connections\n */\nxmpp_conn_t *xmpp_conn_new(xmpp_ctx_t *ctx)\n{\n    xmpp_conn_t *conn = NULL;\n    xmpp_connlist_t *tail, *item;\n\n    if (ctx == NULL)\n        return NULL;\n\n    conn = strophe_alloc(ctx, sizeof(xmpp_conn_t));\n    if (conn != NULL) {\n        memset(conn, 0, sizeof(xmpp_conn_t));\n        conn->ctx = ctx;\n\n        conn->type = XMPP_UNKNOWN;\n        conn->state = XMPP_STATE_DISCONNECTED;\n\n        conn->sock = INVALID_SOCKET;\n        conn->ka_timeout = KEEPALIVE_TIMEOUT;\n        conn->ka_interval = KEEPALIVE_INTERVAL;\n        conn->ka_count = KEEPALIVE_COUNT;\n\n        /* default send parameters */\n        conn->send_queue_max = DEFAULT_SEND_QUEUE_MAX;\n\n        /* default timeouts */\n        conn->connect_timeout = CONNECT_TIMEOUT;\n\n        conn->lang = strophe_strdup(conn->ctx, \"en\");\n        if (!conn->lang) {\n            strophe_free(conn->ctx, conn);\n            return NULL;\n        }\n        tls_clear_password_cache(conn);\n        conn->password_retries = 1;\n\n        conn->parser =\n            parser_new(conn->ctx, _handle_stream_start, _handle_stream_end,\n                       _handle_stream_stanza, conn);\n        /* we own (and will free) the hash values */\n        conn->id_handlers = hash_new(conn->ctx, 32, NULL);\n\n        /* give the caller a reference to connection */\n        conn->ref = 1;\n\n        /* add connection to ctx->connlist */\n        tail = conn->ctx->connlist;\n        while (tail && tail->next)\n            tail = tail->next;\n\n        item = strophe_alloc(conn->ctx, sizeof(xmpp_connlist_t));\n        if (!item) {\n            strophe_error(conn->ctx, \"xmpp\", \"failed to allocate memory\");\n            strophe_free(conn->ctx, conn->lang);\n            parser_free(conn->parser);\n            strophe_free(conn->ctx, conn);\n            conn = NULL;\n        } else {\n            item->conn = conn;\n            item->next = NULL;\n\n            if (tail)\n                tail->next = item;\n            else\n                conn->ctx->connlist = item;\n        }\n    }\n\n    return conn;\n}\n\n/** Clone a Strophe connection object.\n *\n *  @param conn a Strophe connection object\n *\n *  @return the same conn object passed in with its reference count\n *          incremented by 1\n *\n *  @ingroup Connections\n */\nxmpp_conn_t *xmpp_conn_clone(xmpp_conn_t *conn)\n{\n    conn->ref++;\n    return conn;\n}\n\n/** Register sockopt callback\n *  Set function to be called when a new socket is created to allow setting\n *  socket options before connection is started.\n *\n *  If the connection is already connected, this callback will be called\n *  immediately.\n *\n *  To set options that can only be applied to disconnected sockets, the\n *  callback must be registered before connecting.\n *\n *  @param conn The Strophe connection object this callback is being registered\n * for\n *  @param callback a xmpp_sockopt_callback callback function that will receive\n *      notifications of connection status\n *\n *  @ingroup Connections\n */\n\nvoid xmpp_conn_set_sockopt_callback(xmpp_conn_t *conn,\n                                    xmpp_sockopt_callback callback)\n{\n    conn->sockopt_cb = callback;\n    if (conn->state != XMPP_STATE_DISCONNECTED)\n        callback(conn, &conn->sock);\n}\n\n/** Release a Strophe connection object.\n *  Decrement the reference count by one for a connection, freeing the\n *  connection object if the count reaches 0.\n *\n *  @param conn a Strophe connection object\n *\n *  @return TRUE if the connection object was freed and FALSE otherwise\n *\n *  @ingroup Connections\n */\nint xmpp_conn_release(xmpp_conn_t *conn)\n{\n    xmpp_ctx_t *ctx;\n    xmpp_connlist_t *item, *prev;\n    xmpp_handlist_t *hlitem, *thli;\n    hash_iterator_t *iter;\n    const char *key;\n    int released = 0;\n\n    if (conn->ref > 1)\n        conn->ref--;\n    else {\n        ctx = conn->ctx;\n\n        if (conn->state == XMPP_STATE_CONNECTING ||\n            conn->state == XMPP_STATE_CONNECTED) {\n            conn_disconnect(conn);\n        }\n\n        /* remove connection from context's connlist */\n        if (ctx->connlist->conn == conn) {\n            item = ctx->connlist;\n            ctx->connlist = item->next;\n            strophe_free(ctx, item);\n        } else {\n            prev = NULL;\n            item = ctx->connlist;\n            while (item && item->conn != conn) {\n                prev = item;\n                item = item->next;\n            }\n\n            if (!item) {\n                strophe_error(ctx, \"xmpp\",\n                              \"Connection not in context's list\\n\");\n            } else {\n                prev->next = item->next;\n                strophe_free(ctx, item);\n            }\n        }\n\n        _conn_reset(conn);\n\n        /* free handler stuff\n         * note that userdata is the responsibility of the client\n         * and the handler pointers don't need to be freed since they\n         * are pointers to functions */\n\n        hlitem = conn->timed_handlers;\n        while (hlitem) {\n            thli = hlitem;\n            hlitem = hlitem->next;\n\n            strophe_free(ctx, thli);\n        }\n\n        /* id handlers\n         * we have to traverse the hash table freeing list elements\n         * then release the hash table */\n        iter = hash_iter_new(conn->id_handlers);\n        while ((key = hash_iter_next(iter))) {\n            hlitem = (xmpp_handlist_t *)hash_get(conn->id_handlers, key);\n            while (hlitem) {\n                thli = hlitem;\n                hlitem = hlitem->next;\n                strophe_free(conn->ctx, thli->u.id);\n                strophe_free(conn->ctx, thli);\n            }\n        }\n        hash_iter_release(iter);\n        hash_release(conn->id_handlers);\n\n        hlitem = conn->handlers;\n        while (hlitem) {\n            thli = hlitem;\n            hlitem = hlitem->next;\n\n            if (thli->u.ns)\n                strophe_free(ctx, thli->u.ns);\n            if (thli->u.name)\n                strophe_free(ctx, thli->u.name);\n            if (thli->u.type)\n                strophe_free(ctx, thli->u.type);\n            strophe_free(ctx, thli);\n        }\n\n        parser_free(conn->parser);\n\n        if (conn->jid)\n            strophe_free(ctx, conn->jid);\n        if (conn->pass)\n            strophe_free(ctx, conn->pass);\n        if (conn->lang)\n            strophe_free(ctx, conn->lang);\n        if (conn->tls_client_cert)\n            strophe_free(ctx, conn->tls_client_cert);\n        if (conn->tls_client_key)\n            strophe_free(ctx, conn->tls_client_key);\n        if (conn->tls_cafile)\n            strophe_free(ctx, conn->tls_cafile);\n        if (conn->tls_capath)\n            strophe_free(ctx, conn->tls_capath);\n        if (conn->sm_state)\n            xmpp_free_sm_state(conn->sm_state);\n        tls_clear_password_cache(conn);\n        sock_free(conn->xsock);\n        strophe_free(ctx, conn);\n        released = 1;\n    }\n\n    return released;\n}\n\n/** Get the JID which is or will be bound to the connection.\n *\n *  @param conn a Strophe connection object\n *\n *  @return a string containing the full JID or NULL if it has not been set\n *\n *  @ingroup Connections\n */\nconst char *xmpp_conn_get_jid(const xmpp_conn_t *conn)\n{\n    return conn->jid;\n}\n\n/**\n * Get the JID discovered during binding time.\n *\n * This JID will contain the resource used by the current connection.\n * This is useful in the case where a resource was not specified for\n * binding.\n *\n * @param conn a Strophe connection object.\n *\n * @return a string containing the full JID or NULL if it's not been discovered\n *\n * @ingroup Connections\n */\nconst char *xmpp_conn_get_bound_jid(const xmpp_conn_t *conn)\n{\n    return conn->bound_jid;\n}\n\n/** Set the JID of the user that will be bound to the connection.\n *  If any JID was previously set, it will be discarded.  This should not be\n *  be used after a connection is created.  The function will make a copy of\n *  the JID string.  If the supplied JID is missing the node, SASL\n *  ANONYMOUS authentication will be used.\n *\n *  @param conn a Strophe connection object\n *  @param jid a full or bare JID\n *\n *  @ingroup Connections\n */\nvoid xmpp_conn_set_jid(xmpp_conn_t *conn, const char *jid)\n{\n    if (conn->jid)\n        strophe_free(conn->ctx, conn->jid);\n    conn->jid = strophe_strdup(conn->ctx, jid);\n}\n\n/** Set the Handler function which will be called when the TLS stack can't\n *  verify the CA of the server we're trying to connect to.\n *\n *  @param conn a Strophe connection object\n *  @param hndl certfail Handler function\n *\n *  @ingroup TLS\n */\nvoid xmpp_conn_set_certfail_handler(xmpp_conn_t *const conn,\n                                    xmpp_certfail_handler hndl)\n{\n    conn->certfail_handler = hndl;\n}\n\n/** Set the CAfile\n *\n *  @param conn a Strophe connection object\n *  @param path path to a certificate file\n *\n *  @ingroup TLS\n */\nvoid xmpp_conn_set_cafile(xmpp_conn_t *const conn, const char *path)\n{\n    if (conn->tls_cafile)\n        strophe_free(conn->ctx, conn->tls_cafile);\n    conn->tls_cafile = strophe_strdup(conn->ctx, path);\n}\n\n/** Set the CApath\n *\n *  @param conn a Strophe connection object\n *  @param path path to a folder containing certificates\n *\n *  @ingroup TLS\n */\nvoid xmpp_conn_set_capath(xmpp_conn_t *const conn, const char *path)\n{\n    if (conn->tls_capath)\n        strophe_free(conn->ctx, conn->tls_capath);\n    conn->tls_capath = strophe_strdup(conn->ctx, path);\n}\n\n/** Retrieve the peer certificate\n *\n *  The returned Certificate object must be free'd by calling\n *  \\ref xmpp_tlscert_free\n *\n *  @param conn a Strophe connection object\n *\n *  @return a Strophe Certificate object\n *\n *  @ingroup TLS\n */\nxmpp_tlscert_t *xmpp_conn_get_peer_cert(xmpp_conn_t *const conn)\n{\n    return tls_peer_cert(conn);\n}\n\n/** Set the Callback function which will be called when the TLS stack can't\n *  decrypt a password protected key file.\n *\n *  @param conn a   Strophe connection object\n *  @param cb       The callback function that shall be called\n *  @param userdata An opaque data pointer that will be passed to the callback\n *\n *  @ingroup TLS\n */\nvoid xmpp_conn_set_password_callback(xmpp_conn_t *conn,\n                                     xmpp_password_callback cb,\n                                     void *userdata)\n{\n    conn->password_callback = cb;\n    conn->password_callback_userdata = userdata;\n}\n\n/** Set the number of retry attempts to decrypt a private key file.\n *\n *  In case the user enters the password manually it can be useful to\n *  directly retry if the decryption of the key file failed.\n *\n *  @param conn a   Strophe connection object\n *  @param retries  The number of retries that should be tried\n *\n *  @ingroup TLS\n */\nvoid xmpp_conn_set_password_retries(xmpp_conn_t *conn, unsigned int retries)\n{\n    if (retries == 0)\n        conn->password_retries = 1;\n    else\n        conn->password_retries = retries;\n}\n\n/** Retrieve the path of the key file that shall be unlocked.\n *\n *  This makes usually sense to be called from the\n *  \\ref xmpp_password_callback .\n *\n *  @param conn a Strophe connection object\n *\n *  @return a String of the path to the key file\n *\n *  @ingroup TLS\n */\nconst char *xmpp_conn_get_keyfile(const xmpp_conn_t *conn)\n{\n    return conn->tls_client_key;\n}\n\n/** Set the Client Certificate and Private Key or PKCS#12 encoded file that\n *  will be bound to the connection. If any of them was previously set, it\n *  will be discarded. This should not be used after a connection is created.\n *  The function will make a copy of the strings passed in.\n *\n *  In case the Private Key is encrypted, a callback must be set via\n *  \\ref xmpp_conn_set_password_callback so the TLS stack can retrieve the\n *  password.\n *\n *  In case one wants to use a PKCS#12 encoded file, it should be passed via\n *  the `cert` parameter and `key` should be NULL. Passing a PKCS#12 file in\n *  `key` is deprecated.\n *\n *  @param conn a Strophe connection object\n *  @param cert path to a certificate file or a P12 file\n *  @param key path to a private key file or a P12 file\n *\n *  @ingroup TLS\n */\nvoid xmpp_conn_set_client_cert(xmpp_conn_t *const conn,\n                               const char *const cert,\n                               const char *const key)\n{\n    strophe_debug(conn->ctx, \"conn\", \"set client cert %s %s\", cert, key);\n    if (conn->tls_client_cert)\n        strophe_free(conn->ctx, conn->tls_client_cert);\n    conn->tls_client_cert = NULL;\n    if (conn->tls_client_key)\n        strophe_free(conn->ctx, conn->tls_client_key);\n    conn->tls_client_key = NULL;\n    if (cert && key) {\n        conn->tls_client_cert = strophe_strdup(conn->ctx, cert);\n        conn->tls_client_key = strophe_strdup(conn->ctx, key);\n    } else if (cert && !key) {\n        conn->tls_client_cert = strophe_strdup(conn->ctx, cert);\n    } else if (!cert && key) {\n        strophe_warn(conn->ctx, \"xmpp\",\n                     \"xmpp_conn_set_client_cert: Passing PKCS#12 in 'key' \"\n                     \"parameter is deprecated. Use 'cert' instead\");\n        conn->tls_client_cert = strophe_strdup(conn->ctx, key);\n    }\n}\n\n/** Get the number of xmppAddr entries in the client certificate.\n *\n *  @param conn a Strophe connection object\n *\n *  @return the number of xmppAddr entries in the client certificate\n *\n *  @ingroup TLS\n */\nunsigned int xmpp_conn_cert_xmppaddr_num(xmpp_conn_t *const conn)\n{\n    return tls_id_on_xmppaddr_num(conn);\n}\n\n/** Get a specific xmppAddr entry.\n *\n *  @param conn a Strophe connection object\n *  @param n the index of the entry, starting at 0\n *\n *  @return a string containing the xmppAddr or NULL if n is out of range\n *\n *  @ingroup TLS\n */\nchar *xmpp_conn_cert_xmppaddr(xmpp_conn_t *const conn, unsigned int n)\n{\n    return tls_id_on_xmppaddr(conn, n);\n}\n\n/** Get the password used for authentication of a connection.\n *\n *  @param conn a Strophe connection object\n *\n *  @return a string containing the password or NULL if it has not been set\n *\n *  @ingroup Connections\n */\nconst char *xmpp_conn_get_pass(const xmpp_conn_t *conn)\n{\n    return conn->pass;\n}\n\n/** Set the password used to authenticate the connection.\n *  If any password was previously set, it will be discarded.  The function\n *  will make a copy of the password string.\n *\n *  @param conn a Strophe connection object\n *  @param pass the password\n *\n *  @ingroup Connections\n */\nvoid xmpp_conn_set_pass(xmpp_conn_t *conn, const char *pass)\n{\n    if (conn->pass)\n        strophe_free(conn->ctx, conn->pass);\n    conn->pass = pass ? strophe_strdup(conn->ctx, pass) : NULL;\n}\n\n/** Get the strophe context that the connection is associated with.\n *  @param conn a Strophe connection object\n *\n *  @return a Strophe context\n *\n *  @ingroup Connections\n */\nxmpp_ctx_t *xmpp_conn_get_context(xmpp_conn_t *conn)\n{\n    return conn->ctx;\n}\n\n/** Initiate a connection to the XMPP server.\n *  This function returns immediately after starting the connection\n *  process to the XMPP server, and notifications of connection state changes\n *  will be sent to the callback function.  The domain and port to connect to\n *  are usually determined by an SRV lookup for the xmpp-client service at\n *  the domain specified in the JID.  If SRV lookup fails, altdomain and\n *  altport will be used instead if specified.\n *\n *  @param conn a Strophe connection object\n *  @param altdomain a string with domain to use if SRV lookup fails.  If this\n *      is NULL, the domain from the JID will be used.\n *  @param altport an integer port number to use if SRV lookup fails.  If this\n *      is 0, the default port will be assumed.\n *  @param callback a xmpp_conn_handler callback function that will receive\n *      notifications of connection status\n *  @param userdata an opaque data pointer that will be passed to the callback\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Connections\n */\nint xmpp_connect_client(xmpp_conn_t *conn,\n                        const char *altdomain,\n                        unsigned short altport,\n                        xmpp_conn_handler callback,\n                        void *userdata)\n{\n    char *domain;\n    int rc;\n\n    if (!conn->jid && (conn->tls_client_cert || conn->tls_client_key)) {\n        if (tls_id_on_xmppaddr_num(conn) != 1) {\n            strophe_debug(conn->ctx, \"xmpp\",\n                          \"Client certificate contains multiple or no xmppAddr \"\n                          \"and no JID was given to be used.\");\n            return XMPP_EINVOP;\n        }\n        conn->jid = tls_id_on_xmppaddr(conn, 0);\n        if (!conn->jid)\n            return XMPP_EMEM;\n        strophe_debug(conn->ctx, \"xmpp\", \"Use jid %s from id-on-xmppAddr.\",\n                      conn->jid);\n    }\n\n    if (!conn->jid) {\n        strophe_error(conn->ctx, \"xmpp\", \"JID is not set.\");\n        return XMPP_EINVOP;\n    }\n\n    domain = xmpp_jid_domain(conn->ctx, conn->jid);\n    if (!domain)\n        return XMPP_EMEM;\n\n    if (!conn->sm_state) {\n        conn->sm_state = strophe_alloc(conn->ctx, sizeof(*conn->sm_state));\n        if (!conn->sm_state)\n            goto err_mem;\n        memset(conn->sm_state, 0, sizeof(*conn->sm_state));\n        conn->sm_state->ctx = conn->ctx;\n    }\n\n    if (altdomain != NULL)\n        strophe_debug(conn->ctx, \"conn\", \"Connecting via altdomain.\");\n\n    if (conn->tls_legacy_ssl && !altdomain) {\n        /* SSL tunneled connection on 5223 port is legacy and doesn't\n         * have an SRV record. */\n        altdomain = domain;\n    }\n    altport = altport ? altport : _conn_default_port(conn, XMPP_CLIENT);\n\n    if (conn->xsock)\n        sock_free(conn->xsock);\n    conn->xsock = sock_new(conn, domain, altdomain, altport);\n    if (!conn->xsock)\n        goto err_mem;\n\n    rc = _conn_connect(conn, domain, XMPP_CLIENT, callback, userdata);\n    strophe_free(conn->ctx, domain);\n\n    return rc;\n\nerr_mem:\n    strophe_free(conn->ctx, domain);\n    return XMPP_EMEM;\n}\n\n/** Initiate a component connection to server.\n *  This function returns immediately after starting the connection\n *  process to the XMPP server, and notifications of connection state changes\n *  will be sent to the internal callback function that will set up handler\n *  for the component handshake as defined in XEP-0114.\n *  The domain and port to connect to must be provided in this case as the JID\n *  provided to the call serves as component identifier to the server and is\n *  not subject to DNS resolution.\n *\n *  @param conn a Strophe connection object\n *  @param server a string with domain to use directly as the domain can't be\n *      extracted from the component name/JID. If this is not set, the call\n *      will fail.\n *  @param port an integer port number to use to connect to server expecting\n *      an external component.  If this is 0, the port 5347 will be assumed.\n *  @param callback a xmpp_conn_handler callback function that will receive\n *      notifications of connection status\n *  @param userdata an opaque data pointer that will be passed to the callback\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Connections\n */\nint xmpp_connect_component(xmpp_conn_t *conn,\n                           const char *server,\n                           unsigned short port,\n                           xmpp_conn_handler callback,\n                           void *userdata)\n{\n    /*  The server domain, jid and password MUST be specified. */\n    if (!(server && conn->jid && conn->pass))\n        return XMPP_EINVOP;\n\n    /* XEP-0114 does not support TLS */\n    (void)xmpp_conn_set_flags(conn, xmpp_conn_get_flags(conn) |\n                                        XMPP_CONN_FLAG_DISABLE_TLS);\n    if (!conn->tls_disabled) {\n        strophe_error(conn->ctx, \"conn\",\n                      \"Failed to disable TLS. \"\n                      \"XEP-0114 does not support TLS\");\n        return XMPP_EINT;\n    }\n\n    port = port ? port : _conn_default_port(conn, XMPP_COMPONENT);\n    if (conn->xsock)\n        sock_free(conn->xsock);\n    conn->xsock = sock_new(conn, NULL, server, port);\n    if (!conn->xsock)\n        return XMPP_EMEM;\n\n    /* JID serves as an identifier here and will be used as \"to\" attribute\n       of the stream */\n    return _conn_connect(conn, conn->jid, XMPP_COMPONENT, callback, userdata);\n}\n\n/** Initiate a raw connection to the XMPP server.\n *  Arguments and behaviour of the function are similar to\n *  xmpp_connect_client(), but it skips authentication process. In opposite to\n *  xmpp_connect_client() during connection process two events are generated\n *  instead of one. User's callback is called with event XMPP_CONN_RAW_CONNECT\n *  when the TCP connection with the server is established. At this point user\n *  might want to open an XMPP stream with xmpp_conn_open_stream() or establish\n *  TLS session with xmpp_conn_tls_start(). Event XMPP_CONN_CONNECT is generated\n *  when the XMPP stream is opened successfully and user may send stanzas over\n *  the connection.\n *\n *  This function doesn't use password nor node part of a jid. Therefore,\n *  the only required configuration is a domain (or full jid) passed via\n *  xmpp_conn_set_jid().\n *\n *  @see xmpp_connect_client()\n *\n *  @return XMPP_EOK (0) on success a number less than 0 on failure\n *\n *  @ingroup Connections\n */\nint xmpp_connect_raw(xmpp_conn_t *conn,\n                     const char *altdomain,\n                     unsigned short altport,\n                     xmpp_conn_handler callback,\n                     void *userdata)\n{\n    conn->is_raw = 1;\n    return xmpp_connect_client(conn, altdomain, altport, callback, userdata);\n}\n\n/* Called when tcp connection is established. */\nvoid conn_established(xmpp_conn_t *conn)\n{\n    if (conn->tls_legacy_ssl && !conn->is_raw) {\n        strophe_debug(conn->ctx, \"xmpp\", \"using legacy SSL connection\");\n        if (conn_tls_start(conn) != 0) {\n            conn_disconnect(conn);\n            return;\n        }\n    }\n\n    if (conn->is_raw) {\n        handler_reset_timed(conn, 0);\n        /* we skip all the mandatory steps of the stream negotiation for a \"raw\"\n           connection, but the event loop ignores user's handlers when\n           conn->stream_negotiation_completed is not set. */\n        conn->stream_negotiation_completed = 1;\n        conn->conn_handler(conn, XMPP_CONN_RAW_CONNECT, 0, NULL,\n                           conn->userdata);\n    } else {\n        /* send stream init */\n        conn_open_stream(conn);\n    }\n}\n\n/** Send the default opening stream tag.\n *  The default tag is the one sent by xmpp_connect_client().\n *  User's connection handler is called with event XMPP_CONN_CONNECT when\n *  server replies with its opening tag.\n *\n *  @return XMPP_EOK (0) on success a number less than 0 on failure\n *\n *  @note The connection must be connected with xmpp_connect_raw().\n *\n *  @ingroup Connections\n */\nint xmpp_conn_open_stream_default(xmpp_conn_t *conn)\n{\n    if (!conn->is_raw)\n        return XMPP_EINVOP;\n\n    conn_prepare_reset(conn, auth_handle_open_raw);\n    conn_open_stream(conn);\n\n    return XMPP_EOK;\n}\n\n/** Send an opening stream tag.\n *  User's connection handler is called with event XMPP_CONN_CONNECT when\n *  server replies with its opening tag.\n *\n *  @param conn a Strophe connection object\n *  @param attributes Array of strings in format: even index points to\n *      an attribute name and odd index points to its value\n *  @param attributes_len Number of elements in the attributes array, it\n *      should be number of attributes multiplied by 2\n *\n *  @return XMPP_EOK (0) on success a number less than 0 on failure\n *\n *  @note The connection must be connected with xmpp_connect_raw().\n *\n *  @ingroup Connections\n */\nint xmpp_conn_open_stream(xmpp_conn_t *conn,\n                          char **attributes,\n                          size_t attributes_len)\n{\n    if (!conn->is_raw)\n        return XMPP_EINVOP;\n\n    conn_prepare_reset(conn, auth_handle_open_raw);\n\n    return _conn_open_stream_with_attributes(conn, attributes, attributes_len);\n}\n\n/** Start synchronous TLS handshake with the server.\n *\n *  @return XMPP_EOK (0) on success a number less than 0 on failure\n *\n *  @ingroup Connections\n */\nint xmpp_conn_tls_start(xmpp_conn_t *conn)\n{\n    return conn_tls_start(conn);\n}\n\n/** Cleanly disconnect the connection.\n *  This function is only called by the stream parser when </stream:stream>\n *  is received, and it not intended to be called by code outside of Strophe.\n *\n *  @param conn a Strophe connection object\n */\nvoid conn_disconnect_clean(xmpp_conn_t *conn)\n{\n    /* remove the timed handler */\n    xmpp_timed_handler_delete(conn, _disconnect_cleanup);\n\n    conn_disconnect(conn);\n}\n\n/** Disconnect from the XMPP server.\n *  This function immediately disconnects from the XMPP server, and should\n *  not be used outside of the Strophe library.\n *\n *  @param conn a Strophe connection object\n */\nvoid conn_disconnect(xmpp_conn_t *conn)\n{\n    strophe_debug(conn->ctx, \"xmpp\", \"Closing socket.\");\n    conn->state = XMPP_STATE_DISCONNECTED;\n    conn->stream_negotiation_completed = 0;\n    if (conn->tls) {\n        tls_stop(conn->tls);\n        tls_free(conn->tls);\n        conn->tls = NULL;\n    }\n    if (conn->sock != INVALID_SOCKET)\n        sock_close(conn->sock);\n    _reset_sm_state_for_reconnect(conn);\n\n    /* fire off connection handler */\n    conn->conn_handler(conn, XMPP_CONN_DISCONNECT, conn->error,\n                       conn->stream_error, conn->userdata);\n}\n\n/* prepares a parser reset.  this is called from handlers. we can't\n * reset the parser immediately as it is not re-entrant. */\nvoid conn_prepare_reset(xmpp_conn_t *conn, xmpp_open_handler handler)\n{\n    conn->reset_parser = 1;\n    conn->open_handler = handler;\n}\n\n/* reset the parser */\nvoid conn_parser_reset(xmpp_conn_t *conn)\n{\n    conn->reset_parser = 0;\n    parser_reset(conn->parser);\n}\n\n/** Initiate termination of the connection to the XMPP server.\n *  This function starts the disconnection sequence by sending\n *  </stream:stream> to the XMPP server.  This function will do nothing\n *  if the connection state is different from CONNECTING or CONNECTED.\n *\n *  @param conn a Strophe connection object\n *\n *  @ingroup Connections\n */\nvoid xmpp_disconnect(xmpp_conn_t *conn)\n{\n    if (conn->state != XMPP_STATE_CONNECTING &&\n        conn->state != XMPP_STATE_CONNECTED)\n        return;\n\n    /* close the stream */\n    send_raw_string(conn, \"</stream:stream>\");\n\n    /* setup timed handler in case disconnect takes too long */\n    handler_add_timed(conn, _disconnect_cleanup, DISCONNECT_TIMEOUT, NULL);\n}\n\n/** Send a raw string to the XMPP server.\n *  This function is a convenience function to send raw string data to the\n *  XMPP server.  It is used by Strophe to send short messages instead of\n *  building up an XML stanza with DOM methods.  This should be used with care\n *  as it does not validate the data; invalid data may result in immediate\n *  stream termination by the XMPP server.\n *\n *  @param conn a Strophe connection object\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n *\n *  @ingroup Connections\n */\nvoid xmpp_send_raw_string(xmpp_conn_t *conn, const char *fmt, ...)\n{\n    va_list ap;\n\n    if (!_is_connected(conn, XMPP_QUEUE_USER))\n        return;\n\n    va_start(ap, fmt);\n    _send_valist(conn, fmt, ap, XMPP_QUEUE_USER);\n    va_end(ap);\n}\n\n/** Send raw bytes to the XMPP server.\n *  This function is a convenience function to send raw bytes to the\n *  XMPP server.  It is used primarily by xmpp_send_raw_string().  This\n *  function should be used with care as it does not validate the bytes and\n *  invalid data may result in stream termination by the XMPP server.\n *\n *  @param conn a Strophe connection object\n *  @param data a buffer of raw bytes\n *  @param len the length of the data in the buffer\n *\n *  @ingroup Connections\n */\nvoid xmpp_send_raw(xmpp_conn_t *conn, const char *data, size_t len)\n{\n    send_raw(conn, data, len, XMPP_QUEUE_USER, NULL);\n}\n\n/** Send an XML stanza to the XMPP server.\n *  This is the main way to send data to the XMPP server.  The function will\n *  terminate without action if the connection state is not CONNECTED.\n *\n *  @param conn a Strophe connection object\n *  @param stanza a Strophe stanza object\n *\n *  @ingroup Connections\n */\nvoid xmpp_send(xmpp_conn_t *conn, xmpp_stanza_t *stanza)\n{\n    send_stanza(conn, xmpp_stanza_clone(stanza), XMPP_QUEUE_USER);\n}\n\n/** Send the opening &lt;stream:stream&gt; tag to the server.\n *  This function is used by Strophe to begin an XMPP stream.  It should\n *  not be used outside of the library.\n *\n *  @param conn a Strophe connection object\n */\nvoid conn_open_stream(xmpp_conn_t *conn)\n{\n    size_t attributes_len;\n    int rc;\n    char *from = NULL;\n    char *ns = conn->type == XMPP_CLIENT ? XMPP_NS_CLIENT : XMPP_NS_COMPONENT;\n    char *attributes[12] = {\n        \"to\",           conn->domain,    \"xml:lang\", conn->lang,\n        \"version\",      \"1.0\",           \"xmlns\",    ns,\n        \"xmlns:stream\", XMPP_NS_STREAMS, \"from\",     NULL};\n\n    attributes_len = ARRAY_SIZE(attributes);\n    if (conn->tls && conn->jid && strchr(conn->jid, '@') != NULL)\n        from = xmpp_jid_bare(conn->ctx, conn->jid);\n\n    if (from)\n        attributes[attributes_len - 1] = from;\n    else\n        attributes_len -= 2;\n\n    rc = _conn_open_stream_with_attributes(conn, attributes, attributes_len);\n    if (rc != XMPP_EOK) {\n        strophe_error(conn->ctx, \"conn\",\n                      \"Cannot build stream tag: memory error\");\n        conn_disconnect(conn);\n    }\n    if (from)\n        strophe_free(conn->ctx, from);\n}\n\nint conn_interface_write(struct conn_interface *intf,\n                         const void *buff,\n                         size_t len)\n{\n    int ret = intf->write(intf, buff, len);\n    if (ret < 0 && !intf->error_is_recoverable(intf, intf->get_error(intf))) {\n        intf->conn->error = intf->get_error(intf);\n    }\n    return ret;\n}\n\nint conn_int_nop(struct conn_interface *intf)\n{\n    UNUSED(intf);\n    return 0;\n}\n\nint conn_tls_start(xmpp_conn_t *conn)\n{\n    int rc;\n\n    if (conn->tls_disabled) {\n        conn->tls = NULL;\n        rc = XMPP_EINVOP;\n    } else {\n        conn->tls = tls_new(conn);\n        rc = conn->tls == NULL ? XMPP_EMEM : 0;\n    }\n\n    if (conn->tls != NULL) {\n        struct conn_interface old_intf = conn->intf;\n        conn->intf = tls_intf;\n        conn->intf.conn = conn;\n        if (tls_start(conn->tls)) {\n            conn->secured = 1;\n        } else {\n            rc = XMPP_EINT;\n            conn->error = tls_error(&conn->intf);\n            tls_free(conn->tls);\n            conn->tls = NULL;\n            conn->tls_failed = 1;\n            conn->intf = old_intf;\n        }\n    }\n    if (rc != 0) {\n        strophe_debug(conn->ctx, \"conn\",\n                      \"Couldn't start TLS! \"\n                      \"error %d tls_error %d\",\n                      rc, conn->error);\n    }\n    return rc;\n}\n\n/** Return applied flags for the connection.\n *\n *  @param conn a Strophe connection object\n *\n *  @return ORed connection flags that are applied for the connection.\n *\n *  @ingroup Connections\n */\nlong xmpp_conn_get_flags(const xmpp_conn_t *conn)\n{\n    long flags;\n\n    flags =\n        XMPP_CONN_FLAG_DISABLE_TLS * conn->tls_disabled |\n        XMPP_CONN_FLAG_MANDATORY_TLS * conn->tls_mandatory |\n        XMPP_CONN_FLAG_LEGACY_SSL * conn->tls_legacy_ssl |\n        XMPP_CONN_FLAG_TRUST_TLS * conn->tls_trust |\n        XMPP_CONN_FLAG_DISABLE_SM * conn->sm_disable |\n        XMPP_CONN_FLAG_ENABLE_COMPRESSION * conn->compression.allowed |\n        XMPP_CONN_FLAG_COMPRESSION_DONT_RESET * conn->compression.dont_reset |\n        XMPP_CONN_FLAG_LEGACY_AUTH * conn->auth_legacy_enabled;\n\n    return flags;\n}\n\n/** Set flags for the connection.\n *  This function applies set flags and resets unset ones. Default connection\n *  configuration is all flags unset. Flags can be applied only for a connection\n *  in disconnected state.\n *  All unsupported flags are ignored. If a flag is unset after successful set\n *  operation then the flag is not supported by current version.\n *\n *  Supported flags are:\n *\n *    - \\ref XMPP_CONN_FLAG_DISABLE_TLS\n *    - \\ref XMPP_CONN_FLAG_MANDATORY_TLS\n *    - \\ref XMPP_CONN_FLAG_LEGACY_SSL\n *    - \\ref XMPP_CONN_FLAG_TRUST_TLS\n *    - \\ref XMPP_CONN_FLAG_LEGACY_AUTH\n *    - \\ref XMPP_CONN_FLAG_DISABLE_SM\n *    - \\ref XMPP_CONN_FLAG_ENABLE_COMPRESSION\n *    - \\ref XMPP_CONN_FLAG_COMPRESSION_DONT_RESET\n *\n *  @param conn a Strophe connection object\n *  @param flags ORed connection flags\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Connections\n */\nint xmpp_conn_set_flags(xmpp_conn_t *conn, long flags)\n{\n    if (conn->state != XMPP_STATE_DISCONNECTED) {\n        strophe_error(conn->ctx, \"conn\",\n                      \"Flags can be set only \"\n                      \"for disconnected connection\");\n        return XMPP_EINVOP;\n    }\n    if ((flags & XMPP_CONN_FLAG_DISABLE_TLS) &&\n        (flags & (XMPP_CONN_FLAG_MANDATORY_TLS | XMPP_CONN_FLAG_LEGACY_SSL |\n                  XMPP_CONN_FLAG_TRUST_TLS))) {\n        strophe_error(conn->ctx, \"conn\", \"Flags 0x%04lx conflict\", flags);\n        return XMPP_EINVOP;\n    }\n\n    conn->tls_disabled = (flags & XMPP_CONN_FLAG_DISABLE_TLS) ? 1 : 0;\n    conn->tls_mandatory = (flags & XMPP_CONN_FLAG_MANDATORY_TLS) ? 1 : 0;\n    conn->tls_legacy_ssl = (flags & XMPP_CONN_FLAG_LEGACY_SSL) ? 1 : 0;\n    conn->tls_trust = (flags & XMPP_CONN_FLAG_TRUST_TLS) ? 1 : 0;\n    conn->auth_legacy_enabled = (flags & XMPP_CONN_FLAG_LEGACY_AUTH) ? 1 : 0;\n    conn->sm_disable = (flags & XMPP_CONN_FLAG_DISABLE_SM) ? 1 : 0;\n    conn->compression.allowed =\n        (flags & XMPP_CONN_FLAG_ENABLE_COMPRESSION) ? 1 : 0;\n    conn->compression.dont_reset =\n        (flags & XMPP_CONN_FLAG_COMPRESSION_DONT_RESET) ? 1 : 0;\n    flags &= ~(XMPP_CONN_FLAG_DISABLE_TLS | XMPP_CONN_FLAG_MANDATORY_TLS |\n               XMPP_CONN_FLAG_LEGACY_SSL | XMPP_CONN_FLAG_TRUST_TLS |\n               XMPP_CONN_FLAG_LEGACY_AUTH | XMPP_CONN_FLAG_DISABLE_SM |\n               XMPP_CONN_FLAG_ENABLE_COMPRESSION |\n               XMPP_CONN_FLAG_COMPRESSION_DONT_RESET);\n    if (flags) {\n        strophe_error(conn->ctx, \"conn\", \"Flags 0x%04lx unknown\", flags);\n        return XMPP_EINVOP;\n    }\n\n    return 0;\n}\n\n/** Return whether TLS session is established or not.\n *\n *  @return TRUE if TLS session is established and FALSE otherwise\n *\n *  @ingroup Connections\n */\nint xmpp_conn_is_secured(xmpp_conn_t *conn)\n{\n    return conn->secured && !conn->tls_failed && conn->tls != NULL;\n}\n\n/**\n *  @return TRUE if connection is in connecting state and FALSE otherwise\n *\n *  @ingroup Connections\n */\nint xmpp_conn_is_connecting(xmpp_conn_t *conn)\n{\n    return conn->state == XMPP_STATE_CONNECTING ||\n           (conn->state == XMPP_STATE_CONNECTED &&\n            conn->stream_negotiation_completed == 0);\n}\n\nstatic int _is_connected(xmpp_conn_t *conn, xmpp_send_queue_owner_t owner)\n{\n    return conn->state == XMPP_STATE_CONNECTED &&\n           (owner != XMPP_QUEUE_USER ||\n            conn->stream_negotiation_completed == 1);\n}\n\n/**\n *  @return TRUE if connection is established and FALSE otherwise\n *\n *  @ingroup Connections\n */\nint xmpp_conn_is_connected(xmpp_conn_t *conn)\n{\n    return _is_connected(conn, XMPP_QUEUE_USER);\n}\n\n/**\n *  @return TRUE if connection is in disconnected state and FALSE otherwise\n *\n *  @ingroup Connections\n */\nint xmpp_conn_is_disconnected(xmpp_conn_t *conn)\n{\n    return conn->state == XMPP_STATE_DISCONNECTED;\n}\n\n/**\n *  This sets the Stream Management callback function\n *\n *  After setting this API, the library will call the given callback function\n *  each time when the internal SM state is updated.\n *\n *  This can be used in conjunction with \\ref xmpp_conn_restore_sm_state to\n *  e.g. implement a mechanism that retains an SM state over potential\n *  application terminations.\n *\n *  @param conn   a Strophe connection object\n *  @param cb     a callback function or NULL to disable\n *  @param ctx    a context that will be passed on invocation of the callback\n *                function\n *\n *  @ingroup Connections\n */\nvoid xmpp_conn_set_sm_callback(xmpp_conn_t *conn,\n                               xmpp_sm_callback cb,\n                               void *ctx)\n{\n    conn->sm_callback = cb;\n    conn->sm_callback_ctx = ctx;\n}\n\nstruct sm_restore {\n    xmpp_conn_t *conn;\n    const unsigned char *state;\n    const unsigned char *const state_end, *const orig;\n};\n\nstatic int sm_load_u32(struct sm_restore *sm, uint8_t type, uint32_t *val)\n{\n    if (*sm->state != type) {\n        strophe_error(\n            sm->conn->ctx, \"conn\",\n            \"Invalid CBOR type at position %u: 0x%02x, expected: 0x%02x\",\n            sm->state - sm->orig, *sm->state, type);\n        return XMPP_EINVOP;\n    }\n    sm->state++;\n    if ((sm->state + 4) > sm->state_end) {\n        strophe_error(sm->conn->ctx, \"conn\",\n                      \"Provided sm_state data is too short\");\n        return XMPP_EINVOP;\n    }\n    uint32_t v;\n    memcpy(&v, sm->state, 4);\n    sm->state += 4;\n    *val = ntohl(v);\n    return 0;\n}\n\nstatic int sm_load_string(struct sm_restore *sm, char **val, size_t *len)\n{\n    uint32_t l;\n    int ret = sm_load_u32(sm, 0x7a, &l);\n    if (ret)\n        return ret;\n    if ((sm->state + l) > sm->state_end) {\n        strophe_error(sm->conn->ctx, \"conn\",\n                      \"Provided sm_state data is too short\");\n        return XMPP_EINVOP;\n    }\n    *val = strophe_alloc(sm->conn->ctx, l + 1);\n    if (!*val)\n        return XMPP_EMEM;\n    memcpy(*val, sm->state, l);\n    (*val)[l] = '\\0';\n    sm->state += l;\n    *len = l;\n    return 0;\n}\n\n/**\n *  This restores the serialized Stream Management state\n *\n *  After setting this API, the library will call the given callback function\n *  each time when the internal SM state is updated.\n *\n *  This can be used in conjunction with \\ref xmpp_conn_restore_sm_state to\n *  e.g. implement a mechanism that retains an SM state over potential\n *  application terminations.\n *\n *  @param conn            a Strophe connection object\n *  @param sm_state        a buffer as passed to the SM callback\n *  @param sm_state_len    the length of `sm_state`\n *\n *  @ingroup Connections\n */\nint xmpp_conn_restore_sm_state(xmpp_conn_t *conn,\n                               const unsigned char *sm_state,\n                               size_t sm_state_len)\n{\n    /* We can only set the SM state when we're disconnected */\n    if (conn->state != XMPP_STATE_DISCONNECTED) {\n        strophe_error(conn->ctx, \"conn\",\n                      \"SM state can only be set the when we're disconnected\");\n        return XMPP_EINVOP;\n    }\n\n    if (conn->sm_state) {\n        strophe_error(conn->ctx, \"conn\", \"SM state is already set!\");\n        return XMPP_EINVOP;\n    }\n\n    if (sm_state_len < 5 * 6) {\n        strophe_error(conn->ctx, \"conn\", \"Provided sm_state data is too short\");\n        return XMPP_EINVOP;\n    }\n    struct sm_restore sm = {.conn = conn,\n                            .state = sm_state,\n                            .state_end = sm_state + sm_state_len,\n                            .orig = sm_state};\n    /* Check for pointer wrap-around, which should never happen */\n    if (sm.state_end < sm.state) {\n        strophe_error(conn->ctx, \"conn\",\n                      \"Internal error, pointer wrapped around\");\n        return XMPP_EINVOP;\n    }\n\n    if (memcmp(sm.state, \"\\x1a\\x00\\x00\\x00\\x00\", 5) != 0) {\n        strophe_error(conn->ctx, \"conn\", \"Unknown sm_state version\");\n        return XMPP_EINVOP;\n    }\n    sm.state += 5;\n\n    conn->sm_state = strophe_alloc(conn->ctx, sizeof(*conn->sm_state));\n    if (!conn->sm_state)\n        return XMPP_EMEM;\n\n    memset(conn->sm_state, 0, sizeof(*conn->sm_state));\n    conn->sm_state->ctx = conn->ctx;\n\n    conn->sm_state->sm_support = 1;\n    conn->sm_state->sm_enabled = 1;\n    conn->sm_state->can_resume = 1;\n    conn->sm_state->resume = 1;\n\n    int ret;\n    ret = sm_load_u32(&sm, 0x1a, &conn->sm_state->sm_sent_nr);\n    if (ret)\n        goto err_reload;\n\n    ret = sm_load_u32(&sm, 0x1a, &conn->sm_state->sm_handled_nr);\n    if (ret)\n        goto err_reload;\n\n    size_t id_len;\n    ret = sm_load_string(&sm, &conn->sm_state->id, &id_len);\n    if (ret)\n        goto err_reload;\n\n    uint32_t len, i;\n    ret = sm_load_u32(&sm, 0x9a, &len);\n    if (ret)\n        goto err_reload;\n    conn->send_queue_user_len = conn->send_queue_len = len;\n    for (i = 0; i < len; i++) {\n        xmpp_send_queue_t *item = strophe_alloc(conn->ctx, sizeof(*item));\n        if (!item) {\n            ret = XMPP_EMEM;\n            goto err_reload;\n        }\n        memset(item, 0, sizeof(*item));\n\n        if (!conn->send_queue_tail) {\n            conn->send_queue_head = item;\n            conn->send_queue_tail = item;\n        } else {\n            conn->send_queue_tail->next = item;\n            conn->send_queue_tail = item;\n        }\n\n        ret = sm_load_string(&sm, &item->data, &item->len);\n        if (ret)\n            goto err_reload;\n\n        item->owner = XMPP_QUEUE_USER;\n    }\n\n    ret = sm_load_u32(&sm, 0xba, &len);\n    if (ret)\n        goto err_reload;\n    for (i = 0; i < len; i++) {\n        xmpp_send_queue_t *item = strophe_alloc(conn->ctx, sizeof(*item));\n        if (!item) {\n            ret = XMPP_EMEM;\n            goto err_reload;\n        }\n        memset(item, 0, sizeof(*item));\n\n        add_queue_back(&conn->sm_state->sm_queue, item);\n\n        ret = sm_load_u32(&sm, 0x1a, &item->sm_h);\n        if (ret)\n            goto err_reload;\n        ret = sm_load_string(&sm, &item->data, &item->len);\n        if (ret)\n            goto err_reload;\n\n        item->owner = XMPP_QUEUE_USER;\n    }\n\n    return XMPP_EOK;\n\nerr_reload:\n    xmpp_free_sm_state(conn->sm_state);\n    return ret;\n}\n\nstatic int sm_store_u32(unsigned char **next_,\n                        const unsigned char *const end,\n                        uint8_t type,\n                        uint32_t val)\n{\n    unsigned char *next = *next_;\n    if (next + 5 > end)\n        return 1;\n    *next++ = type;\n    uint32_t v = htonl(val);\n    memcpy(next, &v, 4);\n    next += 4;\n    *next_ = next;\n    return 0;\n}\n\nstatic size_t sm_state_serialize(xmpp_conn_t *conn, unsigned char **buf)\n{\n    if (!conn->sm_state->sm_support || !conn->sm_state->sm_enabled ||\n        !conn->sm_state->can_resume) {\n        *buf = NULL;\n        return 0;\n    }\n\n    uint32_t id_len = strlen(conn->sm_state->id);\n    xmpp_send_queue_t *peek = conn->sm_state->sm_queue.head;\n    size_t sm_queue_len = 0;\n    size_t sm_queue_size = 0;\n    while (peek) {\n        sm_queue_len++;\n        sm_queue_size += 10 + peek->len;\n        peek = peek->next;\n    }\n\n    uint32_t send_queue_len = 0;\n    size_t send_queue_size = 0;\n    peek = conn->send_queue_head;\n    while (peek) {\n        send_queue_len++;\n        send_queue_size += 5 + peek->len;\n        peek = peek->next;\n    }\n\n    size_t buf_size =\n        5 + 5 + 5 + 5 + id_len + 5 + send_queue_size + 5 + sm_queue_size;\n    *buf = strophe_alloc(conn->ctx, buf_size);\n    if (*buf == NULL)\n        return 0;\n    unsigned char *next = *buf;\n    const unsigned char *const end = next + buf_size;\n    /* Check for pointer wrap-around, which should never happen */\n    if (end < next) {\n        strophe_error(conn->ctx, \"conn\",\n                      \"Internal error, pointer wrapped around\");\n        return 0;\n    }\n\n    memcpy(next, \"\\x1a\\x00\\x00\\x00\\x00\", 5); // Version\n    next += 5;\n\n    if (sm_store_u32(&next, end, 0x1a, conn->sm_state->sm_sent_nr))\n        goto err_serialize;\n    if (sm_store_u32(&next, end, 0x1a, conn->sm_state->sm_handled_nr))\n        goto err_serialize;\n\n    if (sm_store_u32(&next, end, 0x7a, id_len))\n        goto err_serialize;\n    memcpy(next, conn->sm_state->id, id_len);\n    next += id_len;\n\n    if (sm_store_u32(&next, end, 0x9a, send_queue_len))\n        goto err_serialize;\n\n    peek = conn->send_queue_head;\n    while (peek) {\n        if (sm_store_u32(&next, end, 0x7a, (uint32_t)peek->len))\n            goto err_serialize;\n        if (next + peek->len > end)\n            goto err_serialize;\n        memcpy(next, peek->data, peek->len);\n        next += peek->len;\n        peek = peek->next;\n    }\n\n    if (sm_store_u32(&next, end, 0xba, sm_queue_len))\n        goto err_serialize;\n\n    peek = conn->sm_state->sm_queue.head;\n    while (peek) {\n        if (sm_store_u32(&next, end, 0x1a, peek->sm_h))\n            goto err_serialize;\n\n        if (sm_store_u32(&next, end, 0x7a, (uint32_t)peek->len))\n            goto err_serialize;\n        if (next + peek->len > end)\n            goto err_serialize;\n        memcpy(next, peek->data, peek->len);\n        next += peek->len;\n        peek = peek->next;\n    }\n\n    return buf_size;\n\nerr_serialize:\n    strophe_error(conn->ctx, \"conn\", \"Can't serialize more data, buffer full\");\n    strophe_free(conn->ctx, buf);\n    return 0;\n}\n\nvoid trigger_sm_callback(xmpp_conn_t *conn)\n{\n    if (!conn || !conn->sm_callback)\n        return;\n\n    unsigned char *buf;\n    size_t size = sm_state_serialize(conn, &buf);\n    conn->sm_callback(conn, conn->sm_callback_ctx, buf, size);\n    strophe_free(conn->ctx, buf);\n}\n\nstatic void _reset_sm_state_for_reconnect(xmpp_conn_t *conn)\n{\n    xmpp_sm_state_t *s = conn->sm_state;\n\n    if (s->previd) {\n        strophe_free(conn->ctx, s->previd);\n        s->previd = NULL;\n    }\n\n    if (s->can_resume) {\n        s->previd = s->id;\n        s->id = NULL;\n\n        s->bound_jid = conn->bound_jid;\n        conn->bound_jid = NULL;\n    } else if (s->id) {\n        strophe_free(conn->ctx, s->id);\n        s->id = NULL;\n    }\n\n    s->r_sent = s->sm_enabled = s->sm_support = s->resume = 0;\n\n    if (s->bind) {\n        xmpp_stanza_release(s->bind);\n        s->bind = NULL;\n    }\n}\n\n/**\n *  This returns the Stream Management state of a connection object after\n *  it has been disconnected.\n *  One can then initialise a fresh connection object and set this Stream\n *  Management state by calling \\ref xmpp_conn_set_sm_state\n *\n *  In case one wants to dispose of the state w/o setting it into a fresh\n *  connection object, one can call \\ref xmpp_free_sm_state\n *\n *  After calling this function to retrieve the state, only call one of the\n *  other two.\n *\n *  @param conn   a Strophe connection object\n *  @return The Stream Management state of the connection or NULL on error\n *\n *  @ingroup Connections\n */\nxmpp_sm_state_t *xmpp_conn_get_sm_state(xmpp_conn_t *conn)\n{\n    xmpp_sm_state_t *ret;\n\n    /* We can only return the SM state when we're disconnected */\n    if (conn->state != XMPP_STATE_DISCONNECTED)\n        return NULL;\n\n    ret = conn->sm_state;\n    conn->sm_state = NULL;\n\n    return ret;\n}\n\n/**\n *  @param conn     a Strophe connection object\n *  @param sm_state A Stream Management state returned from a call to\n *                  `xmpp_conn_get_sm_state()`\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Connections\n */\nint xmpp_conn_set_sm_state(xmpp_conn_t *conn, xmpp_sm_state_t *sm_state)\n{\n    /* We can only set the SM state when we're disconnected */\n    if (conn->state != XMPP_STATE_DISCONNECTED) {\n        strophe_error(conn->ctx, \"conn\",\n                      \"SM state can only be set the when we're disconnected\");\n        return XMPP_EINVOP;\n    }\n\n    if (conn->sm_state) {\n        strophe_error(conn->ctx, \"conn\", \"SM state is already set!\");\n        return XMPP_EINVOP;\n    }\n\n    if (conn->ctx != sm_state->ctx) {\n        strophe_error(\n            conn->ctx, \"conn\",\n            \"SM state has to be assigned to connection that stems from \"\n            \"the same context!\");\n        return XMPP_EINVOP;\n    }\n\n    conn->sm_state = sm_state;\n    return XMPP_EOK;\n}\n\nvoid reset_sm_state(xmpp_sm_state_t *sm_state)\n{\n    xmpp_ctx_t *ctx = sm_state->ctx;\n\n    strophe_free_and_null(ctx, sm_state->id);\n    strophe_free_and_null(ctx, sm_state->previd);\n    strophe_free_and_null(ctx, sm_state->bound_jid);\n    if (sm_state->bind)\n        xmpp_stanza_release(sm_state->bind);\n    sm_state->bind = NULL;\n    sm_state->sm_handled_nr = 0;\n    sm_state->sm_sent_nr = 0;\n    sm_state->r_sent = 0;\n}\n\n/**  c.f. \\ref xmpp_conn_get_sm_state for usage documentation\n *\n *  @param sm_state   A Stream Management state returned from a call to\n *                  `xmpp_conn_get_sm_state()`\n *\n *  @ingroup Connections\n */\nvoid xmpp_free_sm_state(xmpp_sm_state_t *sm_state)\n{\n    xmpp_send_queue_t *smq;\n    xmpp_ctx_t *ctx;\n\n    if (!sm_state || !sm_state->ctx)\n        return;\n\n    ctx = sm_state->ctx;\n\n    while ((smq = pop_queue_front(&sm_state->sm_queue))) {\n        strophe_free(ctx, queue_element_free(ctx, smq));\n    }\n\n    reset_sm_state(sm_state);\n    strophe_free(ctx, sm_state);\n}\n\n/**\n *  @return The number of entries in the send queue\n *\n *  @ingroup Connections\n */\nint xmpp_conn_send_queue_len(const xmpp_conn_t *conn)\n{\n    if (conn->send_queue_head && conn->send_queue_head->wip &&\n        conn->send_queue_head->owner == XMPP_QUEUE_USER)\n        return conn->send_queue_user_len - 1;\n    else\n        return conn->send_queue_user_len;\n}\n\nstatic char *_drop_send_queue_element(xmpp_conn_t *conn, xmpp_send_queue_t *e)\n{\n    if (e == conn->send_queue_head)\n        conn->send_queue_head = e->next;\n    if (e == conn->send_queue_tail)\n        conn->send_queue_tail = e->prev;\n    if (!conn->send_queue_head)\n        conn->send_queue_tail = NULL;\n    if (e->prev)\n        e->prev->next = e->next;\n    if (e->next)\n        e->next->prev = e->prev;\n    conn->send_queue_len--;\n    if (e->owner == XMPP_QUEUE_USER)\n        conn->send_queue_user_len--;\n    return queue_element_free(conn->ctx, e);\n}\n\n/** Drop an element of the send queue.\n *  This can be used to manage the send queue in case a server\n *  isn't fast enough in processing the elements you're trying\n *  to send or your outgoing bandwidth isn't fast enough to transfer\n *  everything you want to send out.\n *\n *  @param conn a Strophe connection object\n *  @param which the element that shall be removed\n *\n *  @return The rendered stanza. The pointer returned has to be free'd by the\n *          caller of this function.\n *\n *  @ingroup Connections\n */\nchar *xmpp_conn_send_queue_drop_element(xmpp_conn_t *conn,\n                                        xmpp_queue_element_t which)\n{\n    xmpp_send_queue_t *t;\n    int disconnected = conn->state == XMPP_STATE_DISCONNECTED;\n\n    /* Fast return paths */\n    /* empty queue */\n    if (!conn->send_queue_head)\n        return NULL;\n    /* one element in queue */\n    if (conn->send_queue_head == conn->send_queue_tail) {\n        /* head is already sent out partially */\n        if (conn->send_queue_head->wip && !disconnected)\n            return NULL;\n        /* the element is no USER element */\n        if (conn->send_queue_head->owner != XMPP_QUEUE_USER)\n            return NULL;\n    }\n\n    /* Regular flow */\n    if (which == XMPP_QUEUE_OLDEST) {\n        t = conn->send_queue_head;\n    } else if (which == XMPP_QUEUE_YOUNGEST) {\n        t = conn->send_queue_tail;\n        /* search backwards to find last USER element */\n        while (t && t->owner != XMPP_QUEUE_USER)\n            t = t->prev;\n    } else {\n        strophe_error(conn->ctx, \"conn\", \"Unknown queue element %d\", which);\n        return NULL;\n    }\n    /* there was no USER element in the queue */\n    if (!t)\n        return NULL;\n\n    /* head is already sent out partially */\n    if (t == conn->send_queue_head && t->wip && !disconnected)\n        t = t->next;\n\n    /* search forward to find the first USER element */\n    while (t && t->owner != XMPP_QUEUE_USER)\n        t = t->next;\n\n    /* there was no USER element in the queue we could drop */\n    if (!t)\n        return NULL;\n\n    /* In case there exists a SM stanza that is linked to the\n     * one we're currently dropping, also delete that one.\n     */\n    if (t->next && t->next->userdata == t) {\n        strophe_free(conn->ctx, _drop_send_queue_element(conn, t->next));\n        /* reset the flag, so we restart to send `<r>` stanzas */\n        conn->sm_state->r_sent = 0;\n    }\n    /* Finally drop the element */\n    char *r = _drop_send_queue_element(conn, t);\n    trigger_sm_callback(conn);\n    return r;\n}\n\n/* timed handler for cleanup if normal disconnect procedure takes too long */\nstatic int _disconnect_cleanup(xmpp_conn_t *conn, void *userdata)\n{\n    UNUSED(userdata);\n\n    strophe_debug(conn->ctx, \"xmpp\", \"disconnection forced by cleanup timeout\");\n\n    conn_disconnect(conn);\n\n    return 0;\n}\n\nstatic char *_conn_build_stream_tag(xmpp_conn_t *conn,\n                                    char **attributes,\n                                    size_t attributes_len)\n{\n    char *tag;\n    size_t len;\n    size_t i;\n\n    static const char *tag_head = \"<stream:stream\";\n    static const char *tag_tail = \">\";\n\n    /* ignore the last element unless number is even */\n    attributes_len &= ~(size_t)1;\n\n    len = strlen(tag_head) + strlen(tag_tail);\n    for (i = 0; i < attributes_len; ++i)\n        len += strlen(attributes[i]) + 2;\n    tag = strophe_alloc(conn->ctx, len + 1);\n    if (!tag)\n        return NULL;\n\n    strcpy(tag, tag_head);\n    for (i = 0; i < attributes_len; ++i) {\n        if ((i & 1) == 0) {\n            strcat(tag, \" \");\n            strcat(tag, attributes[i]);\n            strcat(tag, \"=\\\"\");\n        } else {\n            strcat(tag, attributes[i]);\n            strcat(tag, \"\\\"\");\n        }\n    }\n    strcat(tag, tag_tail);\n\n    if (strlen(tag) != len) {\n        strophe_error(conn->ctx, \"xmpp\",\n                      \"Internal error in \"\n                      \"_conn_build_stream_tag().\");\n        strophe_free(conn->ctx, tag);\n        tag = NULL;\n    }\n\n    return tag;\n}\n\nstatic int _conn_open_stream_with_attributes(xmpp_conn_t *conn,\n                                             char **attributes,\n                                             size_t attributes_len)\n{\n    char *tag;\n\n    tag = _conn_build_stream_tag(conn, attributes, attributes_len);\n    if (!tag)\n        return XMPP_EMEM;\n\n    send_raw_string(conn, \"<?xml version=\\\"1.0\\\"?>%s\", tag);\n    strophe_free(conn->ctx, tag);\n\n    return XMPP_EOK;\n}\n\nstatic void _conn_attributes_new(xmpp_conn_t *conn,\n                                 char **attrs,\n                                 char ***attributes,\n                                 size_t *attributes_len)\n{\n    char **array = NULL;\n    size_t nr = 0;\n    size_t i;\n\n    if (attrs) {\n        for (; attrs[nr]; ++nr)\n            ;\n        array = strophe_alloc(conn->ctx, sizeof(*array) * nr);\n        for (i = 0; array && i < nr; ++i) {\n            array[i] = (i & 1) == 0 ? parser_attr_name(conn->ctx, attrs[i])\n                                    : strophe_strdup(conn->ctx, attrs[i]);\n            if (array[i] == NULL)\n                break;\n        }\n        if (!array || i < nr) {\n            strophe_error(conn->ctx, \"xmpp\", \"Memory allocation error.\");\n            _conn_attributes_destroy(conn, array, i);\n            array = NULL;\n            nr = 0;\n        }\n    }\n    *attributes = array;\n    *attributes_len = nr;\n}\n\nstatic void _conn_attributes_destroy(xmpp_conn_t *conn,\n                                     char **attributes,\n                                     size_t attributes_len)\n{\n    size_t i;\n\n    if (attributes) {\n        for (i = 0; i < attributes_len; ++i)\n            strophe_free(conn->ctx, attributes[i]);\n        strophe_free(conn->ctx, attributes);\n    }\n}\n\nstatic void _log_open_tag(xmpp_conn_t *conn, char **attrs)\n{\n    char **attributes;\n    char *tag;\n    size_t nr;\n\n    _conn_attributes_new(conn, attrs, &attributes, &nr);\n    tag = _conn_build_stream_tag(conn, attributes, nr);\n    if (tag) {\n        strophe_debug(conn->ctx, \"xmpp\", \"RECV: %s\", tag);\n        strophe_free(conn->ctx, tag);\n    }\n    _conn_attributes_destroy(conn, attributes, nr);\n}\n\nstatic char *_get_stream_attribute(char **attrs, char *name)\n{\n    int i;\n\n    if (!attrs)\n        return NULL;\n\n    for (i = 0; attrs[i]; i += 2)\n        if (strcmp(name, attrs[i]) == 0)\n            return attrs[i + 1];\n\n    return NULL;\n}\n\nstatic void _handle_stream_start(char *name, char **attrs, void *userdata)\n{\n    xmpp_conn_t *conn = (xmpp_conn_t *)userdata;\n    char *id;\n    int failed = 0;\n\n    if (conn->stream_id)\n        strophe_free(conn->ctx, conn->stream_id);\n    conn->stream_id = NULL;\n\n    if (strcmp(name, \"stream\") == 0) {\n        _log_open_tag(conn, attrs);\n        id = _get_stream_attribute(attrs, \"id\");\n        if (id)\n            conn->stream_id = strophe_strdup(conn->ctx, id);\n\n        if (id && !conn->stream_id) {\n            strophe_error(conn->ctx, \"conn\", \"Memory allocation failed.\");\n            failed = 1;\n        }\n    } else {\n        strophe_error(conn->ctx, \"conn\",\n                      \"Server did not open valid stream.\"\n                      \" name = %s.\",\n                      name);\n        failed = 1;\n    }\n\n    if (!failed) {\n        /* call stream open handler */\n        conn->open_handler(conn);\n    } else {\n        conn_disconnect(conn);\n    }\n}\n\nstatic void _handle_stream_end(char *name, void *userdata)\n{\n    xmpp_conn_t *conn = (xmpp_conn_t *)userdata;\n\n    UNUSED(name);\n\n    /* stream is over */\n    strophe_debug(conn->ctx, \"xmpp\", \"RECV: </stream:stream>\");\n    /* the session has been terminated properly, i.e. it can't be resumed */\n    conn->sm_state->can_resume = 0;\n    trigger_sm_callback(conn);\n    conn_disconnect_clean(conn);\n}\n\nstatic void _handle_stream_stanza(xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_conn_t *conn = (xmpp_conn_t *)userdata;\n    char *buf;\n    size_t len;\n\n    if (xmpp_stanza_to_text(stanza, &buf, &len) == 0) {\n        strophe_debug(conn->ctx, \"xmpp\", \"RECV: %s\", buf);\n        strophe_free(conn->ctx, buf);\n    }\n\n    handler_fire_stanza(conn, stanza);\n    if (conn->sm_state->sm_enabled)\n        _conn_sm_handle_stanza(conn, stanza);\n}\n\n/* XEP-0198 stream management */\nstatic void _conn_sm_handle_stanza(xmpp_conn_t *const conn,\n                                   xmpp_stanza_t *stanza)\n{\n    xmpp_stanza_t *a;\n    xmpp_send_queue_t *e;\n    char *c;\n    const char *name, *ns, *attr_h;\n    char h[11];\n    unsigned long ul_h;\n\n    ns = xmpp_stanza_get_ns(stanza);\n    if (ns && strcmp(ns, XMPP_NS_SM) != 0)\n        ++conn->sm_state->sm_handled_nr;\n    else {\n        name = xmpp_stanza_get_name(stanza);\n        if (!name)\n            return;\n        if (strcmp(name, \"r\") == 0) {\n            a = xmpp_stanza_new(conn->ctx);\n            if (!a) {\n                strophe_debug(conn->ctx, \"conn\", \"Couldn't create <a> stanza.\");\n                return;\n            }\n            xmpp_stanza_set_name(a, \"a\");\n            xmpp_stanza_set_ns(a, XMPP_NS_SM);\n            strophe_snprintf(h, sizeof(h), \"%u\", conn->sm_state->sm_handled_nr);\n            xmpp_stanza_set_attribute(a, \"h\", h);\n            send_stanza(conn, a, XMPP_QUEUE_SM_STROPHE);\n        } else if (strcmp(name, \"a\") == 0) {\n            attr_h = xmpp_stanza_get_attribute(stanza, \"h\");\n            if (!attr_h) {\n                strophe_debug(conn->ctx, \"conn\", \"Didn't find 'h' attribute.\");\n                return;\n            }\n            if (string_to_ul(attr_h, &ul_h)) {\n                strophe_error(\n                    conn->ctx, \"conn\",\n                    \"Error on strtoul() of '%s', returned value is %llu.\",\n                    attr_h, ul_h);\n                /* We continue here and drop the complete SM queue instead of\n                 * returning and letting the queue fill up.\n                 */\n                ul_h = ULONG_MAX;\n            }\n            while (conn->sm_state->sm_queue.head &&\n                   conn->sm_state->sm_queue.head->sm_h < ul_h) {\n                e = pop_queue_front(&conn->sm_state->sm_queue);\n                strophe_debug_verbose(2, conn->ctx, \"conn\",\n                                      \"SM_Q_DROP: %p, h=%lu\", e, e->sm_h);\n                c = queue_element_free(conn->ctx, e);\n                strophe_free(conn->ctx, c);\n            }\n            conn->sm_state->r_sent = 0;\n        }\n    }\n    trigger_sm_callback(conn);\n}\n\nstatic unsigned short _conn_default_port(xmpp_conn_t *conn,\n                                         xmpp_conn_type_t type)\n{\n    switch (type) {\n    case XMPP_CLIENT:\n        return conn->tls_legacy_ssl ? XMPP_PORT_CLIENT_LEGACY_SSL\n                                    : XMPP_PORT_CLIENT;\n    case XMPP_COMPONENT:\n        return XMPP_PORT_COMPONENT;\n    default:\n        return 0;\n    };\n}\n\nchar *queue_element_free(xmpp_ctx_t *ctx, xmpp_send_queue_t *e)\n{\n    char *ret = e->data;\n    strophe_debug_verbose(2, ctx, \"conn\", \"Q_FREE: %p\", e);\n    memset(e, 0, sizeof(*e));\n    strophe_free(ctx, e);\n    strophe_debug_verbose(3, ctx, \"conn\", \"Q_CONTENT: %s\", ret);\n    return ret;\n}\n\nstatic void _conn_reset(xmpp_conn_t *conn)\n{\n    xmpp_ctx_t *ctx = conn->ctx;\n    xmpp_send_queue_t *sq, *tsq;\n\n    if (conn->state != XMPP_STATE_DISCONNECTED) {\n        strophe_debug(ctx, \"conn\", \"Can't reset connected object.\");\n        return;\n    }\n\n    compression_free(conn);\n\n    conn->intf = sock_intf;\n    conn->intf.conn = conn;\n\n    /* free queued */\n    sq = conn->send_queue_head;\n    while (sq) {\n        tsq = sq;\n        sq = sq->next;\n        strophe_free(ctx, queue_element_free(ctx, tsq));\n    }\n    conn->send_queue_head = NULL;\n    conn->send_queue_tail = NULL;\n    conn->send_queue_len = 0;\n    conn->send_queue_user_len = 0;\n\n    if (conn->stream_error) {\n        xmpp_stanza_release(conn->stream_error->stanza);\n        strophe_free_and_null(ctx, conn->stream_error->text);\n        strophe_free_and_null(ctx, conn->stream_error);\n    }\n\n    strophe_free_and_null(ctx, conn->domain);\n    strophe_free_and_null(ctx, conn->bound_jid);\n    strophe_free_and_null(ctx, conn->stream_id);\n    conn->stream_negotiation_completed = 0;\n    conn->secured = 0;\n    conn->tls_failed = 0;\n    conn->error = 0;\n\n    conn->tls_support = 0;\n\n    conn->bind_required = 0;\n    conn->session_required = 0;\n\n    handler_system_delete_all(conn);\n}\n\nstatic int _conn_connect(xmpp_conn_t *conn,\n                         const char *domain,\n                         xmpp_conn_type_t type,\n                         xmpp_conn_handler callback,\n                         void *userdata)\n{\n    xmpp_open_handler open_handler;\n\n    if (conn->state != XMPP_STATE_DISCONNECTED)\n        return XMPP_EINVOP;\n    if (type != XMPP_CLIENT && type != XMPP_COMPONENT)\n        return XMPP_EINVOP;\n\n    _conn_reset(conn);\n\n    conn->type = type;\n    conn->domain = strophe_strdup(conn->ctx, domain);\n    if (!conn->domain)\n        return XMPP_EMEM;\n\n    conn->sock = sock_connect(conn->xsock);\n    if (conn->sock == INVALID_SOCKET)\n        return XMPP_EINT;\n\n    /* setup handler */\n    conn->conn_handler = callback;\n    conn->userdata = userdata;\n\n    open_handler = conn->is_raw          ? auth_handle_open_stub\n                   : type == XMPP_CLIENT ? auth_handle_open\n                                         : auth_handle_component_open;\n    conn_prepare_reset(conn, open_handler);\n\n    /* FIXME: it could happen that the connect returns immediately as\n     * successful, though this is pretty unlikely.  This would be a little\n     * hard to fix, since we'd have to detect and fire off the callback\n     * from within the event loop */\n\n    conn->state = XMPP_STATE_CONNECTING;\n    conn->timeout_stamp = time_stamp();\n\n    return 0;\n}\n\nvoid send_raw(xmpp_conn_t *conn,\n              const char *data,\n              size_t len,\n              xmpp_send_queue_owner_t owner,\n              void *userdata)\n{\n    char *d;\n\n    if (conn->state != XMPP_STATE_CONNECTED)\n        return;\n\n    d = strophe_strndup(conn->ctx, data, len);\n    if (!d) {\n        strophe_error(conn->ctx, \"conn\", \"Failed to strndup\");\n        return;\n    }\n\n    _send_raw(conn, d, len, owner, userdata);\n}\n\nstatic void _send_valist(xmpp_conn_t *conn,\n                         const char *fmt,\n                         va_list ap,\n                         xmpp_send_queue_owner_t owner)\n{\n    va_list apdup;\n    size_t len;\n    char buf[1024]; /* small buffer for common case */\n    char *bigbuf;\n\n    if (!_is_connected(conn, owner))\n        return;\n\n    va_copy(apdup, ap);\n    len = strophe_vsnprintf(buf, sizeof(buf), fmt, apdup);\n    va_end(apdup);\n\n    if (len >= sizeof(buf)) {\n        /* we need more space for this data, so we allocate a big\n         * enough buffer and print to that */\n        len++; /* account for trailing \\0 */\n        bigbuf = strophe_alloc(conn->ctx, len);\n        if (!bigbuf) {\n            strophe_debug(conn->ctx, \"xmpp\",\n                          \"Could not allocate memory for send_raw_string\");\n            return;\n        }\n        va_copy(apdup, ap);\n        strophe_vsnprintf(bigbuf, len, fmt, apdup);\n        va_end(apdup);\n\n        /* len - 1 so we don't send trailing \\0 */\n        _send_raw(conn, bigbuf, len - 1, owner, NULL);\n    } else {\n        /* go through send_raw() which does the strdup() for us */\n        send_raw(conn, buf, len, owner, NULL);\n    }\n}\n\nvoid send_raw_string(xmpp_conn_t *conn, const char *fmt, ...)\n{\n    va_list ap;\n\n    if (conn->state != XMPP_STATE_CONNECTED)\n        return;\n\n    va_start(ap, fmt);\n    _send_valist(conn, fmt, ap, XMPP_QUEUE_SM_STROPHE);\n    va_end(ap);\n}\n\nvoid send_stanza(xmpp_conn_t *conn,\n                 xmpp_stanza_t *stanza,\n                 xmpp_send_queue_owner_t owner)\n{\n    char *buf = NULL;\n    size_t len;\n\n    if (!_is_connected(conn, owner))\n        goto out;\n\n    if (xmpp_stanza_to_text(stanza, &buf, &len) != 0) {\n        strophe_error(conn->ctx, \"conn\", \"Failed to stanza_to_text\");\n        goto out;\n    }\n\n    _send_raw(conn, buf, len, owner, NULL);\nout:\n    xmpp_stanza_release(stanza);\n}\n\nvoid add_queue_back(xmpp_queue_t *queue, xmpp_send_queue_t *item)\n{\n    item->next = NULL;\n    if (!queue->tail) {\n        item->prev = NULL;\n        queue->head = item;\n        queue->tail = item;\n    } else {\n        item->prev = queue->tail;\n        queue->tail->next = item;\n        queue->tail = item;\n    }\n}\n\nxmpp_send_queue_t *peek_queue_front(xmpp_queue_t *queue)\n{\n    return queue->head;\n}\n\nxmpp_send_queue_t *pop_queue_front(xmpp_queue_t *queue)\n{\n    xmpp_send_queue_t *ret = queue->head;\n    if (queue->head) {\n        queue->head = queue->head->next;\n        if (!queue->head) {\n            queue->tail = NULL;\n        } else {\n            queue->head->prev = NULL;\n        }\n        ret->prev = ret->next = NULL;\n    }\n    return ret;\n}\n\nstatic int _send_raw(xmpp_conn_t *conn,\n                     char *data,\n                     size_t len,\n                     xmpp_send_queue_owner_t owner,\n                     void *userdata)\n{\n    xmpp_send_queue_t *item;\n    const char *req_ack = \"<r xmlns='urn:xmpp:sm:3'/>\";\n\n    /* create send queue item for queue */\n    item = strophe_alloc(conn->ctx, sizeof(xmpp_send_queue_t));\n    if (!item) {\n        strophe_error(conn->ctx, \"conn\", \"DROPPED: %s\", data);\n        strophe_free(conn->ctx, data);\n        return XMPP_EMEM;\n    }\n\n    item->data = data;\n    item->len = len;\n    item->next = NULL;\n    item->prev = conn->send_queue_tail;\n    item->written = 0;\n    item->wip = 0;\n    item->userdata = userdata;\n    item->owner = owner;\n\n    if (!conn->send_queue_tail) {\n        /* first item, set head and tail */\n        conn->send_queue_head = item;\n        conn->send_queue_tail = item;\n    } else {\n        /* add to the tail */\n        conn->send_queue_tail->next = item;\n        conn->send_queue_tail = item;\n    }\n    conn->send_queue_len++;\n    if (owner == XMPP_QUEUE_USER)\n        conn->send_queue_user_len++;\n    strophe_debug_verbose(3, conn->ctx, \"conn\", \"QUEUED: %s\", data);\n    strophe_debug_verbose(1, conn->ctx, \"conn\", \"Q_ADD: %p\", item);\n    if (!(owner & XMPP_QUEUE_SM) && conn->sm_state->sm_enabled &&\n        !conn->sm_state->r_sent) {\n        conn->sm_state->r_sent = 1;\n        send_raw(conn, req_ack, strlen(req_ack), XMPP_QUEUE_SM_STROPHE, item);\n    } else {\n        trigger_sm_callback(conn);\n    }\n    return XMPP_EOK;\n}\n"
  },
  {
    "path": "src/crypto.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* crypto.c\n * strophe XMPP client library -- public interface for digests, encodings\n *\n * Copyright (C) 2016 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/** @file\n *  Public interface for digests and encodings used in XEPs.\n */\n\n/** @defgroup Digests Message digests\n */\n\n/** @defgroup Encodings Encodings\n */\n\n#include <assert.h>\n#include <string.h> /* memset, memcpy */\n\n#include \"common.h\"  /* strophe_alloc */\n#include \"ostypes.h\" /* uint8_t, size_t */\n#include \"sha1.h\"\n#include \"snprintf.h\" /* xmpp_snprintf */\n#include \"strophe.h\"  /* xmpp_ctx_t, strophe_free */\n\nstruct _xmpp_sha1_t {\n    xmpp_ctx_t *xmpp_ctx;\n    SHA1_CTX ctx;\n    uint8_t digest[SHA1_DIGEST_SIZE];\n};\n\nstatic char *digest_to_string(const uint8_t *digest, char *s, size_t len)\n{\n    int i;\n\n    if (len < SHA1_DIGEST_SIZE * 2 + 1)\n        return NULL;\n\n    for (i = 0; i < SHA1_DIGEST_SIZE; ++i)\n        strophe_snprintf(s + i * 2, 3, \"%02x\", digest[i]);\n\n    return s;\n}\n\nstatic char *digest_to_string_alloc(xmpp_ctx_t *ctx, const uint8_t *digest)\n{\n    char *s;\n    size_t slen;\n\n    slen = SHA1_DIGEST_SIZE * 2 + 1;\n    s = strophe_alloc(ctx, slen);\n    if (s) {\n        s = digest_to_string(digest, s, slen);\n        assert(s != NULL);\n    }\n    return s;\n}\n\n/** Compute SHA1 message digest.\n *  Returns an allocated string which represents SHA1 message digest in\n *  hexadecimal notation. The string must be freed with xmpp_free().\n *\n *  @param ctx a Strophe context object\n *  @param data buffer for digest computation\n *  @param len size of the data buffer\n *\n *  @return an allocated string or NULL on allocation error\n *\n *  @ingroup Digests\n */\nchar *xmpp_sha1(xmpp_ctx_t *ctx, const unsigned char *data, size_t len)\n{\n    uint8_t digest[SHA1_DIGEST_SIZE];\n\n    crypto_SHA1((const uint8_t *)data, len, digest);\n    return digest_to_string_alloc(ctx, digest);\n}\n\n/** Compute SHA1 message digest.\n *  Stores digest in user's buffer which must be at least XMPP_SHA1_DIGEST_SIZE\n *  bytes long.\n *\n *  @param data buffer for digest computation\n *  @param len size of the data buffer\n *  @param digest output buffer of XMPP_SHA1_DIGEST_SIZE bytes\n *\n *  @ingroup Digests\n */\nvoid xmpp_sha1_digest(const unsigned char *data,\n                      size_t len,\n                      unsigned char *digest)\n{\n    crypto_SHA1((const uint8_t *)data, len, digest);\n}\n\n/** Create new SHA1 object.\n *  SHA1 object is used to compute SHA1 digest of a buffer that is split\n *  in multiple chunks or provided in stream mode. A single buffer can be\n *  processed by short functions xmpp_sha1() and xmpp_sha1_digest().\n *  Follow the next use-case for xmpp_sha1_t object:\n *  @code\n *      xmpp_sha1_t *sha1 = xmpp_sha1_new(ctx);\n *      // Repeat update for all chunks of data\n *      xmpp_sha1_update(sha1, data, len);\n *      xmpp_sha1_final(sha1);\n *      char *digest = xmpp_sha1_to_string_alloc(sha1);\n *      xmpp_sha1_free(sha1);\n *  @endcode\n *\n *  @param ctx a Strophe context object\n *\n *  @return new SHA1 object\n *\n *  @ingroup Digests\n */\nxmpp_sha1_t *xmpp_sha1_new(xmpp_ctx_t *ctx)\n{\n    xmpp_sha1_t *sha1;\n\n    sha1 = strophe_alloc(ctx, sizeof(*sha1));\n    if (sha1) {\n        memset(sha1, 0, sizeof(*sha1));\n        crypto_SHA1_Init(&sha1->ctx);\n        sha1->xmpp_ctx = ctx;\n    }\n    return sha1;\n}\n\n/** Destroy SHA1 object.\n *\n *  @param sha1 a SHA1 object\n *\n *  @ingroup Digests\n */\nvoid xmpp_sha1_free(xmpp_sha1_t *sha1)\n{\n    strophe_free(sha1->xmpp_ctx, sha1);\n}\n\n/** Update SHA1 context with the next portion of data.\n *  Can be called repeatedly.\n *\n *  @param sha1 a SHA1 object\n *  @param data pointer to a buffer to be hashed\n *  @param len size of the data buffer\n *\n *  @ingroup Digests\n */\nvoid xmpp_sha1_update(xmpp_sha1_t *sha1, const unsigned char *data, size_t len)\n{\n    crypto_SHA1_Update(&sha1->ctx, data, len);\n}\n\n/** Finish SHA1 computation.\n *  Don't call xmpp_sha1_update() after this function. Retrieve resulting\n *  message digest with xmpp_sha1_to_string() or xmpp_sha1_to_digest().\n *\n *  @param sha1 a SHA1 object\n *\n *  @ingroup Digests\n */\nvoid xmpp_sha1_final(xmpp_sha1_t *sha1)\n{\n    crypto_SHA1_Final(&sha1->ctx, sha1->digest);\n}\n\n/** Return message digest rendered as a string.\n *  Stores the string to a user's buffer and returns the buffer. Call this\n *  function after xmpp_sha1_final().\n *\n *  @param sha1 a SHA1 object\n *  @param s output string\n *  @param slen size reserved for the string including '\\0'\n *\n *  @return pointer s or NULL if resulting string is bigger than slen bytes\n *\n *  @ingroup Digests\n */\nchar *xmpp_sha1_to_string(xmpp_sha1_t *sha1, char *s, size_t slen)\n{\n    return digest_to_string(sha1->digest, s, slen);\n}\n\n/** Return message digest rendered as a string.\n *  Returns an allocated string. Free the string by calling xmpp_free() using\n *  the Strophe context which is passed to xmpp_sha1_new(). Call this function\n *  after xmpp_sha1_final().\n *\n *  @param sha1 a SHA1 object\n *\n *  @return an allocated string\n *\n *  @ingroup Digests\n */\nchar *xmpp_sha1_to_string_alloc(xmpp_sha1_t *sha1)\n{\n    return digest_to_string_alloc(sha1->xmpp_ctx, sha1->digest);\n}\n\n/** Stores message digest to a user's buffer.\n *\n *  @param sha1 a SHA1 object\n *  @param digest output buffer of XMPP_SHA1_DIGEST_SIZE bytes\n *\n *  @ingroup Digests\n */\nvoid xmpp_sha1_to_digest(xmpp_sha1_t *sha1, unsigned char *digest)\n{\n    assert(SHA1_DIGEST_SIZE == XMPP_SHA1_DIGEST_SIZE);\n    memcpy(digest, sha1->digest, SHA1_DIGEST_SIZE);\n}\n\n/* Base64 encoding routines. Implemented according to RFC 3548. */\n\n/* map of all byte values to the base64 values, or to\n   '65' which indicates an invalid character. '=' is '64' */\nstatic const unsigned char _base64_invcharmap[256] = {\n    65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 62, 65, 65, 65, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60,\n    61, 65, 65, 65, 64, 65, 65, 65, 0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  10,\n    11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 65, 65, 65, 65,\n    65, 65, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,\n    43, 44, 45, 46, 47, 48, 49, 50, 51, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65,\n    65, 65, 65, 65, 65, 65, 65, 65, 65};\n\n/* map of all 6-bit values to their corresponding byte\n   in the base64 alphabet. Padding char is the value '64' */\nstatic const char _base64_charmap[65] = {\n    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',\n    'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',\n    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',\n    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',\n    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '='};\n\nstatic size_t base64_encoded_len(size_t len)\n{\n    /* encoded steam is 4 bytes for every three, rounded up */\n    return ((len + 2) / 3) << 2;\n}\n\nstatic char *\nbase64_encode(xmpp_ctx_t *ctx, const unsigned char *buffer, size_t len)\n{\n    size_t clen;\n    char *cbuf, *c;\n    uint32_t word, hextet;\n    size_t i;\n\n    clen = base64_encoded_len(len);\n    cbuf = strophe_alloc(ctx, clen + 1);\n    if (cbuf != NULL) {\n        c = cbuf;\n        /* loop over data, turning every 3 bytes into 4 characters */\n        for (i = 0; i + 2 < len; i += 3) {\n            word = buffer[i] << 16 | buffer[i + 1] << 8 | buffer[i + 2];\n            hextet = (word & 0x00FC0000) >> 18;\n            *c++ = _base64_charmap[hextet];\n            hextet = (word & 0x0003F000) >> 12;\n            *c++ = _base64_charmap[hextet];\n            hextet = (word & 0x00000FC0) >> 6;\n            *c++ = _base64_charmap[hextet];\n            hextet = (word & 0x000003F);\n            *c++ = _base64_charmap[hextet];\n        }\n        /* zero, one or two bytes left */\n        switch (len - i) {\n        case 0:\n            break;\n        case 1:\n            hextet = (buffer[len - 1] & 0xFC) >> 2;\n            *c++ = _base64_charmap[hextet];\n            hextet = (buffer[len - 1] & 0x03) << 4;\n            *c++ = _base64_charmap[hextet];\n            *c++ = _base64_charmap[64]; /* pad */\n            *c++ = _base64_charmap[64]; /* pad */\n            break;\n        case 2:\n            hextet = (buffer[len - 2] & 0xFC) >> 2;\n            *c++ = _base64_charmap[hextet];\n            hextet = ((buffer[len - 2] & 0x03) << 4) |\n                     ((buffer[len - 1] & 0xF0) >> 4);\n            *c++ = _base64_charmap[hextet];\n            hextet = (buffer[len - 1] & 0x0F) << 2;\n            *c++ = _base64_charmap[hextet];\n            *c++ = _base64_charmap[64]; /* pad */\n            break;\n        }\n        /* add a terminal null */\n        *c = '\\0';\n    }\n    return cbuf;\n}\n\nstatic size_t base64_decoded_len(const char *buffer, size_t len)\n{\n    size_t nudge = 0;\n    unsigned char c;\n    size_t i;\n\n    if (len < 4)\n        return 0;\n\n    /* count the padding characters for the remainder */\n    for (i = len; i > 0; --i) {\n        c = _base64_invcharmap[(unsigned char)buffer[i - 1]];\n        if (c < 64)\n            break;\n        if (c == 64)\n            ++nudge;\n        if (c > 64)\n            return 0;\n    }\n    if (nudge > 2)\n        return 0;\n\n    /* decoded steam is 3 bytes for every four */\n    return 3 * (len >> 2) - nudge;\n}\n\nstatic void base64_decode(xmpp_ctx_t *ctx,\n                          const char *buffer,\n                          size_t len,\n                          unsigned char **out,\n                          size_t *outlen)\n{\n    size_t dlen;\n    unsigned char *dbuf, *d;\n    uint32_t word, hextet = 0;\n    size_t i;\n\n    /* len must be a multiple of 4 */\n    if (len & 0x03)\n        goto _base64_error;\n\n    dlen = base64_decoded_len(buffer, len);\n    if (dlen == 0)\n        goto _base64_error;\n\n    dbuf = strophe_alloc(ctx, dlen + 1);\n    if (dbuf != NULL) {\n        d = dbuf;\n        /* loop over each set of 4 characters, decoding 3 bytes */\n        for (i = 0; i + 3 < len; i += 4) {\n            hextet = _base64_invcharmap[(unsigned char)buffer[i]];\n            if (hextet & 0xC0)\n                break;\n            word = hextet << 18;\n            hextet = _base64_invcharmap[(unsigned char)buffer[i + 1]];\n            if (hextet & 0xC0)\n                break;\n            word |= hextet << 12;\n            hextet = _base64_invcharmap[(unsigned char)buffer[i + 2]];\n            if (hextet & 0xC0)\n                break;\n            word |= hextet << 6;\n            hextet = _base64_invcharmap[(unsigned char)buffer[i + 3]];\n            if (hextet & 0xC0)\n                break;\n            word |= hextet;\n            *d++ = (word & 0x00FF0000) >> 16;\n            *d++ = (word & 0x0000FF00) >> 8;\n            *d++ = (word & 0x000000FF);\n        }\n        if (hextet > 64)\n            goto _base64_decode_error;\n        /* handle the remainder */\n        switch (dlen % 3) {\n        case 0:\n            /* nothing to do */\n            break;\n        case 1:\n            /* redo the last quartet, checking for correctness */\n            hextet = _base64_invcharmap[(unsigned char)buffer[len - 4]];\n            if (hextet & 0xC0)\n                goto _base64_decode_error;\n            word = hextet << 2;\n            hextet = _base64_invcharmap[(unsigned char)buffer[len - 3]];\n            if (hextet & 0xC0)\n                goto _base64_decode_error;\n            word |= hextet >> 4;\n            *d++ = word & 0xFF;\n            hextet = _base64_invcharmap[(unsigned char)buffer[len - 2]];\n            if (hextet != 64)\n                goto _base64_decode_error;\n            hextet = _base64_invcharmap[(unsigned char)buffer[len - 1]];\n            if (hextet != 64)\n                goto _base64_decode_error;\n            break;\n        case 2:\n            /* redo the last quartet, checking for correctness */\n            hextet = _base64_invcharmap[(unsigned char)buffer[len - 4]];\n            if (hextet & 0xC0)\n                goto _base64_decode_error;\n            word = hextet << 10;\n            hextet = _base64_invcharmap[(unsigned char)buffer[len - 3]];\n            if (hextet & 0xC0)\n                goto _base64_decode_error;\n            word |= hextet << 4;\n            hextet = _base64_invcharmap[(unsigned char)buffer[len - 2]];\n            if (hextet & 0xC0)\n                goto _base64_decode_error;\n            word |= hextet >> 2;\n            *d++ = (word & 0xFF00) >> 8;\n            *d++ = (word & 0x00FF);\n            hextet = _base64_invcharmap[(unsigned char)buffer[len - 1]];\n            if (hextet != 64)\n                goto _base64_decode_error;\n            break;\n        }\n        *d = '\\0';\n    }\n    *out = dbuf;\n    *outlen = dbuf == NULL ? 0 : dlen;\n    return;\n\n_base64_decode_error:\n    /* invalid character; abort decoding! */\n    strophe_free(ctx, dbuf);\n_base64_error:\n    *out = NULL;\n    *outlen = 0;\n}\n\n/** Base64 encoding routine.\n *  Returns an allocated string which must be freed with xmpp_free().\n *\n *  @param ctx a Strophe context\n *  @param data buffer to encode\n *  @param len size of the data buffer\n *\n *  @return an allocated null-terminated string or NULL on error\n *\n *  @ingroup Encodings\n */\nchar *xmpp_base64_encode(xmpp_ctx_t *ctx, const unsigned char *data, size_t len)\n{\n    return base64_encode(ctx, data, len);\n}\n\n/** Base64 decoding routine.\n *  Returns an allocated string which must be freed with xmpp_free(). User\n *  calls this function when the result must be a string. When decoded buffer\n *  contains '\\0' NULL is returned.\n *\n *  @param ctx a Strophe context\n *  @param base64 encoded buffer\n *  @param len size of the buffer\n *\n *  @return an allocated null-terminated string or NULL on error\n *\n *  @ingroup Encodings\n */\nchar *xmpp_base64_decode_str(xmpp_ctx_t *ctx, const char *base64, size_t len)\n{\n    unsigned char *buf = NULL;\n    size_t buflen;\n\n    if (len == 0) {\n        /* handle empty string */\n        buf = strophe_alloc(ctx, 1);\n        if (buf)\n            buf[0] = '\\0';\n        buflen = 0;\n    } else {\n        base64_decode(ctx, base64, len, &buf, &buflen);\n    }\n    if (buf) {\n        if (buflen != strlen((char *)buf)) {\n            strophe_free(ctx, buf);\n            buf = NULL;\n        }\n    }\n    return (char *)buf;\n}\n\n/** Base64 decoding routine.\n *  Returns an allocated buffer which must be freed with xmpp_free().\n *\n *  @param ctx a Strophe context\n *  @param base64 encoded buffer\n *  @param len size of the encoded buffer\n *  @param out allocated buffer is stored here\n *  @param outlen size of the allocated buffer\n *\n *  @note on an error the `*out` will be NULL\n *\n *  @ingroup Encodings\n */\nvoid xmpp_base64_decode_bin(xmpp_ctx_t *ctx,\n                            const char *base64,\n                            size_t len,\n                            unsigned char **out,\n                            size_t *outlen)\n{\n    base64_decode(ctx, base64, len, out, outlen);\n}\n"
  },
  {
    "path": "src/ctx.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* ctx.c\n** strophe XMPP client library -- run-time context implementation\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Runtime contexts, library initialization and shutdown, and versioning.\n */\n\n/** @defgroup Context Context objects\n *  These functions create and manipulate Strophe context objects.\n *\n *  In order to support usage in a variety of environments, the\n *  Strophe library uses a runtime context object.  This object\n *  contains the information on how to do memory allocation and\n *  logging.  This allows the user to control how memory is allocated\n *  and what do to with log messages.\n *\n *  These issues do not affect programs in the common case, but many\n *  environments require special treatment.  Abstracting these into a runtime\n *  context object makes it easy to use Strophe on embedded platforms.\n *\n *  Objects in Strophe are reference counted to ease memory management issues,\n *  but the context objects are not.\n */\n\n/** @defgroup Init Initialization, shutdown, and versioning\n *  These functions initialize and shutdown the library, and also allow\n *  for API version checking.  Failure to properly call these functions may\n *  result in strange (and platform dependent) behavior.\n *\n *  Specifically, the socket library on Win32 platforms must be initialized\n *  before use (although this is not the case on POSIX systems).  The TLS\n *  subsystem must also seed the random number generator.\n */\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <stdarg.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"resolver.h\"\n#include \"util.h\"\n\n#ifndef va_copy\n#ifdef HAVE_VA_COPY\n#define va_copy(dest, src) va_copy(dest, src)\n#else\n#ifdef HAVE___VA_COPY\n#define va_copy(dest, src) __va_copy(dest, src)\n#else\n#ifndef VA_LIST_IS_ARRAY\n#define va_copy(dest, src) (dest) = (src)\n#else\n#include <string.h>\n#define va_copy(dest, src) \\\n    memcpy((char *)(dest), (char *)(src), sizeof(va_list))\n#endif\n#endif\n#endif\n#endif\n\n/** Initialize the Strophe library.\n *  This function initializes subcomponents of the Strophe library and must\n *  be called for Strophe to operate correctly.\n *\n *  @ingroup Init\n */\nvoid xmpp_initialize(void)\n{\n    sock_initialize();\n    resolver_initialize();\n    tls_initialize();\n}\n\n/** Shutdown the Strophe library.\n *\n *  @ingroup Init\n */\nvoid xmpp_shutdown(void)\n{\n    tls_shutdown();\n    resolver_shutdown();\n    sock_shutdown();\n}\n\n/* version information */\n\n#ifndef LIBXMPP_VERSION_MAJOR\n/** @def LIBXMPP_VERSION_MAJOR\n *  The major version number of Strophe.\n */\n#define LIBXMPP_VERSION_MAJOR (0)\n#endif\n#ifndef LIBXMPP_VERSION_MINOR\n/** @def LIBXMPP_VERSION_MINOR\n *  The minor version number of Strophe.\n */\n#define LIBXMPP_VERSION_MINOR (0)\n#endif\n\n#ifndef EVENT_LOOP_DEFAULT_TIMEOUT\n/** @def EVENT_LOOP_DEFAULT_TIMEOUT\n *  The default timeout in milliseconds for the event loop.\n *  This is set to 1 second.\n */\n#define EVENT_LOOP_DEFAULT_TIMEOUT 1000\n#endif\n\n/** Check that Strophe supports a specific API version.\n *\n *  @param major the major version number\n *  @param minor the minor version number\n *\n *  @return TRUE if the version is supported and FALSE if unsupported\n *\n *  @ingroup Init\n */\nint xmpp_version_check(int major, int minor)\n{\n    return (major == LIBXMPP_VERSION_MAJOR) && (minor >= LIBXMPP_VERSION_MINOR);\n}\n\n/* We define the global default allocator, logger, and context here. */\n\n/* Wrap stdlib routines malloc, free, and realloc for default memory\n * management.\n */\nstatic void *_malloc(size_t size, void *userdata)\n{\n    UNUSED(userdata);\n    return malloc(size);\n}\n\nstatic void _free(void *p, void *userdata)\n{\n    UNUSED(userdata);\n    free(p);\n}\n\nstatic void *_realloc(void *p, size_t size, void *userdata)\n{\n    UNUSED(userdata);\n    return realloc(p, size);\n}\n\n/* default memory function map */\nstatic xmpp_mem_t xmpp_default_mem = {\n    _malloc, /* use the thinly wrapped stdlib routines by default */\n    _free, _realloc, NULL};\n\n/* log levels and names */\nstatic const char *_xmpp_log_level_name[4] = {\"DEBUG\", \"INFO\", \"WARN\", \"ERROR\"};\nstatic const xmpp_log_level_t _xmpp_default_logger_levels[] = {\n    XMPP_LEVEL_DEBUG, XMPP_LEVEL_INFO, XMPP_LEVEL_WARN, XMPP_LEVEL_ERROR};\n\n/** Log a message.\n *  The default logger writes to stderr.\n *\n *  @param userdata the opaque data used by the default logger.  This contains\n *      the filter level in the default logger.\n *  @param level the level to log at\n *  @param area the area the log message is for\n *  @param msg the log message\n */\nstatic void xmpp_default_logger(void *userdata,\n                                xmpp_log_level_t level,\n                                const char *area,\n                                const char *msg)\n{\n    xmpp_log_level_t filter_level = *(xmpp_log_level_t *)userdata;\n    if (level >= filter_level)\n        fprintf(stderr, \"%s %s %s\\n\", area, _xmpp_log_level_name[level], msg);\n}\n\nstatic const xmpp_log_t _xmpp_default_loggers[] = {\n    {&xmpp_default_logger,\n     (void *)&_xmpp_default_logger_levels[XMPP_LEVEL_DEBUG]},\n    {&xmpp_default_logger,\n     (void *)&_xmpp_default_logger_levels[XMPP_LEVEL_INFO]},\n    {&xmpp_default_logger,\n     (void *)&_xmpp_default_logger_levels[XMPP_LEVEL_WARN]},\n    {&xmpp_default_logger,\n     (void *)&_xmpp_default_logger_levels[XMPP_LEVEL_ERROR]}};\n\n/** Get a default logger with filtering.\n *  The default logger provides a basic logging setup which writes log\n *  messages to stderr.  Only messages where level is greater than or\n *  equal to the filter level will be logged.\n *\n *  @param level the highest level the logger will log at\n *\n *  @return the log structure for the given level\n *\n *  @ingroup Context\n */\nxmpp_log_t *xmpp_get_default_logger(xmpp_log_level_t level)\n{\n    /* clamp to the known range */\n    if (level > XMPP_LEVEL_ERROR)\n        level = XMPP_LEVEL_ERROR;\n\n    return (xmpp_log_t *)&_xmpp_default_loggers[level];\n}\n\nstatic xmpp_log_t xmpp_default_log = {NULL, NULL};\n\n/* convenience functions for accessing the context */\n\n/** Allocate memory in a Strophe context.\n *  All Strophe functions will use this to allocate memory.\n *\n *  @param ctx a Strophe context object\n *  @param size the number of bytes to allocate\n *\n *  @return a pointer to the allocated memory or NULL on an error\n */\nvoid *strophe_alloc(const xmpp_ctx_t *ctx, size_t size)\n{\n    return ctx->mem->alloc(size, ctx->mem->userdata);\n}\n\n/** Free memory in a Strophe context.\n *  All Strophe functions will use this to free allocated memory.\n *\n *  @param ctx a Strophe context object\n *  @param p a pointer referencing memory to be freed\n */\nvoid strophe_free(const xmpp_ctx_t *ctx, void *p)\n{\n    ctx->mem->free(p, ctx->mem->userdata);\n}\n\n/** Trampoline to \\ref strophe_free\n *\n *  @param ctx \\ref strophe_free\n *  @param p \\ref strophe_free\n */\nvoid xmpp_free(const xmpp_ctx_t *ctx, void *p)\n{\n    strophe_free(ctx, p);\n}\n\n/** Reallocate memory in a Strophe context.\n *  All Strophe functions will use this to reallocate memory.\n *\n *  @param ctx a Strophe context object\n *  @param p a pointer to previously allocated memory\n *  @param size the new size in bytes to allocate\n *\n *  @return a pointer to the reallocated memory or NULL on an error\n */\nvoid *strophe_realloc(const xmpp_ctx_t *ctx, void *p, size_t size)\n{\n    return ctx->mem->realloc(p, size, ctx->mem->userdata);\n}\n\n/** Write a log message to the logger.\n *  Write a log message to the logger for the context for the specified\n *  level and area.  This function takes a printf-style format string and a\n *  variable argument list (in va_list) format.  This function is not meant\n *  to be called directly, but is used via strophe_error, strophe_warn,\n * strophe_info, and strophe_debug.\n *\n *  @param ctx a Strophe context object\n *  @param level the level at which to log\n *  @param area the area to log for\n *  @param fmt a printf-style format string for the message\n *  @param ap variable argument list supplied for the format string\n */\nstatic void _strophe_log(const xmpp_ctx_t *ctx,\n                         xmpp_log_level_t level,\n                         const char *area,\n                         const char *fmt,\n                         va_list ap)\n{\n    int oldret, ret;\n    char smbuf[1024];\n    char *buf;\n    va_list copy;\n\n    if (!ctx->log->handler)\n        return;\n\n    if (ctx->log->handler == xmpp_default_logger &&\n        level < *(xmpp_log_level_t *)ctx->log->userdata)\n        return;\n\n    va_copy(copy, ap);\n    ret = strophe_vsnprintf(smbuf, sizeof(smbuf), fmt, ap);\n    if (ret >= (int)sizeof(smbuf)) {\n        buf = (char *)strophe_alloc(ctx, ret + 1);\n        if (!buf) {\n            buf = NULL;\n            strophe_error(ctx, \"log\",\n                          \"Failed allocating memory for log message.\");\n            va_end(copy);\n            return;\n        }\n        oldret = ret;\n        ret = strophe_vsnprintf(buf, ret + 1, fmt, copy);\n        if (ret > oldret) {\n            strophe_error(ctx, \"log\", \"Unexpected error\");\n            strophe_free(ctx, buf);\n            va_end(copy);\n            return;\n        }\n    } else {\n        buf = smbuf;\n    }\n    va_end(copy);\n\n    ctx->log->handler(ctx->log->userdata, level, area, buf);\n\n    if (buf != smbuf)\n        strophe_free(ctx, buf);\n}\n\n/* Dummy trampoline, will be removed when deprecated.c is deleted */\nvoid strophe_log_internal(const xmpp_ctx_t *ctx,\n                          xmpp_log_level_t level,\n                          const char *area,\n                          const char *fmt,\n                          va_list ap)\n{\n    _strophe_log(ctx, level, area, fmt, ap);\n}\n\n/** Write to the log at the ERROR level.\n *  This is a convenience function for writing to the log at the\n *  ERROR level.  It takes a printf-style format string followed by a\n *  variable list of arguments for formatting.\n *\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n */\nvoid strophe_error(const xmpp_ctx_t *ctx,\n                   const char *area,\n                   const char *fmt,\n                   ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    _strophe_log(ctx, XMPP_LEVEL_ERROR, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Write to the log at the WARN level.\n *  This is a convenience function for writing to the log at the WARN level.\n *  It takes a printf-style format string followed by a variable list of\n *  arguments for formatting.\n *\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n */\nvoid strophe_warn(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    _strophe_log(ctx, XMPP_LEVEL_WARN, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Write to the log at the INFO level.\n *  This is a convenience function for writing to the log at the INFO level.\n *  It takes a printf-style format string followed by a variable list of\n *  arguments for formatting.\n *\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n */\nvoid strophe_info(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    _strophe_log(ctx, XMPP_LEVEL_INFO, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Write to the log at the DEBUG level.\n *  This is a convenience function for writing to the log at the DEBUG level.\n *  It takes a printf-style format string followed by a variable list of\n *  arguments for formatting.\n *\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n */\nvoid strophe_debug(const xmpp_ctx_t *ctx,\n                   const char *area,\n                   const char *fmt,\n                   ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    _strophe_log(ctx, XMPP_LEVEL_DEBUG, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Write to the log at the DEBUG level if verbosity is enabled.\n *  This is a convenience function for writing to the log at the DEBUG level.\n *  It takes a printf-style format string followed by a variable list of\n *  arguments for formatting.\n *\n *  @param level the verbosity level\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n */\nvoid strophe_debug_verbose(\n    int level, const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...)\n{\n    va_list ap;\n\n    if (ctx->verbosity < level)\n        return;\n\n    va_start(ap, fmt);\n    _strophe_log(ctx, XMPP_LEVEL_DEBUG, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Create and initialize a Strophe context object.\n *  If mem is NULL, a default allocation setup will be used which\n *  wraps malloc(), free(), and realloc() from the standard library.\n *  If log is NULL, a default logger will be used which does no\n *  logging.  Basic filtered logging to stderr can be done with the\n *  xmpp_get_default_logger() convenience function.\n *\n *  @param mem a pointer to an xmpp_mem_t structure or NULL\n *  @param log a pointer to an xmpp_log_t structure or NULL\n *\n *  @return the allocated Strophe context object or NULL on an error\n *\n *  @ingroup Context\n */\nxmpp_ctx_t *xmpp_ctx_new(const xmpp_mem_t *mem, const xmpp_log_t *log)\n{\n    xmpp_ctx_t *ctx = NULL;\n\n    if (mem == NULL)\n        ctx = xmpp_default_mem.alloc(sizeof(xmpp_ctx_t), NULL);\n    else\n        ctx = mem->alloc(sizeof(xmpp_ctx_t), mem->userdata);\n\n    if (ctx != NULL) {\n        memset(ctx, 0, sizeof(xmpp_ctx_t));\n\n        if (mem != NULL)\n            ctx->mem = mem;\n        else\n            ctx->mem = &xmpp_default_mem;\n\n        if (log == NULL)\n            ctx->log = &xmpp_default_log;\n        else\n            ctx->log = log;\n\n        ctx->loop_status = XMPP_LOOP_NOTSTARTED;\n        ctx->rand = xmpp_rand_new(ctx);\n        ctx->timeout = EVENT_LOOP_DEFAULT_TIMEOUT;\n        if (ctx->rand == NULL) {\n            strophe_free(ctx, ctx);\n            ctx = NULL;\n        }\n    }\n\n    return ctx;\n}\n\n/** Free a Strophe context object that is no longer in use.\n *\n *  @param ctx a Strophe context object\n *\n *  @ingroup Context\n */\nvoid xmpp_ctx_free(xmpp_ctx_t *ctx)\n{\n    /* mem and log are owned by their suppliers */\n    xmpp_rand_free(ctx, ctx->rand);\n    strophe_free(ctx, ctx); /* pull the hole in after us */\n}\n\n/** Set the verbosity level of a Strophe context.\n *\n *  @param ctx a Strophe context object\n *  @param level the verbosity level\n *\n *  @ingroup Context\n */\nvoid xmpp_ctx_set_verbosity(xmpp_ctx_t *ctx, int level)\n{\n    ctx->verbosity = level;\n}\n"
  },
  {
    "path": "src/deprecated.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* deprecated.c\n** strophe XMPP client library -- File with deprecated API functions.\n**\n** Copyright (C) 2022 Steffen Jaeckel\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  File with deprecated API functions.\n */\n\n/** @defgroup Deprecated All deprecated functions\n *  These functions will be removed in the next release.\n */\n\n#include \"common.h\"\n\n/** Allocate memory in a Strophe context.\n *  All Strophe functions will use this to allocate memory.\n *\n *  @param ctx a Strophe context object\n *  @param size the number of bytes to allocate\n *\n *  @return a pointer to the allocated memory or NULL on an error\n *\n *  @ingroup Deprecated\n */\nvoid *xmpp_alloc(const xmpp_ctx_t *ctx, size_t size)\n{\n    return strophe_alloc(ctx, size);\n}\n\n/** Reallocate memory in a Strophe context.\n *  All Strophe functions will use this to reallocate memory.\n *\n *  @param ctx a Strophe context object\n *  @param p a pointer to previously allocated memory\n *  @param size the new size in bytes to allocate\n *\n *  @return a pointer to the reallocated memory or NULL on an error\n *\n *  @ingroup Deprecated\n */\nvoid *xmpp_realloc(const xmpp_ctx_t *ctx, void *p, size_t size)\n{\n    return strophe_realloc(ctx, p, size);\n}\n\n/** implement our own strdup that uses the ctx allocator */\n/** Duplicate a string.\n *  This function replaces the standard strdup library call with a version\n *  that uses the Strophe context object's allocator.\n *\n *  @param ctx a Strophe context object\n *  @param s a string\n *\n *  @return a newly allocated string with the same data as s or NULL on error\n *\n *  @ingroup Deprecated\n */\nchar *xmpp_strdup(const xmpp_ctx_t *ctx, const char *s)\n{\n    return strophe_strdup(ctx, s);\n}\n\n/** Duplicate a string with a maximum length.\n *  This function replaces the standard strndup library call with a version\n *  that uses the Strophe context object's allocator.\n *\n *  @param ctx a Strophe context object\n *  @param s a string\n *  @param len the maximum length of the string to copy\n *\n *  @return a newly allocated string that contains at most `len` symbols\n *             of the original string or NULL on error\n *\n *  @ingroup Deprecated\n */\nchar *xmpp_strndup(const xmpp_ctx_t *ctx, const char *s, size_t len)\n{\n    return strophe_strndup(ctx, s, len);\n}\n\nvoid xmpp_log(const xmpp_ctx_t *ctx,\n              xmpp_log_level_t level,\n              const char *area,\n              const char *fmt,\n              va_list ap)\n{\n    strophe_log_internal(ctx, level, area, fmt, ap);\n}\n\n/** Write to the log at the ERROR level.\n *  This is a convenience function for writing to the log at the\n *  ERROR level.  It takes a printf-style format string followed by a\n *  variable list of arguments for formatting.\n *\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n *\n *  @ingroup Deprecated\n */\nvoid xmpp_error(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    strophe_log_internal(ctx, XMPP_LEVEL_ERROR, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Write to the log at the WARN level.\n *  This is a convenience function for writing to the log at the WARN level.\n *  It takes a printf-style format string followed by a variable list of\n *  arguments for formatting.\n *\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n *\n *  @ingroup Deprecated\n */\nvoid xmpp_warn(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    strophe_log_internal(ctx, XMPP_LEVEL_WARN, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Write to the log at the INFO level.\n *  This is a convenience function for writing to the log at the INFO level.\n *  It takes a printf-style format string followed by a variable list of\n *  arguments for formatting.\n *\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n *\n *  @ingroup Deprecated\n */\nvoid xmpp_info(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    strophe_log_internal(ctx, XMPP_LEVEL_INFO, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Write to the log at the DEBUG level.\n *  This is a convenience function for writing to the log at the DEBUG level.\n *  It takes a printf-style format string followed by a variable list of\n *  arguments for formatting.\n *\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n *\n *  @ingroup Deprecated\n */\nvoid xmpp_debug(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...)\n{\n    va_list ap;\n\n    va_start(ap, fmt);\n    strophe_log_internal(ctx, XMPP_LEVEL_DEBUG, area, fmt, ap);\n    va_end(ap);\n}\n\n/** Write to the log at the DEBUG level if verbosity is enabled.\n *  This is a convenience function for writing to the log at the DEBUG level.\n *  It takes a printf-style format string followed by a variable list of\n *  arguments for formatting.\n *\n *  @param level the verbosity level\n *  @param ctx a Strophe context object\n *  @param area the area to log for\n *  @param fmt a printf-style format string followed by a variable list of\n *      arguments to format\n *\n *  @ingroup Deprecated\n */\nvoid xmpp_debug_verbose(\n    int level, const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...)\n{\n    va_list ap;\n\n    if (ctx->verbosity < level)\n        return;\n\n    va_start(ap, fmt);\n    strophe_log_internal(ctx, XMPP_LEVEL_DEBUG, area, fmt, ap);\n    va_end(ap);\n}\n\n/** strtok_r(3) implementation.\n *  This function has appeared in POSIX.1-2001, but not in C standard.\n *  For example, visual studio older than 2005 doesn't provide strtok_r()\n *  nor strtok_s().\n *\n *  @ingroup Deprecated\n */\nchar *xmpp_strtok_r(char *s, const char *delim, char **saveptr)\n{\n    return strophe_strtok_r(s, delim, saveptr);\n}\n\nint xmpp_snprintf(char *str, size_t count, const char *fmt, ...)\n{\n    va_list ap;\n    int ret;\n\n    va_start(ap, fmt);\n    ret = strophe_vsnprintf(str, count, fmt, ap);\n    va_end(ap);\n    return ret;\n}\n\nint xmpp_vsnprintf(char *str, size_t count, const char *fmt, va_list arg)\n{\n    return strophe_vsnprintf(str, count, fmt, arg);\n}\n\n/** Set TCP keepalive parameters\n *  Turn on TCP keepalive and set timeout and interval. Zero timeout\n *  disables TCP keepalives. The parameters are applied immediately for\n *  a non disconnected object. Also, they are applied when the connection\n *  object connects successfully.\n *\n *  @param conn a Strophe connection object\n *  @param timeout TCP keepalive timeout in seconds\n *  @param interval TCP keepalive interval in seconds\n *\n *  @note this function is deprecated\n *  @see xmpp_conn_set_sockopt_callback()\n *\n *  @ingroup Deprecated\n */\nvoid xmpp_conn_set_keepalive(xmpp_conn_t *conn, int timeout, int interval)\n{\n    conn->ka_timeout = timeout;\n    conn->ka_interval = interval;\n    conn->ka_count = 0;\n    xmpp_conn_set_sockopt_callback(conn, xmpp_sockopt_cb_keepalive);\n}\n\n/** Disable TLS for this connection, called by users of the library.\n *  Occasionally a server will be misconfigured to send the starttls\n *  feature, but will not support the handshake.\n *\n *  @param conn a Strophe connection object\n *\n *  @note this function is deprecated\n *  @see xmpp_conn_set_flags()\n *\n *  @ingroup Deprecated\n */\nvoid xmpp_conn_disable_tls(xmpp_conn_t *conn)\n{\n    long flags = xmpp_conn_get_flags(conn);\n\n    flags |= XMPP_CONN_FLAG_DISABLE_TLS;\n    (void)xmpp_conn_set_flags(conn, flags);\n}\n"
  },
  {
    "path": "src/event.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* event.c\n** strophe XMPP client library -- event loop and management\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Event loop and management.\n */\n\n/** @defgroup EventLoop Event loop\n *  These functions manage the Strophe event loop.\n *\n *  Simple tools can use xmpp_run() and xmpp_stop() to manage the life\n *  cycle of the program.  A common idiom is to set up a few initial\n *  event handers, call xmpp_run(), and then respond and react to\n *  events as they come in.  At some point, one of the handlers will\n *  call xmpp_stop() to quit the event loop which leads to the program\n *  terminating.\n *\n *  More complex programs will have their own event loops, and should\n *  ensure that xmpp_run_once() is called regularly from there.  For\n *  example, a GUI program will already include an event loop to\n *  process UI events from users, and xmpp_run_once() would be called\n *  from an idle function.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#ifndef _WIN32\n#include <sys/select.h>\n#include <errno.h>\n#include <unistd.h>\n#define _sleep(x) usleep((x) * 1000)\n#else\n#include <winsock2.h>\n#ifndef ETIMEDOUT\n#define ETIMEDOUT WSAETIMEDOUT\n#endif\n#ifndef ECONNRESET\n#define ECONNRESET WSAECONNRESET\n#endif\n#ifndef ECONNABORTED\n#define ECONNABORTED WSAECONNABORTED\n#endif\n#define _sleep(x) Sleep(x)\n#endif\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"parser.h\"\n\n#ifndef STROPHE_MESSAGE_BUFFER_SIZE\n/** Max buffer size for receiving messages. */\n#define STROPHE_MESSAGE_BUFFER_SIZE 4096\n#endif\n\nstatic int _connect_next(xmpp_conn_t *conn)\n{\n    sock_close(conn->sock);\n    conn->sock = sock_connect(conn->xsock);\n    if (conn->sock == INVALID_SOCKET)\n        return -1;\n\n    conn->timeout_stamp = time_stamp();\n\n    return 0;\n}\n\n/** Run the event loop once.\n *  This function will run send any data that has been queued by\n *  xmpp_send and related functions and run through the Strophe even\n *  loop a single time, and will not wait more than timeout\n *  milliseconds for events.  This is provided to support integration\n *  with event loops outside the library, and if used, should be\n *  called regularly to achieve low latency event handling.\n *\n *  @param ctx a Strophe context object\n *  @param timeout time to wait for events in milliseconds\n *\n *  @ingroup EventLoop\n */\nvoid xmpp_run_once(xmpp_ctx_t *ctx, unsigned long timeout)\n{\n    xmpp_connlist_t *connitem;\n    xmpp_conn_t *conn;\n    struct conn_interface *intf;\n    fd_set rfds, wfds;\n    sock_t max = 0;\n    int ret;\n    struct timeval tv;\n    xmpp_send_queue_t *sq, *tsq;\n    int towrite;\n    char buf[STROPHE_MESSAGE_BUFFER_SIZE];\n    uint64_t next;\n    uint64_t usec;\n    int tls_read_bytes = 0;\n\n    if (ctx->loop_status == XMPP_LOOP_QUIT)\n        return;\n\n    /* send queued data */\n    connitem = ctx->connlist;\n    while (connitem) {\n        conn = connitem->conn;\n        if (conn->state != XMPP_STATE_CONNECTED) {\n            connitem = connitem->next;\n            continue;\n        }\n        intf = &conn->intf;\n\n        /* if we're running tls, there may be some remaining data waiting to\n         * be sent, so push that out */\n        if (conn->tls) {\n            ret = tls_clear_pending_write(intf);\n\n            if (ret < 0 && !tls_is_recoverable(intf, tls_error(intf))) {\n                /* an error occurred */\n                strophe_debug(\n                    ctx, \"xmpp\",\n                    \"Send error of pending data occurred, disconnecting.\");\n                conn->error = ECONNABORTED;\n                conn_disconnect(conn);\n                goto next_item;\n            }\n        }\n\n        /* write all data from the send queue to the socket */\n        sq = conn->send_queue_head;\n        while (sq) {\n            towrite = sq->len - sq->written;\n\n            ret = conn_interface_write(intf, &sq->data[sq->written], towrite);\n            if (ret > 0 && ret < towrite)\n                sq->written += ret; /* not all data could be sent now */\n            sq->wip = 1;\n            if (ret != towrite)\n                break; /* partial write or an error */\n\n            /* all data for this queue item written, delete and move on */\n            strophe_debug(conn->ctx, \"conn\", \"SENT: %s\", sq->data);\n            strophe_debug_verbose(1, ctx, \"xmpp\", \"Q_SENT: %p\", sq);\n            tsq = sq;\n            sq = sq->next;\n            conn->send_queue_len--;\n            if (tsq->owner & XMPP_QUEUE_USER)\n                conn->send_queue_user_len--;\n            if (!(tsq->owner & XMPP_QUEUE_SM) && conn->sm_state->sm_enabled) {\n                tsq->sm_h = conn->sm_state->sm_sent_nr;\n                conn->sm_state->sm_sent_nr++;\n                strophe_debug_verbose(1, ctx, \"xmpp\", \"SM_Q_MOVE: %p, h=%lu\",\n                                      tsq, tsq->sm_h);\n                add_queue_back(&conn->sm_state->sm_queue, tsq);\n                tsq = NULL;\n            }\n            if (tsq) {\n                strophe_debug_verbose(2, ctx, \"xmpp\", \"Q_FREE: %p\", tsq);\n                strophe_debug_verbose(3, ctx, \"conn\", \"Q_CONTENT: %s\",\n                                      tsq->data);\n                strophe_free(ctx, tsq->data);\n                strophe_free(ctx, tsq);\n            }\n\n            /* pop the top item */\n            conn->send_queue_head = sq;\n            /* if we've sent everything update the tail */\n            if (!sq)\n                conn->send_queue_tail = NULL;\n            trigger_sm_callback(conn);\n        }\n        intf->flush(intf);\n\n        /* tear down connection on error */\n        if (conn->error) {\n            /* FIXME: need to tear down send queues and random other things\n             * maybe this should be abstracted */\n            strophe_debug(ctx, \"xmpp\", \"Send error occurred, disconnecting.\");\n            conn->error = ECONNABORTED;\n            conn_disconnect(conn);\n        }\nnext_item:\n        connitem = connitem->next;\n    }\n\n    /* reset parsers if needed */\n    for (connitem = ctx->connlist; connitem; connitem = connitem->next) {\n        if (connitem->conn->reset_parser)\n            conn_parser_reset(connitem->conn);\n    }\n\n    /* fire any ready timed handlers, then make sure we don't wait past\n       the time when timed handlers need to be called */\n    next = handler_fire_timed(ctx);\n\n    usec = ((next < timeout) ? next : timeout) * 1000;\n    tv.tv_sec = (long)(usec / 1000000);\n    tv.tv_usec = (long)(usec % 1000000);\n\n    FD_ZERO(&rfds);\n    FD_ZERO(&wfds);\n\n    /* find events to watch */\n    connitem = ctx->connlist;\n    while (connitem) {\n        conn = connitem->conn;\n        intf = &conn->intf;\n\n        switch (conn->state) {\n        case XMPP_STATE_CONNECTING:\n            /* connect has been called and we're waiting for it to complete */\n            /* connection will give us write or error events */\n\n            /* make sure the timeout hasn't expired */\n            if (time_elapsed(conn->timeout_stamp, time_stamp()) <=\n                conn->connect_timeout)\n                FD_SET(conn->sock, &wfds);\n            else {\n                strophe_info(ctx, \"xmpp\", \"Connection attempt timed out.\");\n                ret = _connect_next(conn);\n                if (ret != 0) {\n                    conn->error = ETIMEDOUT;\n                    conn_disconnect(conn);\n                } else {\n                    FD_SET(conn->sock, &wfds);\n                }\n            }\n            break;\n        case XMPP_STATE_CONNECTED:\n            FD_SET(conn->sock, &rfds);\n            if (conn->send_queue_len > 0)\n                FD_SET(conn->sock, &wfds);\n            break;\n        case XMPP_STATE_DISCONNECTED:\n            /* do nothing */\n        default:\n            break;\n        }\n\n        /* Check if there is something in the SSL buffer. */\n        if (conn->tls)\n            tls_read_bytes += tls_pending(intf);\n\n        if (conn->state != XMPP_STATE_DISCONNECTED && conn->sock > max)\n            max = conn->sock;\n\n        connitem = connitem->next;\n    }\n\n    /* check for events */\n    if (max > 0)\n        ret = select(max + 1, &rfds, &wfds, NULL, &tv);\n    else {\n        if (timeout > 0)\n            _sleep(timeout);\n        return;\n    }\n\n    /* select errored */\n    if (ret < 0) {\n        if (!sock_is_recoverable(NULL, sock_error(NULL)))\n            strophe_error(ctx, \"xmpp\", \"event watcher internal error %d\",\n                          sock_error(NULL));\n        return;\n    }\n\n    /* no events happened */\n    if (ret == 0 && tls_read_bytes == 0)\n        return;\n\n    /* process events */\n    connitem = ctx->connlist;\n    while (connitem) {\n        conn = connitem->conn;\n        intf = &conn->intf;\n\n        switch (conn->state) {\n        case XMPP_STATE_CONNECTING:\n            if (FD_ISSET(conn->sock, &wfds)) {\n                /* connection complete */\n\n                /* check for error */\n                ret = sock_connect_error(conn->sock);\n                if (ret != 0) {\n                    /* connection failed */\n                    strophe_debug(ctx, \"xmpp\", \"connection failed, error %d\",\n                                  ret);\n                    ret = _connect_next(conn);\n                    if (ret != 0) {\n                        conn->error = ret;\n                        conn_disconnect(conn);\n                    }\n                    break;\n                }\n\n                conn->state = XMPP_STATE_CONNECTED;\n                strophe_debug(ctx, \"xmpp\", \"connection successful\");\n                conn_established(conn);\n            }\n\n            break;\n        case XMPP_STATE_CONNECTED:\n            if (FD_ISSET(conn->sock, &rfds) || intf->pending(intf)) {\n\n                ret = intf->read(intf, buf, STROPHE_MESSAGE_BUFFER_SIZE);\n\n                if (ret > 0) {\n                    ret = parser_feed(conn->parser, buf, ret);\n                    if (!ret) {\n                        strophe_debug(ctx, \"xmpp\", \"parse error [%s]\", buf);\n                        xmpp_send_error(conn, XMPP_SE_INVALID_XML,\n                                        \"parse error\");\n                    }\n                } else {\n                    int err = intf->get_error(intf);\n                    if (!intf->error_is_recoverable(intf, err)) {\n                        strophe_debug(ctx, \"xmpp\", \"Unrecoverable error: %d.\",\n                                      err);\n                        conn->error = err;\n                        conn_disconnect(conn);\n                    } else if (!conn->tls) {\n                        /* return of 0 means socket closed by server */\n                        strophe_debug(ctx, \"xmpp\",\n                                      \"Socket closed by remote host.\");\n                        conn->error = ECONNRESET;\n                        conn_disconnect(conn);\n                    }\n                }\n            }\n\n            break;\n        case XMPP_STATE_DISCONNECTED:\n            /* do nothing */\n        default:\n            break;\n        }\n\n        connitem = connitem->next;\n    }\n\n    /* fire any ready handlers */\n    handler_fire_timed(ctx);\n}\n\n/** Start the event loop.\n *  This function continuously calls xmpp_run_once and does not return\n *  until xmpp_stop has been called.\n *\n *  @param ctx a Strophe context object\n *\n *  @ingroup EventLoop\n */\nvoid xmpp_run(xmpp_ctx_t *ctx)\n{\n    if (ctx->loop_status != XMPP_LOOP_NOTSTARTED)\n        return;\n\n    ctx->loop_status = XMPP_LOOP_RUNNING;\n    while (ctx->loop_status == XMPP_LOOP_RUNNING) {\n        xmpp_run_once(ctx, ctx->timeout);\n    }\n\n    /* make it possible to start event loop again */\n    ctx->loop_status = XMPP_LOOP_NOTSTARTED;\n\n    strophe_debug(ctx, \"event\", \"Event loop completed.\");\n}\n\n/** Stop the event loop.\n *  This will stop the event loop after the current iteration and cause\n *  xmpp_run to exit.\n *\n *  @param ctx a Strophe context object\n *\n *  @ingroup EventLoop\n */\nvoid xmpp_stop(xmpp_ctx_t *ctx)\n{\n    strophe_debug(ctx, \"event\", \"Stopping event loop.\");\n\n    if (ctx->loop_status == XMPP_LOOP_RUNNING)\n        ctx->loop_status = XMPP_LOOP_QUIT;\n}\n\n/** Set the timeout to use when calling xmpp_run().\n *\n *  @param ctx a Strophe context object\n *  @param timeout the time to wait for events in milliseconds\n *\n *  @ingroup EventLoop\n */\nvoid xmpp_ctx_set_timeout(xmpp_ctx_t *ctx, unsigned long timeout)\n{\n    ctx->timeout = timeout;\n}\n"
  },
  {
    "path": "src/handler.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* handler.c\n** strophe XMPP client library -- event handler management\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Event handler management.\n */\n\n/** @defgroup Handlers Stanza and timed event handlers\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"ostypes.h\"\n\n/* Remove item from the list pointed by head, but don't free it.\n * There can be a situation when user's handler deletes another handler which\n * is the previous in the list. handler_fire_stanza() and handler_fire_timed()\n * must handle this situation correctly. Current function helps to avoid\n * list corruption in described scenario.\n *\n * TODO Convert handler lists to double-linked lists. Current implementation\n * works for O(n).\n */\nstatic void _handler_item_remove(xmpp_handlist_t **head, xmpp_handlist_t *item)\n{\n    while (*head) {\n        if (*head == item) {\n            *head = item->next;\n            break;\n        }\n        head = &(*head)->next;\n    }\n}\n\nstatic void _free_handlist_item(xmpp_ctx_t *ctx, xmpp_handlist_t *item)\n{\n    if (item->u.ns)\n        strophe_free(ctx, item->u.ns);\n    if (item->u.name)\n        strophe_free(ctx, item->u.name);\n    if (item->u.type)\n        strophe_free(ctx, item->u.type);\n    strophe_free(ctx, item);\n}\n\n/** Fire off all stanza handlers that match.\n *  This function is called internally by the event loop whenever stanzas\n *  are received from the XMPP server.\n *\n *  @param conn a Strophe connection object\n *  @param stanza a Strophe stanza object\n */\nvoid handler_fire_stanza(xmpp_conn_t *conn, xmpp_stanza_t *stanza)\n{\n    xmpp_handlist_t *item, *next, *head, *head_old;\n    const char *id, *ns, *name, *type;\n    int ret;\n\n    /* call id handlers */\n    id = xmpp_stanza_get_id(stanza);\n    if (id) {\n        head = (xmpp_handlist_t *)hash_get(conn->id_handlers, id);\n        /* enable all added handlers */\n        for (item = head; item; item = item->next)\n            item->enabled = 1;\n\n        item = head;\n        while (item) {\n            /* don't fire user handlers until stream negotiation has completed\n               and skip newly added handlers */\n            if ((item->user_handler && !conn->stream_negotiation_completed) ||\n                !item->enabled) {\n                item = item->next;\n                continue;\n            }\n\n            ret = ((xmpp_handler)(item->handler))(conn, stanza, item->userdata);\n            next = item->next;\n            if (!ret) {\n                /* handler is one-shot, so delete it */\n                head_old = head;\n                _handler_item_remove(&head, item);\n                if (head != head_old) {\n                    /* replace old value */\n                    hash_add(conn->id_handlers, id, head);\n                }\n                strophe_free(conn->ctx, item->u.id);\n                strophe_free(conn->ctx, item);\n            }\n            item = next;\n        }\n    }\n\n    /* call handlers */\n    ns = xmpp_stanza_get_ns(stanza);\n    name = xmpp_stanza_get_name(stanza);\n    type = xmpp_stanza_get_type(stanza);\n\n    /* enable all added handlers */\n    for (item = conn->handlers; item; item = item->next)\n        item->enabled = 1;\n\n    item = conn->handlers;\n    while (item) {\n        /* don't fire user handlers until stream negotiation has completed and\n           skip newly added handlers */\n        if ((item->user_handler && !conn->stream_negotiation_completed) ||\n            !item->enabled) {\n            item = item->next;\n            continue;\n        }\n\n        next = item->next;\n        if ((!item->u.ns || (ns && strcmp(ns, item->u.ns) == 0) ||\n             xmpp_stanza_get_child_by_ns(stanza, item->u.ns)) &&\n            (!item->u.name || (name && strcmp(name, item->u.name) == 0)) &&\n            (!item->u.type || (type && strcmp(type, item->u.type) == 0))) {\n\n            ret = ((xmpp_handler)(item->handler))(conn, stanza, item->userdata);\n            /* list may be changed during execution of a handler */\n            next = item->next;\n            if (!ret) {\n                /* handler is one-shot, so delete it */\n                _handler_item_remove(&conn->handlers, item);\n                _free_handlist_item(conn->ctx, item);\n            }\n        }\n        item = next;\n    }\n}\n\n/** Fire off all timed handlers that are ready.\n *  This function is called internally by the event loop.\n *\n *  @param ctx a Strophe context object\n *\n *  @return the time in milliseconds until the next handler will be ready\n */\nuint64_t handler_fire_timed(xmpp_ctx_t *ctx)\n{\n    xmpp_connlist_t *connitem;\n    xmpp_handlist_t *item, *next;\n    xmpp_conn_t *conn;\n    uint64_t elapsed, min;\n    uint64_t timestamp;\n    int ret;\n\n    min = (uint64_t)(-1);\n\n    connitem = ctx->connlist;\n    while (connitem) {\n        conn = connitem->conn;\n        if (conn->state != XMPP_STATE_CONNECTED) {\n            connitem = connitem->next;\n            continue;\n        }\n\n        /* enable all handlers that were added */\n        for (item = conn->timed_handlers; item; item = item->next)\n            item->enabled = 1;\n\n        item = conn->timed_handlers;\n        while (item) {\n            /* don't fire user handlers until stream negotiation has completed\n               and skip newly added handlers */\n            if ((item->user_handler && !conn->stream_negotiation_completed) ||\n                !item->enabled) {\n                item = item->next;\n                continue;\n            }\n\n            next = item->next;\n            timestamp = time_stamp();\n            elapsed = time_elapsed(item->u.last_stamp, timestamp);\n            if (elapsed >= item->u.period) {\n                /* fire! */\n                item->u.last_stamp = timestamp;\n                ret = ((xmpp_timed_handler)item->handler)(conn, item->userdata);\n                /* list may be changed during execution of a handler */\n                next = item->next;\n                if (!ret) {\n                    /* delete handler if it returned false */\n                    _handler_item_remove(&conn->timed_handlers, item);\n                    strophe_free(ctx, item);\n                }\n            } else if (min > (item->u.period - elapsed))\n                min = item->u.period - elapsed;\n\n            item = next;\n        }\n\n        connitem = connitem->next;\n    }\n\n    /*\n     * Check timed handlers in context. These handlers fire periodically\n     * regardless of connections state.\n     * TODO Reduce copy-paste.\n     */\n    item = ctx->timed_handlers;\n    while (item) {\n        next = item->next;\n        timestamp = time_stamp();\n        elapsed = time_elapsed(item->u.last_stamp, timestamp);\n        if (elapsed >= item->u.period) {\n            /* fire! */\n            item->u.last_stamp = timestamp;\n            ret =\n                ((xmpp_global_timed_handler)item->handler)(ctx, item->userdata);\n            /* list may be changed during execution of a handler */\n            next = item->next;\n            if (!ret) {\n                /* delete handler if it returned false */\n                _handler_item_remove(&ctx->timed_handlers, item);\n                strophe_free(ctx, item);\n            }\n        } else if (min > (item->u.period - elapsed))\n            min = item->u.period - elapsed;\n\n        item = next;\n    }\n\n    return min;\n}\n\n/** Reset all timed handlers.\n *  This function is called internally when a connection is successful.\n *\n *  @param conn a Strophe connection object\n *  @param user_only whether to reset all handlers or only user ones\n */\nvoid handler_reset_timed(xmpp_conn_t *conn, int user_only)\n{\n    xmpp_handlist_t *handitem;\n\n    handitem = conn->timed_handlers;\n    while (handitem) {\n        if ((user_only && handitem->user_handler) || !user_only)\n            handitem->u.last_stamp = time_stamp();\n\n        handitem = handitem->next;\n    }\n}\n\nstatic void _timed_handler_add(xmpp_ctx_t *ctx,\n                               xmpp_handlist_t **handlers_list,\n                               xmpp_void_handler handler,\n                               unsigned long period,\n                               void *userdata,\n                               int user_handler)\n{\n    xmpp_handlist_t *item;\n\n    /* check if handler is already in the list */\n    for (item = *handlers_list; item; item = item->next) {\n        if (item->handler == handler && item->userdata == userdata) {\n            strophe_warn(ctx, \"xmpp\", \"Timed handler already exists.\");\n            break;\n        }\n    }\n    if (item)\n        return;\n\n    /* build new item */\n    item = strophe_alloc(ctx, sizeof(xmpp_handlist_t));\n    if (!item)\n        return;\n\n    item->user_handler = user_handler;\n    item->handler = handler;\n    item->userdata = userdata;\n    item->enabled = 0;\n\n    item->u.period = period;\n    item->u.last_stamp = time_stamp();\n\n    /* append item to list */\n    item->next = *handlers_list;\n    *handlers_list = item;\n}\n\nstatic void _timed_handler_delete(xmpp_ctx_t *ctx,\n                                  xmpp_handlist_t **handlers_list,\n                                  xmpp_void_handler handler)\n{\n    xmpp_handlist_t *item;\n\n    while (*handlers_list) {\n        item = *handlers_list;\n        if (item->handler == handler) {\n            *handlers_list = item->next;\n            strophe_free(ctx, item);\n        } else {\n            handlers_list = &item->next;\n        }\n    }\n}\n\n/** Delete a timed handler.\n *\n *  @param conn a Strophe connection object\n *  @param handler function pointer to the handler\n *\n *  @ingroup Handlers\n */\nvoid xmpp_timed_handler_delete(xmpp_conn_t *conn, xmpp_timed_handler handler)\n{\n    _timed_handler_delete(conn->ctx, &conn->timed_handlers, handler);\n}\n\nstatic void _id_handler_add(xmpp_conn_t *conn,\n                            xmpp_handler handler,\n                            const char *id,\n                            void *userdata,\n                            int user_handler)\n{\n    xmpp_handlist_t *item, *tail;\n\n    /* check if handler is already in the list */\n    item = (xmpp_handlist_t *)hash_get(conn->id_handlers, id);\n    while (item) {\n        if (item->handler == handler && item->userdata == userdata) {\n            strophe_warn(conn->ctx, \"xmpp\", \"Id handler already exists.\");\n            break;\n        }\n        item = item->next;\n    }\n    if (item)\n        return;\n\n    /* build new item */\n    item = strophe_alloc(conn->ctx, sizeof(xmpp_handlist_t));\n    if (!item)\n        return;\n\n    item->user_handler = user_handler;\n    item->handler = handler;\n    item->userdata = userdata;\n    item->enabled = 0;\n    item->next = NULL;\n\n    item->u.id = strophe_strdup(conn->ctx, id);\n    if (!item->u.id) {\n        strophe_free(conn->ctx, item);\n        return;\n    }\n\n    /* put on list in hash table */\n    tail = (xmpp_handlist_t *)hash_get(conn->id_handlers, id);\n    if (!tail)\n        hash_add(conn->id_handlers, id, item);\n    else {\n        while (tail->next)\n            tail = tail->next;\n        tail->next = item;\n    }\n}\n\n/** Delete an id based stanza handler.\n *\n *  @param conn a Strophe connection object\n *  @param handler a function pointer to a stanza handler\n *  @param id a string containing the id the handler is for\n *\n *  @ingroup Handlers\n */\nvoid xmpp_id_handler_delete(xmpp_conn_t *conn,\n                            xmpp_handler handler,\n                            const char *id)\n{\n    xmpp_handlist_t *item, *prev, *next;\n\n    prev = NULL;\n    item = (xmpp_handlist_t *)hash_get(conn->id_handlers, id);\n    if (!item)\n        return;\n\n    while (item) {\n        next = item->next;\n\n        if (item->handler == handler) {\n            if (prev)\n                prev->next = next;\n            else {\n                hash_drop(conn->id_handlers, id);\n                hash_add(conn->id_handlers, id, next);\n            }\n\n            strophe_free(conn->ctx, item->u.id);\n            strophe_free(conn->ctx, item);\n            item = next;\n        } else {\n            prev = item;\n            item = next;\n        }\n    }\n}\n\nstatic int _dup_string(xmpp_ctx_t *ctx, const char *src, char **dest)\n{\n    if (src) {\n        *dest = strophe_strdup(ctx, src);\n        if (!(*dest))\n            return 1;\n    }\n    return 0;\n}\n\n/* add a stanza handler */\nstatic void _handler_add(xmpp_conn_t *conn,\n                         xmpp_handler handler,\n                         const char *ns,\n                         const char *name,\n                         const char *type,\n                         void *userdata,\n                         int user_handler)\n{\n    xmpp_handlist_t *item, *tail;\n\n    /* check if handler already in list */\n    for (item = conn->handlers; item; item = item->next) {\n        /* same handler function can process different stanzas and\n           distinguish them according to userdata. */\n        if (item->handler == handler && item->userdata == userdata) {\n            strophe_warn(conn->ctx, \"xmpp\", \"Stanza handler already exists.\");\n            break;\n        }\n    }\n    if (item)\n        return;\n\n    /* build new item */\n    item = (xmpp_handlist_t *)strophe_alloc(conn->ctx, sizeof(xmpp_handlist_t));\n    if (!item)\n        return;\n\n    memset(item, 0, sizeof(*item));\n    item->user_handler = user_handler;\n    item->handler = handler;\n    item->userdata = userdata;\n\n    if (_dup_string(conn->ctx, ns, &item->u.ns))\n        goto error_out;\n    if (_dup_string(conn->ctx, name, &item->u.name))\n        goto error_out;\n    if (_dup_string(conn->ctx, type, &item->u.type))\n        goto error_out;\n\n    /* append to list */\n    if (!conn->handlers)\n        conn->handlers = item;\n    else {\n        tail = conn->handlers;\n        while (tail->next)\n            tail = tail->next;\n        tail->next = item;\n    }\n\n    return;\n\nerror_out:\n    _free_handlist_item(conn->ctx, item);\n}\n\n/** Delete a stanza handler.\n *\n *  @param conn a Strophe connection object\n *  @param handler a function pointer to a stanza handler\n *\n *  @ingroup Handlers\n */\nvoid xmpp_handler_delete(xmpp_conn_t *conn, xmpp_handler handler)\n{\n    xmpp_handlist_t *prev, *item;\n\n    if (!conn->handlers)\n        return;\n\n    prev = NULL;\n    item = conn->handlers;\n    while (item) {\n        if (item->handler == handler) {\n            if (prev)\n                prev->next = item->next;\n            else\n                conn->handlers = item->next;\n\n            _free_handlist_item(conn->ctx, item);\n            item = prev ? prev->next : conn->handlers;\n        } else {\n            prev = item;\n            item = item->next;\n        }\n    }\n}\n\n/** Add a timed handler.\n *  The handler will fire for the first time once the period has elapsed,\n *  and continue firing regularly after that.  Strophe will try its best\n *  to fire handlers as close to the period times as it can, but accuracy\n *  will vary depending on the resolution of the event loop.\n *\n *  If the handler function returns true, it will be kept, and if it\n *  returns false, it will be deleted from the list of handlers.\n *\n *  @param conn a Strophe connection object\n *  @param handler a function pointer to a timed handler\n *  @param period the time in milliseconds between firings\n *  @param userdata an opaque data pointer that will be passed to the handler\n *\n *  @ingroup Handlers\n */\nvoid xmpp_timed_handler_add(xmpp_conn_t *conn,\n                            xmpp_timed_handler handler,\n                            unsigned long period,\n                            void *userdata)\n{\n    _timed_handler_add(conn->ctx, &conn->timed_handlers, handler, period,\n                       userdata, 1);\n}\n\n/** Add a timed system handler.\n *  This function is used to add internal timed handlers and should not be\n *  used outside of the library.\n *\n *  @param conn a Strophe connection object\n *  @param handler a function pointer to a timed handler\n *  @param period the time in milliseconds between firings\n *  @param userdata an opaque data pointer that will be passed to the handler\n */\nvoid handler_add_timed(xmpp_conn_t *conn,\n                       xmpp_timed_handler handler,\n                       unsigned long period,\n                       void *userdata)\n{\n    _timed_handler_add(conn->ctx, &conn->timed_handlers, handler, period,\n                       userdata, 0);\n}\n\n/** Add an id based stanza handler.\n\n *  This function adds a stanza handler for an &lt;iq/&gt; stanza of\n *  type 'result' or 'error' with a specific id attribute.  This can\n *  be used to handle responses to specific &lt;iq/&gt;s.\n *\n *  If the handler function returns true, it will be kept, and if it\n *  returns false, it will be deleted from the list of handlers.\n *\n *  @param conn a Strophe connection object\n *  @param handler a function pointer to a stanza handler\n *  @param id a string with the id\n *  @param userdata an opaque data pointer that will be passed to the handler\n *\n *  @ingroup Handlers\n */\nvoid xmpp_id_handler_add(xmpp_conn_t *conn,\n                         xmpp_handler handler,\n                         const char *id,\n                         void *userdata)\n{\n    _id_handler_add(conn, handler, id, userdata, 1);\n}\n\n/** Add an id based system stanza handler.\n *  This function is used to add internal id based stanza handlers and should\n *  not be used outside of the library.\n *\n *  @param conn a Strophe connection object\n *  @param handler a function pointer to a stanza handler\n *  @param id a string with the id\n *  @param userdata an opaque data pointer that will be passed to the handler\n */\nvoid handler_add_id(xmpp_conn_t *conn,\n                    xmpp_handler handler,\n                    const char *id,\n                    void *userdata)\n{\n    _id_handler_add(conn, handler, id, userdata, 0);\n}\n\n/** Add a stanza handler.\n *  This function is used to add a stanza handler to a connection.\n *  The handler will be called when the any of the filters match.  The\n *  name filter matches to the top level stanza name.  The type filter\n *  matches the 'type' attribute of the top level stanza.  The ns\n *  filter matches the namespace ('xmlns' attribute) of either the top\n *  level stanza or any of it's immediate children (this allows you do\n *  handle specific &lt;iq/&gt; stanzas based on the &lt;query/&gt;\n *  child namespace.\n *\n *  If the handler function returns true, it will be kept, and if it\n *  returns false, it will be deleted from the list of handlers.\n *\n *  @param conn a Strophe connection object\n *  @param handler a function pointer to a stanza handler\n *  @param ns a string with the namespace to match\n *  @param name a string with the stanza name to match\n *  @param type a string with the 'type' attribute to match\n *  @param userdata an opaque data pointer that will be passed to the handler\n *\n *  @ingroup Handlers\n */\nvoid xmpp_handler_add(xmpp_conn_t *conn,\n                      xmpp_handler handler,\n                      const char *ns,\n                      const char *name,\n                      const char *type,\n                      void *userdata)\n{\n    _handler_add(conn, handler, ns, name, type, userdata, 1);\n}\n\n/** Add a system stanza handler.\n *  This function is used to add internal stanza handlers and should\n *  not be used outside of the library.\n *\n *  @param conn a Strophe connection object\n *  @param handler a function pointer to a stanza handler\n *  @param ns a string with the namespace to match\n *  @param name a string with the stanza name to match\n *  @param type a string with the 'type' attribute value to match\n *  @param userdata an opaque data pointer that will be passed to the handler\n */\nvoid handler_add(xmpp_conn_t *conn,\n                 xmpp_handler handler,\n                 const char *ns,\n                 const char *name,\n                 const char *type,\n                 void *userdata)\n{\n    _handler_add(conn, handler, ns, name, type, userdata, 0);\n}\n\n/** Delete all system handlers.\n *  This function is used to reset conn object before re-connecting.\n *\n *  @param conn a Strophe connection object\n */\nvoid handler_system_delete_all(xmpp_conn_t *conn)\n{\n    xmpp_handlist_t *item, *next, *head, *head_old;\n    hash_iterator_t *iter;\n    const char *key, *key2;\n\n    /* TODO unify all kinds of handlers and avoid copy-paste below */\n\n    item = conn->handlers;\n    while (item) {\n        if (!item->user_handler) {\n            next = item->next;\n            _handler_item_remove(&conn->handlers, item);\n            _free_handlist_item(conn->ctx, item);\n            item = next;\n        } else\n            item = item->next;\n    }\n\n    item = conn->timed_handlers;\n    while (item) {\n        if (!item->user_handler) {\n            next = item->next;\n            _handler_item_remove(&conn->timed_handlers, item);\n            strophe_free(conn->ctx, item);\n            item = next;\n        } else\n            item = item->next;\n    }\n\n    iter = hash_iter_new(conn->id_handlers);\n    key = iter == NULL ? NULL : hash_iter_next(iter);\n    while (key != NULL) {\n        head = head_old = (xmpp_handlist_t *)hash_get(conn->id_handlers, key);\n        item = head;\n        while (item) {\n            if (!item->user_handler) {\n                next = item->next;\n                _handler_item_remove(&head, item);\n                strophe_free(conn->ctx, item->u.id);\n                strophe_free(conn->ctx, item);\n                item = next;\n            } else\n                item = item->next;\n        }\n        /* Hash table implementation is not perfect, so we need to find next\n           key before dropping current one. Otherwise, we will get access to\n           freed memory. */\n        key2 = hash_iter_next(iter);\n        if (head != head_old) {\n            /* hash_add() replaces value if the key exists */\n            if (head != NULL)\n                hash_add(conn->id_handlers, key, head);\n            else\n                hash_drop(conn->id_handlers, key);\n        }\n        key = key2;\n    }\n    if (iter)\n        hash_iter_release(iter);\n}\n\n/** Add a global timed handler.\n *  The handler will fire for the first time once the period has elapsed,\n *  and continue firing regularly after that.  Strophe will try its best\n *  to fire handlers as close to the period times as it can, but accuracy\n *  will vary depending on the resolution of the event loop.\n *\n *  The main difference between global and ordinary handlers:\n *  - Ordinary handler is related to a connection, fires only when the\n *    connection is in connected state and is removed once the connection is\n *    destroyed.\n *  - Global handler fires regardless of connections state and is related to\n *    a Strophe context.\n *\n *  The handler is executed in context of the respective event loop.\n *\n *  If the handler function returns true, it will be kept, and if it\n *  returns false, it will be deleted from the list of handlers.\n *\n *  Notice, the same handler pointer may be added multiple times with different\n *  userdata pointers. However, xmpp_global_timed_handler_delete() deletes\n *  all occurrences.\n *\n *  @param ctx a Strophe context object\n *  @param handler a function pointer to a timed handler\n *  @param period the time in milliseconds between firings\n *  @param userdata an opaque data pointer that will be passed to the handler\n *\n *  @ingroup Handlers\n */\nvoid xmpp_global_timed_handler_add(xmpp_ctx_t *ctx,\n                                   xmpp_global_timed_handler handler,\n                                   unsigned long period,\n                                   void *userdata)\n{\n    _timed_handler_add(ctx, &ctx->timed_handlers, handler, period, userdata, 1);\n}\n\n/** Delete a global timed handler.\n *\n *  @param ctx a Strophe context object\n *  @param handler function pointer to the handler\n *\n *  @ingroup Handlers\n */\nvoid xmpp_global_timed_handler_delete(xmpp_ctx_t *ctx,\n                                      xmpp_global_timed_handler handler)\n{\n    _timed_handler_delete(ctx, &ctx->timed_handlers, handler);\n}\n"
  },
  {
    "path": "src/hash.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* hash.c\n** strophe XMPP client library -- hash table implementation\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Hash tables.\n */\n\n#include <stdlib.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"hash.h\"\n\n/* private types */\ntypedef struct _hashentry_t hashentry_t;\n\nstruct _hashentry_t {\n    hashentry_t *next;\n    char *key;\n    void *value;\n};\n\nstruct _hash_t {\n    unsigned int ref;\n    xmpp_ctx_t *ctx;\n    hash_free_func free;\n    int length;\n    int num_keys;\n    hashentry_t **entries;\n};\n\nstruct _hash_iterator_t {\n    unsigned int ref;\n    hash_t *table;\n    hashentry_t *entry;\n    int index;\n};\n\n/** allocate and initialize a new hash table */\nhash_t *hash_new(xmpp_ctx_t *ctx, int size, hash_free_func free_func)\n{\n    hash_t *result = NULL;\n\n    result = strophe_alloc(ctx, sizeof(hash_t));\n    if (result != NULL) {\n        result->entries = strophe_alloc(ctx, size * sizeof(hashentry_t *));\n        if (result->entries == NULL) {\n            strophe_free(ctx, result);\n            return NULL;\n        }\n        memset(result->entries, 0, size * sizeof(hashentry_t *));\n        result->length = size;\n\n        result->ctx = ctx;\n        result->free = free_func;\n        result->num_keys = 0;\n        /* give the caller a reference */\n        result->ref = 1;\n    }\n\n    return result;\n}\n\n/** obtain a new reference to an existing hash table */\nhash_t *hash_clone(hash_t *table)\n{\n    table->ref++;\n    return table;\n}\n\n/** release a hash table that is no longer needed */\nvoid hash_release(hash_t *table)\n{\n    xmpp_ctx_t *ctx = table->ctx;\n    hashentry_t *entry, *next;\n    int i;\n\n    if (table->ref > 1)\n        table->ref--;\n    else {\n        for (i = 0; i < table->length; i++) {\n            entry = table->entries[i];\n            while (entry != NULL) {\n                next = entry->next;\n                strophe_free(ctx, entry->key);\n                if (table->free)\n                    table->free(ctx, entry->value);\n                strophe_free(ctx, entry);\n                entry = next;\n            }\n        }\n        strophe_free(ctx, table->entries);\n        strophe_free(ctx, table);\n    }\n}\n\n/** hash a key for our table lookup */\nstatic int _hash_key(hash_t *table, const char *key)\n{\n    unsigned hash = 0;\n    unsigned shift = 0;\n    const unsigned char *c = (const unsigned char *)key;\n\n    while (*c != 0) {\n        /* assume 32 bit ints */\n        hash ^= ((unsigned)*c++ << shift);\n        shift += 8;\n        if (shift > 24)\n            shift = 0;\n    }\n    return hash % (unsigned)table->length;\n}\n\nhashentry_t *_hash_entry_find(hash_t *table, const char *key)\n{\n    hashentry_t *entry;\n    int table_index = _hash_key(table, key);\n\n    /* look up the hash entry */\n    entry = table->entries[table_index];\n    while (entry != NULL) {\n        /* traverse the linked list looking for the key */\n        if (!strcmp(key, entry->key)) {\n            /* match */\n            break;\n        }\n        entry = entry->next;\n    }\n    return entry;\n}\n\n/** add a key, value pair to a hash table.\n *  each key can appear only once; the value of any\n *  identical key will be replaced\n */\nint hash_add(hash_t *table, const char *key, void *data)\n{\n    xmpp_ctx_t *ctx = table->ctx;\n    hashentry_t *entry = NULL;\n    int table_index = _hash_key(table, key);\n\n    /* find and replace existing entry, if any */\n    entry = _hash_entry_find(table, key);\n\n    if (entry == NULL) {\n        /* allocate and fill a new entry */\n        entry = strophe_alloc(ctx, sizeof(hashentry_t));\n        if (!entry)\n            return -1;\n        entry->key = strophe_strdup(ctx, key);\n        if (!entry->key) {\n            strophe_free(ctx, entry);\n            return -1;\n        }\n        /* insert ourselves in the linked list */\n        entry->next = table->entries[table_index];\n        table->entries[table_index] = entry;\n        table->num_keys++;\n    } else {\n        if (table->free)\n            table->free(ctx, entry->value);\n    }\n\n    entry->value = data;\n\n    return 0;\n}\n\n/** look up a key in a hash table */\nvoid *hash_get(hash_t *table, const char *key)\n{\n    hashentry_t *entry;\n\n    entry = _hash_entry_find(table, key);\n    return entry == NULL ? NULL : entry->value;\n}\n\n/** delete a key from a hash table */\nint hash_drop(hash_t *table, const char *key)\n{\n    xmpp_ctx_t *ctx = table->ctx;\n    hashentry_t *entry, *prev;\n    int table_index = _hash_key(table, key);\n\n    /* look up the hash entry */\n    entry = table->entries[table_index];\n    prev = NULL;\n    while (entry != NULL) {\n        /* traverse the linked list looking for the key */\n        if (!strcmp(key, entry->key)) {\n            /* match, remove the entry */\n            strophe_free(ctx, entry->key);\n            if (table->free)\n                table->free(ctx, entry->value);\n            if (prev == NULL) {\n                table->entries[table_index] = entry->next;\n            } else {\n                prev->next = entry->next;\n            }\n            strophe_free(ctx, entry);\n            table->num_keys--;\n            return 0;\n        }\n        prev = entry;\n        entry = entry->next;\n    }\n    /* no match */\n    return -1;\n}\n\nint hash_num_keys(hash_t *table)\n{\n    return table->num_keys;\n}\n\n/** allocate and initialize a new iterator */\nhash_iterator_t *hash_iter_new(hash_t *table)\n{\n    xmpp_ctx_t *ctx = table->ctx;\n    hash_iterator_t *iter;\n\n    iter = strophe_alloc(ctx, sizeof(*iter));\n    if (iter != NULL) {\n        iter->ref = 1;\n        iter->table = hash_clone(table);\n        iter->entry = NULL;\n        iter->index = -1;\n    }\n\n    return iter;\n}\n\n/** release an iterator that is no longer needed */\nvoid hash_iter_release(hash_iterator_t *iter)\n{\n    xmpp_ctx_t *ctx = iter->table->ctx;\n\n    iter->ref--;\n\n    if (iter->ref == 0) { // ref is unsigned!!!\n        hash_release(iter->table);\n        strophe_free(ctx, iter);\n    }\n}\n\n/** return the next hash table key from the iterator.\n    the returned key should not be freed */\nconst char *hash_iter_next(hash_iterator_t *iter)\n{\n    hash_t *table = iter->table;\n    hashentry_t *entry = iter->entry;\n    int i;\n\n    /* advance until we find the next entry */\n    if (entry != NULL)\n        entry = entry->next;\n    if (entry == NULL) {\n        /* we're off the end of list, search for a new entry */\n        i = iter->index + 1;\n        while (i < iter->table->length) {\n            entry = table->entries[i];\n            if (entry != NULL) {\n                iter->index = i;\n                break;\n            }\n            i++;\n        }\n    }\n\n    if (entry == NULL) {\n        /* no more keys! */\n        return NULL;\n    }\n\n    /* remember our current match */\n    iter->entry = entry;\n    return entry->key;\n}\n"
  },
  {
    "path": "src/hash.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* hash.h\n** strophe XMPP client library -- hash table interface\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Hash table API.\n */\n\n#ifndef __LIBSTROPHE_HASH_H__\n#define __LIBSTROPHE_HASH_H__\n\ntypedef struct _hash_t hash_t;\n\ntypedef void (*hash_free_func)(const xmpp_ctx_t *ctx, void *p);\n\n/** allocate and initialize a new hash table */\nhash_t *hash_new(xmpp_ctx_t *ctx, int size, hash_free_func free_func);\n\n/** allocate a new reference to an existing hash table */\nhash_t *hash_clone(hash_t *table);\n\n/** release a hash table when no longer needed */\nvoid hash_release(hash_t *table);\n\n/** add a key, value pair to a hash table.\n *  each key can appear only once; the value of any\n *  identical key will be replaced\n */\nint hash_add(hash_t *table, const char *key, void *data);\n\n/** look up a key in a hash table */\nvoid *hash_get(hash_t *table, const char *key);\n\n/** delete a key from a hash table */\nint hash_drop(hash_t *table, const char *key);\n\n/** return the number of keys in a hash */\nint hash_num_keys(hash_t *table);\n\n/** hash key iterator functions */\ntypedef struct _hash_iterator_t hash_iterator_t;\n\n/** allocate and initialize a new iterator */\nhash_iterator_t *hash_iter_new(hash_t *table);\n\n/** release an iterator that is no longer needed */\nvoid hash_iter_release(hash_iterator_t *iter);\n\n/** return the next hash table key from the iterator.\n    the returned key should not be freed */\nconst char *hash_iter_next(hash_iterator_t *iter);\n\n#endif /* __LIBXMPPP_HASH_H__ */\n"
  },
  {
    "path": "src/jid.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* jid.c\n** strophe XMPP client library -- helper functions for parsing JIDs\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  JID creation and parsing.\n */\n\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n\n/** Create a JID string from component parts node, domain, and resource.\n *\n *  @param ctx the Strophe context object\n *  @param node a string representing the node\n *  @param domain a string representing the domain.  Required.\n *  @param resource a string representing the resource\n *\n *  @return an allocated string with the full JID or NULL if no domain\n *      is specified\n */\nchar *xmpp_jid_new(xmpp_ctx_t *ctx,\n                   const char *node,\n                   const char *domain,\n                   const char *resource)\n{\n    char *result;\n    size_t len, nlen, dlen, rlen;\n\n    /* jid must at least have a domain */\n    if (domain == NULL) {\n        strophe_error(ctx, \"jid\", \"domainpart missing.\");\n        return NULL;\n    }\n\n    /* accumulate lengths */\n    dlen = strlen(domain);\n    nlen = (node) ? strlen(node) + 1 : 0;\n    rlen = (resource) ? strlen(resource) + 1 : 0;\n    len = nlen + dlen + rlen;\n\n    if (dlen > 1023) {\n        strophe_error(ctx, \"jid\", \"domainpart too long.\");\n        return NULL;\n    }\n    if (nlen > 1024) {\n        strophe_error(ctx, \"jid\", \"localpart too long.\");\n        return NULL;\n    }\n    if (rlen > 1024) {\n        strophe_error(ctx, \"jid\", \"resourcepart too long.\");\n        return NULL;\n    }\n\n    if (node) {\n        if (strcspn(node, \"\\\"&'/:<>@\") != nlen - 1) {\n            strophe_error(ctx, \"jid\", \"localpart contained invalid character.\");\n            return NULL;\n        }\n    }\n\n    /* concat components */\n    result = strophe_alloc(ctx, len + 1);\n    if (result != NULL) {\n        if (node != NULL) {\n            memcpy(result, node, nlen - 1);\n            result[nlen - 1] = '@';\n        }\n        memcpy(result + nlen, domain, dlen);\n        if (resource != NULL) {\n            result[nlen + dlen] = '/';\n            memcpy(result + nlen + dlen + 1, resource, rlen - 1);\n        }\n        result[len] = '\\0';\n    }\n\n    return result;\n}\n\n/** Create a bare JID from a JID.\n *\n *  @param ctx the Strophe context object\n *  @param jid the JID\n *\n *  @return an allocated string with the bare JID or NULL on an error\n */\nchar *xmpp_jid_bare(xmpp_ctx_t *ctx, const char *jid)\n{\n    char *result;\n    size_t len;\n\n    len = strcspn(jid, \"/\");\n    result = strophe_alloc(ctx, len + 1);\n    if (result != NULL) {\n        memcpy(result, jid, len);\n        result[len] = '\\0';\n    }\n\n    return result;\n}\n\n/** Create a node string from a JID.\n *\n *  @param ctx a Strophe context object\n *  @param jid the JID\n *\n *  @return an allocated string with the node or NULL if no node is found\n *      or an error occurs\n */\nchar *xmpp_jid_node(xmpp_ctx_t *ctx, const char *jid)\n{\n    char *dup_jid = strophe_strdup(ctx, jid);\n    char *result = NULL;\n    const char *c;\n\n    /* Apply the same parsing rules from rfc7622 Section 3.2\n     * 1. Strip resource\n     * 2. take part before the '@'\n     */\n\n    char *resource = strchr(dup_jid, '/');\n    if (resource != NULL) {\n        *resource = '\\0';\n    }\n\n    c = strchr(dup_jid, '@');\n    if (c != NULL) {\n        result = strophe_alloc(ctx, (c - dup_jid) + 1);\n        if (result != NULL) {\n            memcpy(result, dup_jid, (c - dup_jid));\n            result[c - dup_jid] = '\\0';\n        }\n    }\n    strophe_free(ctx, dup_jid);\n\n    return result;\n}\n\n/** Create a domain string from a JID.\n *\n *  @param ctx the Strophe context object\n *  @param jid the JID\n *\n *  @return an allocated string with the domain or NULL on an error\n */\nchar *xmpp_jid_domain(xmpp_ctx_t *ctx, const char *jid)\n{\n    char *dup_jid = strophe_strdup(ctx, jid);\n\n    /* rfc7622 Section 3.2\n     * 1.  Remove any portion from the first '/' character to the end of the\n     *     string (if there is a '/' character present).\n     */\n\n    char *resource = strchr(dup_jid, '/');\n    if (resource != NULL) {\n        *resource = '\\0';\n    }\n\n    /* 2.  Remove any portion from the beginning of the string to the first\n     *     '@' character (if there is an '@' character present).\n     */\n    char *at_sign = strchr(dup_jid, '@');\n    char *result = NULL;\n    if (at_sign != NULL) {\n        result = strophe_strdup(ctx, (at_sign + 1));\n    } else {\n        result = strophe_strdup(ctx, dup_jid);\n    }\n    strophe_free(ctx, dup_jid);\n\n    return result;\n}\n\n/** Create a resource string from a JID.\n *\n *  @param ctx a Strophe context object\n *  @param jid the JID\n *\n *  @return an allocated string with the resource or NULL if no resource\n *      is found or an error occurs\n */\nchar *xmpp_jid_resource(xmpp_ctx_t *ctx, const char *jid)\n{\n    const char *c;\n\n    c = strchr(jid, '/');\n    return c != NULL ? strophe_strdup(ctx, c + 1) : NULL;\n}\n"
  },
  {
    "path": "src/md5.c",
    "content": "/* md5.c\n** MD5 hash function implemention, adapted for local use\n**\n** This code is in the Public Domain\n*/\n\n/*\n * This code implements the MD5 message-digest algorithm.\n * The algorithm is due to Ron Rivest.  This code was\n * written by Colin Plumb in 1993, no copyright is claimed.\n * This code is in the public domain; do with it what you wish.\n *\n * Equivalent code is available from RSA Data Security, Inc.\n * This code has been tested against that, and is equivalent,\n * except that you don't need to include two pages of legalese\n * with every copy.\n *\n * To compute the message digest of a chunk of bytes, declare an\n * MD5Context structure, pass it to MD5Init, call MD5Update as\n * needed on buffers full of bytes, and then call MD5Final, which\n * will fill a supplied 16-byte array with the digest.\n */\n\n/** @file\n *  MD5 hash.\n */\n\n#include <string.h> /* memcpy(), memset() */\n#include \"md5.h\"\n\n/* little-endian word access macros */\n#define GET_32BIT_LSB_FIRST(cp)                 \\\n    (((uint32_t)(unsigned char)(cp)[0]) |       \\\n     ((uint32_t)(unsigned char)(cp)[1] << 8) |  \\\n     ((uint32_t)(unsigned char)(cp)[2] << 16) | \\\n     ((uint32_t)(unsigned char)(cp)[3] << 24))\n\n#define PUT_32BIT_LSB_FIRST(cp, value)    \\\n    do {                                  \\\n        (cp)[0] = (value) & 0xFF;         \\\n        (cp)[1] = ((value) >> 8) & 0xFF;  \\\n        (cp)[2] = ((value) >> 16) & 0xFF; \\\n        (cp)[3] = ((value) >> 24) & 0xFF; \\\n    } while (0)\n\nstatic void MD5Transform(uint32_t buf[4], const unsigned char inext[64]);\n\n/*\n * Start MD5 accumulation.  Set bit count to 0 and buffer to mysterious\n * initialization constants.\n */\nvoid MD5Init(struct MD5Context *ctx)\n{\n    ctx->buf[0] = 0x67452301;\n    ctx->buf[1] = 0xefcdab89;\n    ctx->buf[2] = 0x98badcfe;\n    ctx->buf[3] = 0x10325476;\n\n    ctx->bits[0] = 0;\n    ctx->bits[1] = 0;\n\n    memset(ctx->in, 0, 64);\n}\n\n/*\n * Update context to reflect the concatenation of another buffer full\n * of bytes.\n */\nvoid MD5Update(struct MD5Context *ctx, unsigned char const *buf, uint32_t len)\n{\n    uint32_t t;\n\n    /* Update bitcount */\n\n    t = ctx->bits[0];\n    if ((ctx->bits[0] = (t + ((uint32_t)len << 3)) & 0xffffffff) < t)\n        ctx->bits[1]++; /* Carry from low to high */\n    ctx->bits[1] += len >> 29;\n\n    t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */\n\n    /* Handle any leading odd-sized chunks */\n\n    if (t) {\n        unsigned char *p = ctx->in + t;\n\n        t = 64 - t;\n        if (len < t) {\n            memcpy(p, buf, len);\n            return;\n        }\n        memcpy(p, buf, t);\n        MD5Transform(ctx->buf, ctx->in);\n        buf += t;\n        len -= t;\n    }\n    /* Process data in 64-byte chunks */\n\n    while (len >= 64) {\n        memcpy(ctx->in, buf, 64);\n        MD5Transform(ctx->buf, ctx->in);\n        buf += 64;\n        len -= 64;\n    }\n\n    /* Handle any remaining bytes of data. */\n\n    memcpy(ctx->in, buf, len);\n}\n\n/*\n * Final wrapup - pad to 64-byte boundary with the bit pattern\n * 1 0* (64-bit count of bits processed, MSB-first)\n */\nvoid MD5Final(unsigned char digest[16], struct MD5Context *ctx)\n{\n    unsigned count;\n    unsigned char *p;\n\n    /* Compute number of bytes mod 64 */\n    count = (ctx->bits[0] >> 3) & 0x3F;\n\n    /* Set the first char of padding to 0x80.  This is safe since there is\n       always at least one byte free */\n    p = ctx->in + count;\n    *p++ = 0x80;\n\n    /* Bytes of padding needed to make 64 bytes */\n    count = 64 - 1 - count;\n\n    /* Pad out to 56 mod 64 */\n    if (count < 8) {\n        /* Two lots of padding:  Pad the first block to 64 bytes */\n        memset(p, 0, count);\n        MD5Transform(ctx->buf, ctx->in);\n\n        /* Now fill the next block with 56 bytes */\n        memset(ctx->in, 0, 56);\n    } else {\n        /* Pad block to 56 bytes */\n        memset(p, 0, count - 8);\n    }\n\n    /* Append length in bits and transform */\n    PUT_32BIT_LSB_FIRST(ctx->in + 56, ctx->bits[0]);\n    PUT_32BIT_LSB_FIRST(ctx->in + 60, ctx->bits[1]);\n\n    MD5Transform(ctx->buf, ctx->in);\n    PUT_32BIT_LSB_FIRST(digest, ctx->buf[0]);\n    PUT_32BIT_LSB_FIRST(digest + 4, ctx->buf[1]);\n    PUT_32BIT_LSB_FIRST(digest + 8, ctx->buf[2]);\n    PUT_32BIT_LSB_FIRST(digest + 12, ctx->buf[3]);\n    memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */\n}\n\n/* The four core functions - F1 is optimized somewhat */\n\n/* #define F1(x, y, z) (x & y | ~x & z) */\n#define F1(x, y, z) (z ^ (x & (y ^ z)))\n#define F2(x, y, z) F1(z, x, y)\n#define F3(x, y, z) (x ^ y ^ z)\n#define F4(x, y, z) (y ^ (x | ~z))\n\n/* This is the central step in the MD5 algorithm. */\n/* debugging version: */\n/*\n#define MD5STEP(f, w, x, y, z, data, s) \\\n        printf(\"MD5STEP:  w: %x x: %x y: %x z: %x data: %x s: %x\\n\", \\\n                w, x, y, z, data, s); \\\n        printf(\"f(x,y,z) = %x\\n\", f(x,y,z)+data); \\\n        ( w += f(x, y, z) + data,  printf(\" - w: %x \", w), \\\n        w = w<<s | w>>(32-s),  printf(\" - w: %x\\n\", w), w += x )\n*/\n#define MD5STEP(f, w, x, y, z, data, s) \\\n    (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x)\n\n/*\n * The core of the MD5 algorithm, this alters an existing MD5 hash to\n * reflect the addition of 16 longwords of new data.  MD5Update blocks\n * the data and converts bytes into longwords for this routine.\n */\nstatic void MD5Transform(uint32_t buf[4], const unsigned char inext[64])\n{\n    register uint32_t a, b, c, d, i;\n    uint32_t in[16];\n\n    for (i = 0; i < 16; i++)\n        in[i] = GET_32BIT_LSB_FIRST(inext + 4 * i);\n\n    a = buf[0];\n    b = buf[1];\n    c = buf[2];\n    d = buf[3];\n\n    MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);\n\n    MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);\n    MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);\n    MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);\n    MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);\n    MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);\n    MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);\n    MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);\n    MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);\n    MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);\n    MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);\n    MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);\n    MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);\n    MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);\n    MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);\n    MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);\n\n    MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);\n    MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);\n    MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);\n    MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);\n    MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);\n    MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);\n    MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);\n    MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);\n    MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);\n    MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);\n    MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);\n    MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);\n    MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);\n    MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);\n    MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);\n    MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);\n\n    MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);\n    MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);\n    MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);\n    MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);\n    MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);\n    MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);\n    MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);\n    MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);\n    MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);\n    MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);\n    MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);\n    MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);\n    MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);\n    MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);\n    MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);\n    MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);\n\n    MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);\n    MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);\n    MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);\n    MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);\n    MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);\n    MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);\n    MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);\n    MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);\n    MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);\n    MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);\n    MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);\n    MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);\n    MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);\n    MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);\n    MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);\n    MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);\n\n    buf[0] += a;\n    buf[1] += b;\n    buf[2] += c;\n    buf[3] += d;\n}\n"
  },
  {
    "path": "src/md5.h",
    "content": "/* md5.h\n** interface to MD5 hash function\n**\n** This code is in the Public Domain.\n*/\n\n/** @file\n *  MD5 hash API.\n */\n\n#ifndef MD5_H\n#define MD5_H\n\n/* make sure the stdint.h types are available */\n#include \"ostypes.h\"\n\nstruct MD5Context {\n    uint32_t buf[4];\n    uint32_t bits[2];\n    unsigned char in[64];\n};\n\nvoid MD5Init(struct MD5Context *context);\nvoid MD5Update(struct MD5Context *context,\n               unsigned char const *buf,\n               uint32_t len);\nvoid MD5Final(unsigned char digest[16], struct MD5Context *context);\n\n#endif /* !MD5_H */\n"
  },
  {
    "path": "src/ostypes.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* ostypes.h\n** strophe XMPP client library -- type definitions for platforms\n**     without stdint.h\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Type definitions for platforms without stdint.h.\n */\n\n#ifndef __LIBSTROPHE_OSTYPES_H__\n#define __LIBSTROPHE_OSTYPES_H__\n\n#include <stddef.h> /* size_t */\n\n#if defined(_MSC_VER) && _MSC_VER < 1600\ntypedef signed char int8_t;\ntypedef short int int16_t;\ntypedef int int32_t;\ntypedef __int64 int64_t;\n\ntypedef unsigned char uint8_t;\ntypedef unsigned short int uint16_t;\ntypedef unsigned int uint32_t;\ntypedef unsigned __int64 uint64_t;\n\n#ifndef UINT16_MAX\n#define UINT16_MAX ((uint16_t)0xffff)\n#endif /* UINT16_MAX */\n#ifndef UINT32_MAX\n#define UINT32_MAX ((uint32_t)0xffffffff)\n#endif /* UINT32_MAX */\n#ifndef SIZE_MAX\n#define SIZE_MAX UINT32_MAX\n#endif /* SIZE_MAX */\n\n#else\n#include <stdint.h>\n#endif\n\n#endif /* __LIBSTROPHE_OSTYPES_H__ */\n"
  },
  {
    "path": "src/parser.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* parser.h\n** strophe XMPP client library -- parser structures and functions\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express or\n**  implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Internally used functions and structures.\n */\n\n#ifndef __LIBSTROPHE_PARSER_H__\n#define __LIBSTROPHE_PARSER_H__\n\n#include \"strophe.h\"\n\ntypedef struct _parser_t parser_t;\n\ntypedef void (*parser_start_callback)(char *name, char **attrs, void *userdata);\ntypedef void (*parser_end_callback)(char *name, void *userdata);\ntypedef void (*parser_stanza_callback)(xmpp_stanza_t *stanza, void *userdata);\n\nparser_t *parser_new(xmpp_ctx_t *ctx,\n                     parser_start_callback startcb,\n                     parser_end_callback endcb,\n                     parser_stanza_callback stanzacb,\n                     void *userdata);\nvoid parser_free(parser_t *parser);\nchar *parser_attr_name(xmpp_ctx_t *ctx, char *nsname);\nint parser_reset(parser_t *parser);\nint parser_feed(parser_t *parser, char *chunk, int len);\n\n#endif /* __LIBSTROPHE_PARSER_H__ */\n"
  },
  {
    "path": "src/parser_expat.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* parser.c\n** strophe XMPP client library -- xml parser handlers and utility functions\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  XML parser handlers.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <expat.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"parser.h\"\n\n/* Allocate inner text by this number bytes more. Expat splits string\n * \"new\\nline\" into 3 strings: \"new\" \"\\n\" \"line\". Expecting this pattern,\n * we can leave few bytes in the inner_text for \"\\n\". It should reduce\n * number of re-allocations in 2 times for multi-line texts. */\n#define INNER_TEXT_PADDING 2\n\nstruct _parser_t {\n    xmpp_ctx_t *ctx;\n    XML_Parser expat;\n    parser_start_callback startcb;\n    parser_end_callback endcb;\n    parser_stanza_callback stanzacb;\n    void *userdata;\n    int depth;\n    xmpp_stanza_t *stanza;\n    char *inner_text;\n    /* number of allocated bytes */\n    int inner_text_size;\n    /* excluding terminal '\\0' */\n    int inner_text_used;\n};\n\n/* Use the Unit Separator to delimit namespace and name in our XML */\nconst XML_Char namespace_sep = '\\x1F';\n\n/*\n * Cached strophe ctx. It is used for memory suite.\n * Note, expat doesn't support userdata in memory suite, therefore,\n * we can support only one strophe context. If user creates more than one\n * context, this module will fallback to default library allocator for all\n * contexts other than mem_ctx.\n */\nstatic xmpp_ctx_t *mem_ctx = NULL;\n\nstatic void *parser_mem_malloc(size_t size)\n{\n    if (mem_ctx != NULL)\n        return strophe_alloc(mem_ctx, size);\n    else\n        return NULL;\n}\n\nstatic void *parser_mem_realloc(void *ptr, size_t size)\n{\n    if (mem_ctx != NULL)\n        return strophe_realloc(mem_ctx, ptr, size);\n    else\n        return NULL;\n}\n\nstatic void parser_mem_free(void *ptr)\n{\n    if (mem_ctx != NULL)\n        strophe_free(mem_ctx, ptr);\n}\n\nstatic const XML_Memory_Handling_Suite parser_mem_suite = {\n    .malloc_fcn = &parser_mem_malloc,\n    .realloc_fcn = &parser_mem_realloc,\n    .free_fcn = &parser_mem_free,\n};\n\n/* return allocated string with the name from a delimited\n * namespace/name string */\nstatic char *_xml_name(xmpp_ctx_t *ctx, const char *nsname)\n{\n    char *result = NULL;\n    const char *c;\n    size_t len;\n\n    c = strchr(nsname, namespace_sep);\n    if (c == NULL)\n        return strophe_strdup(ctx, nsname);\n\n    c++;\n    len = strlen(c);\n    result = strophe_alloc(ctx, len + 1);\n    if (result != NULL) {\n        memcpy(result, c, len);\n        result[len] = '\\0';\n    }\n\n    return result;\n}\n\n/* return allocated string with the namespace from a delimited string */\nstatic char *_xml_namespace(xmpp_ctx_t *ctx, const char *nsname)\n{\n    char *result = NULL;\n    const char *c;\n\n    c = strchr(nsname, namespace_sep);\n    if (c != NULL) {\n        result = strophe_alloc(ctx, (c - nsname) + 1);\n        if (result != NULL) {\n            memcpy(result, nsname, (c - nsname));\n            result[c - nsname] = '\\0';\n        }\n    }\n\n    return result;\n}\n\nstatic void _set_attributes(xmpp_stanza_t *stanza, const XML_Char **attrs)\n{\n    char *attr;\n    int i;\n\n    if (!attrs)\n        return;\n\n    for (i = 0; attrs[i]; i += 2) {\n        /* namespaced attributes aren't used in xmpp, discard namespace */\n        attr = _xml_name(stanza->ctx, attrs[i]);\n        xmpp_stanza_set_attribute(stanza, attr, attrs[i + 1]);\n        strophe_free(stanza->ctx, attr);\n    }\n}\n\nstatic void complete_inner_text(parser_t *parser)\n{\n    xmpp_stanza_t *stanza;\n\n    if (parser->inner_text) {\n        /* create and populate stanza */\n        stanza = xmpp_stanza_new(parser->ctx);\n        /* FIXME: disconnect on allocation error */\n        if (stanza) {\n            xmpp_stanza_set_text(stanza, parser->inner_text);\n            xmpp_stanza_add_child_ex(parser->stanza, stanza, 0);\n        }\n        strophe_free(parser->ctx, parser->inner_text);\n        parser->inner_text = NULL;\n        parser->inner_text_size = 0;\n        parser->inner_text_used = 0;\n    }\n}\n\nstatic void\n_start_element(void *userdata, const XML_Char *nsname, const XML_Char **attrs)\n{\n    parser_t *parser = (parser_t *)userdata;\n    xmpp_stanza_t *child;\n    char *ns, *name;\n\n    ns = _xml_namespace(parser->ctx, nsname);\n    name = _xml_name(parser->ctx, nsname);\n\n    if (parser->depth == 0) {\n        /* notify the owner */\n        if (parser->startcb)\n            parser->startcb(name, (char **)attrs, parser->userdata);\n    } else {\n        /* build stanzas at depth 1 */\n        if (!parser->stanza && parser->depth != 1) {\n            /* something terrible happened */\n            /* FIXME: shutdown disconnect */\n            strophe_error(parser->ctx, \"parser\",\n                          \"oops, where did our stanza go?\");\n        } else {\n            child = xmpp_stanza_new(parser->ctx);\n            if (!child) {\n                /* FIXME: can't allocate, disconnect */\n            }\n            xmpp_stanza_set_name(child, name);\n            _set_attributes(child, attrs);\n            if (ns)\n                xmpp_stanza_set_ns(child, ns);\n\n            if (parser->stanza != NULL) {\n                complete_inner_text(parser);\n                xmpp_stanza_add_child_ex(parser->stanza, child, 0);\n            }\n            parser->stanza = child;\n        }\n    }\n\n    if (ns)\n        strophe_free(parser->ctx, ns);\n    if (name)\n        strophe_free(parser->ctx, name);\n\n    parser->depth++;\n}\n\nstatic void _end_element(void *userdata, const XML_Char *name)\n{\n    parser_t *parser = (parser_t *)userdata;\n\n    parser->depth--;\n\n    if (parser->depth == 0) {\n        /* notify the owner */\n        if (parser->endcb)\n            parser->endcb((char *)name, parser->userdata);\n    } else {\n        complete_inner_text(parser);\n        if (parser->stanza->parent) {\n            /* we're finishing a child stanza, so set current to the parent */\n            parser->stanza = parser->stanza->parent;\n        } else {\n            if (parser->stanzacb)\n                parser->stanzacb(parser->stanza, parser->userdata);\n            xmpp_stanza_release(parser->stanza);\n            parser->stanza = NULL;\n        }\n    }\n}\n\nstatic void _characters(void *userdata, const XML_Char *s, int len)\n{\n    parser_t *parser = (parser_t *)userdata;\n    char *p;\n\n    if (parser->depth < 2)\n        return;\n\n    /* Join all parts to a single resulting string. Stanza is created in\n     * _start_element() and _end_element(). */\n    if (parser->inner_text_used + len >= parser->inner_text_size) {\n        parser->inner_text_size =\n            parser->inner_text_used + len + 1 + INNER_TEXT_PADDING;\n        p = strophe_realloc(parser->ctx, parser->inner_text,\n                            parser->inner_text_size);\n        if (p == NULL) {\n            strophe_free(parser->ctx, parser->inner_text);\n            parser->inner_text = NULL;\n            parser->inner_text_used = 0;\n            parser->inner_text_size = 0;\n            return;\n        }\n        parser->inner_text = p;\n        parser->inner_text[parser->inner_text_used] = '\\0';\n    }\n    parser->inner_text_used += len;\n    strncat(parser->inner_text, s, len);\n}\n\nparser_t *parser_new(xmpp_ctx_t *ctx,\n                     parser_start_callback startcb,\n                     parser_end_callback endcb,\n                     parser_stanza_callback stanzacb,\n                     void *userdata)\n{\n    parser_t *parser;\n\n    parser = strophe_alloc(ctx, sizeof(parser_t));\n    if (parser != NULL) {\n        parser->ctx = ctx;\n        parser->expat = NULL;\n        parser->startcb = startcb;\n        parser->endcb = endcb;\n        parser->stanzacb = stanzacb;\n        parser->userdata = userdata;\n        parser->depth = 0;\n        parser->stanza = NULL;\n        parser->inner_text = NULL;\n        parser->inner_text_size = 0;\n        parser->inner_text_used = 0;\n\n        parser_reset(parser);\n    }\n\n    return parser;\n}\n\nchar *parser_attr_name(xmpp_ctx_t *ctx, char *nsname)\n{\n    return _xml_name(ctx, nsname);\n}\n\nstatic void _free_parent_stanza(xmpp_stanza_t *stanza)\n{\n    xmpp_stanza_t *parent;\n\n    for (parent = stanza; parent->parent != NULL; parent = parent->parent)\n        ;\n    xmpp_stanza_release(parent);\n}\n\n/* free a parser */\nvoid parser_free(parser_t *parser)\n{\n    if (parser->expat)\n        XML_ParserFree(parser->expat);\n\n    if (parser->stanza) {\n        _free_parent_stanza(parser->stanza);\n        parser->stanza = NULL;\n    }\n\n    if (parser->inner_text) {\n        strophe_free(parser->ctx, parser->inner_text);\n        parser->inner_text = NULL;\n    }\n\n    strophe_free(parser->ctx, parser);\n}\n\n/* shuts down and restarts XML parser.  true on success */\nint parser_reset(parser_t *parser)\n{\n    XML_Bool ret;\n    const XML_Memory_Handling_Suite *mem = NULL;\n\n    if (parser->expat) {\n        ret = XML_ParserReset(parser->expat, NULL);\n        if (ret != XML_TRUE) {\n            XML_ParserFree(parser->expat);\n            parser->expat = NULL;\n        }\n    } else {\n        if (mem_ctx == NULL)\n            mem_ctx = parser->ctx;\n        if (parser->ctx == mem_ctx)\n            mem = &parser_mem_suite;\n        parser->expat = XML_ParserCreate_MM(NULL, mem, &namespace_sep);\n    }\n\n    if (parser->stanza) {\n        _free_parent_stanza(parser->stanza);\n        parser->stanza = NULL;\n    }\n\n    if (parser->inner_text) {\n        strophe_free(parser->ctx, parser->inner_text);\n        parser->inner_text = NULL;\n    }\n\n    if (!parser->expat)\n        return 0;\n\n    parser->depth = 0;\n\n    XML_SetUserData(parser->expat, parser);\n    XML_SetElementHandler(parser->expat, _start_element, _end_element);\n    XML_SetCharacterDataHandler(parser->expat, _characters);\n\n    return 1;\n}\n\nint parser_feed(parser_t *parser, char *chunk, int len)\n{\n    return XML_Parse(parser->expat, chunk, len, 0);\n}\n"
  },
  {
    "path": "src/parser_libxml2.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* parser.c\n** strophe XMPP client library -- xml parser handlers and utility functions\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  XML parser handlers.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include <libxml/parser.h>\n#include <libxml/tree.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"parser.h\"\n\nstruct _parser_t {\n    xmpp_ctx_t *ctx;\n    xmlParserCtxtPtr xmlctx;\n    xmlSAXHandler handlers;\n    parser_start_callback startcb;\n    parser_end_callback endcb;\n    parser_stanza_callback stanzacb;\n    void *userdata;\n    int depth;\n    xmpp_stanza_t *stanza;\n};\n\nstatic void\n_set_attributes(xmpp_stanza_t *stanza, int nattrs, const xmlChar **attrs)\n{\n    int i, len;\n    char *value;\n\n    if (!attrs)\n        return;\n\n    /* SAX2 uses array of localname/prefix/uri/value_begin/value_end */\n    for (i = 0; i < nattrs * 5; i += 5) {\n        len = attrs[i + 4] - attrs[i + 3];\n        value = strophe_alloc(stanza->ctx, len + 1);\n        if (value) {\n            memcpy(value, attrs[i + 3], len);\n            value[len] = '\\0';\n            xmpp_stanza_set_attribute(stanza, (const char *)attrs[i], value);\n            strophe_free(stanza->ctx, value);\n        }\n    }\n}\n\n/* SAX2 gives us the attrs in an incredibly inconvenient array,\n * convert it to what the start callback is expecting */\nstatic char **\n_convert_attrs(parser_t *parser, int nattrs, const xmlChar **attrs)\n{\n    int c, i, o, len;\n    char *value;\n    char **ret;\n\n    if (!attrs)\n        return NULL;\n\n    ret = strophe_alloc(parser->ctx, (nattrs + 1) * 2 * sizeof(char *));\n    if (!ret)\n        return NULL;\n    memset(ret, 0, (nattrs + 1) * 2 * sizeof(char *));\n\n    for (c = 0; c < nattrs; c++) {\n        i = c * 5;\n        o = c * 2;\n\n        len = attrs[i + 4] - attrs[i + 3];\n        value = strophe_alloc(parser->ctx, len + 1);\n        if (value) {\n            memcpy(value, attrs[i + 3], len);\n            value[len] = '\\0';\n            ret[o] = strophe_strdup(parser->ctx, (char *)attrs[i]);\n            ret[o + 1] = value;\n        }\n    }\n\n    return ret;\n}\n\nstatic void _free_cbattrs(parser_t *parser, char **attrs)\n{\n    int i;\n\n    if (!attrs)\n        return;\n\n    for (i = 0; attrs[i]; i += 2) {\n        if (attrs[i])\n            strophe_free(parser->ctx, attrs[i]);\n        if (attrs[i + 1])\n            strophe_free(parser->ctx, attrs[i + 1]);\n    }\n\n    strophe_free(parser->ctx, attrs);\n}\n\nstatic void _start_element(void *userdata,\n                           const xmlChar *name,\n                           const xmlChar *prefix,\n                           const xmlChar *uri,\n                           int nnamespaces,\n                           const xmlChar **namespaces,\n                           int nattrs,\n                           int ndefaulted,\n                           const xmlChar **attrs)\n{\n    parser_t *parser = (parser_t *)userdata;\n    xmpp_stanza_t *child;\n    char **cbattrs;\n\n    UNUSED(prefix);\n    UNUSED(nnamespaces);\n    UNUSED(namespaces);\n    UNUSED(ndefaulted);\n\n    if (parser->depth == 0) {\n        /* notify the owner */\n        if (parser->startcb) {\n            cbattrs = _convert_attrs(parser, nattrs, attrs);\n            parser->startcb((char *)name, cbattrs, parser->userdata);\n            _free_cbattrs(parser, cbattrs);\n        }\n    } else {\n        /* build stanzas at depth 1 */\n        if (!parser->stanza && parser->depth != 1) {\n            /* something terrible happened */\n            /* FIXME: we should probably trigger a disconnect */\n            strophe_error(parser->ctx, \"parser\",\n                          \"oops, where did our stanza go?\");\n        } else if (!parser->stanza) {\n            /* starting a new toplevel stanza */\n            parser->stanza = xmpp_stanza_new(parser->ctx);\n            if (!parser->stanza) {\n                /* FIXME: can't allocate, disconnect */\n            }\n            xmpp_stanza_set_name(parser->stanza, (char *)name);\n            _set_attributes(parser->stanza, nattrs, attrs);\n            if (uri)\n                xmpp_stanza_set_ns(parser->stanza, (char *)uri);\n        } else {\n            /* starting a child of conn->stanza */\n            child = xmpp_stanza_new(parser->ctx);\n            if (!child) {\n                /* FIXME: can't allocate, disconnect */\n            }\n            xmpp_stanza_set_name(child, (char *)name);\n            _set_attributes(child, nattrs, attrs);\n            if (uri)\n                xmpp_stanza_set_ns(child, (char *)uri);\n\n            /* add child to parent */\n            xmpp_stanza_add_child_ex(parser->stanza, child, 0);\n\n            /* make child the current stanza */\n            parser->stanza = child;\n        }\n    }\n\n    parser->depth++;\n}\n\nstatic void _end_element(void *userdata,\n                         const xmlChar *name,\n                         const xmlChar *prefix,\n                         const xmlChar *uri)\n{\n    parser_t *parser = (parser_t *)userdata;\n\n    UNUSED(prefix);\n    UNUSED(uri);\n\n    parser->depth--;\n\n    if (parser->depth == 0) {\n        /* notify owner */\n        if (parser->endcb)\n            parser->endcb((char *)name, parser->userdata);\n    } else {\n        if (parser->stanza->parent) {\n            /* we're finishing a child stanza, so set current to the parent */\n            parser->stanza = parser->stanza->parent;\n        } else {\n            if (parser->stanzacb)\n                parser->stanzacb(parser->stanza, parser->userdata);\n            xmpp_stanza_release(parser->stanza);\n            parser->stanza = NULL;\n        }\n    }\n}\n\nstatic void _characters(void *userdata, const xmlChar *chr, int len)\n{\n    parser_t *parser = (parser_t *)userdata;\n    xmpp_stanza_t *stanza;\n\n    /* skip unimportant whitespace, etc */\n    if (parser->depth < 2)\n        return;\n\n    /* create and populate stanza */\n    stanza = xmpp_stanza_new(parser->ctx);\n    if (!stanza) {\n        /* FIXME: allocation error, disconnect */\n        return;\n    }\n    xmpp_stanza_set_text_with_size(stanza, (char *)chr, len);\n\n    xmpp_stanza_add_child_ex(parser->stanza, stanza, 0);\n}\n\n/* create a new parser */\nparser_t *parser_new(xmpp_ctx_t *ctx,\n                     parser_start_callback startcb,\n                     parser_end_callback endcb,\n                     parser_stanza_callback stanzacb,\n                     void *userdata)\n{\n    parser_t *parser;\n\n    parser = strophe_alloc(ctx, sizeof(parser_t));\n    if (parser != NULL) {\n        parser->ctx = ctx;\n        parser->xmlctx = NULL;\n        memset(&parser->handlers, 0, sizeof(xmlSAXHandler));\n        parser->handlers.initialized = XML_SAX2_MAGIC;\n        parser->handlers.startElementNs = _start_element;\n        parser->handlers.endElementNs = _end_element;\n        parser->handlers.characters = _characters;\n        parser->startcb = startcb;\n        parser->endcb = endcb;\n        parser->stanzacb = stanzacb;\n        parser->userdata = userdata;\n        parser->depth = 0;\n        parser->stanza = NULL;\n\n        parser_reset(parser);\n    }\n\n    return parser;\n}\n\nchar *parser_attr_name(xmpp_ctx_t *ctx, char *nsname)\n{\n    return strophe_strdup(ctx, nsname);\n}\n\nstatic void _free_parent_stanza(xmpp_stanza_t *stanza)\n{\n    xmpp_stanza_t *parent;\n\n    for (parent = stanza; parent->parent != NULL; parent = parent->parent)\n        ;\n    xmpp_stanza_release(parent);\n}\n\n/* free a parser */\nvoid parser_free(parser_t *parser)\n{\n    if (parser->xmlctx)\n        xmlFreeParserCtxt(parser->xmlctx);\n    if (parser->stanza)\n        _free_parent_stanza(parser->stanza);\n    strophe_free(parser->ctx, parser);\n}\n\n/* shuts down and restarts XML parser.  true on success */\nint parser_reset(parser_t *parser)\n{\n    if (parser->xmlctx)\n        xmlFreeParserCtxt(parser->xmlctx);\n    if (parser->stanza)\n        _free_parent_stanza(parser->stanza);\n\n    parser->stanza = NULL;\n    parser->depth = 0;\n\n    parser->xmlctx =\n        xmlCreatePushParserCtxt(&parser->handlers, parser, NULL, 0, NULL);\n\n    return parser->xmlctx ? 1 : 0;\n}\n\n/* feed a chunk of data to the parser */\nint parser_feed(parser_t *parser, char *chunk, int len)\n{\n    /* xmlParseChunk API returns 0 on success which is opposite logic to\n       the status returned by parser_feed */\n    return !xmlParseChunk(parser->xmlctx, chunk, len, 0);\n}\n"
  },
  {
    "path": "src/rand.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* rand.c\n * strophe XMPP client library -- pseudo-random number generator\n *\n * Copyright (C) 2014 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/** @file\n *  Pseudo-random number generator.\n *\n *  Implemented Hash_DRBG mechanism according to NIST SP 800-90A.\n *  Hash function is SHA1.\n */\n\n/** @defgroup Random Pseudo-random number generator\n */\n\n#include <assert.h>\n#include <string.h> /* memeset */\n#include <time.h>   /* clock, time */\n\n#if !defined(_WIN32)\n#include <unistd.h>\n#endif\n\n#if !defined(DONT_USE_GETRANDOM) && defined(__linux__) && \\\n    defined(__GLIBC_PREREQ)\n#if __GLIBC_PREREQ(2, 25)\n#define USE_GETRANDOM\n#include <sys/random.h>\n#include <errno.h>\n#endif\n#endif\n\n#include \"common.h\"  /* strophe_alloc, strophe_free */\n#include \"ostypes.h\" /* uint8_t, uint32_t, size_t */\n\n#ifndef USE_GETRANDOM\n#include \"sha1.h\"\n\n#define outlen SHA1_DIGEST_SIZE\n#define seedlen (440 / 8)\n#define reseed_interval 0x7fffffff\n\n/* maximum number of bytes that can be generated per call */\n#define GENERATE_MAX (outlen * 10)\n#define ENTROPY_MAX 128\n#define NONCE_MAX 8\n\n#define RESEED_NEEDED (-1)\n\nstruct Hash_DRBG_CTX_struc {\n    uint8_t V[seedlen];\n    uint8_t C[seedlen];\n    uint32_t reseed_counter;\n};\ntypedef struct Hash_DRBG_CTX_struc Hash_DRBG_CTX;\n\nstruct _xmpp_rand_t {\n    int inited;\n    unsigned reseed_count;\n    Hash_DRBG_CTX ctx;\n};\n\n/* returns smallest number mupliple of y that not less than x */\n#define round_up(x, y) (((x) + (y) - 1) / (y) * (y))\n/* returns smallest integer number that not less than x/y */\n#define div_round_up(x, y) (((x) + (y) - 1) / (y))\n\n/* adds two arrays as numbers in big-endian representation and stores\n * result in the first one.\n */\nstatic void\narr_add(uint8_t *arr1, size_t arr1_len, uint8_t *arr2, size_t arr2_len)\n{\n    size_t i;\n    uint32_t acc;\n    uint32_t carry = 0;\n\n    assert(arr1_len >= arr2_len);\n\n    for (i = 1; (i <= arr2_len) || (carry != 0 && i <= arr1_len); ++i) {\n        acc = (uint32_t)arr1[arr1_len - i] + carry;\n        if (i <= arr2_len)\n            acc += (uint32_t)arr2[arr2_len - i];\n        carry = acc >> 8;\n        arr1[arr1_len - i] = (uint8_t)(acc & 0xff);\n    }\n}\n\n/* stores 32-bit number in big-endian representation */\nstatic void store_be32(uint32_t val, uint8_t be[4])\n{\n    be[0] = (uint8_t)((val >> 24) & 0xff);\n    be[1] = (uint8_t)((val >> 16) & 0xff);\n    be[2] = (uint8_t)((val >> 8) & 0xff);\n    be[3] = (uint8_t)(val & 0xff);\n}\n\nstatic void Hash_df(uint8_t *input_string,\n                    size_t input_string_len,\n                    uint8_t *output_string,\n                    size_t no_of_bytes_to_return)\n{\n    uint8_t counter;\n    uint8_t temp[round_up(seedlen, outlen)];\n    uint8_t conj[ENTROPY_MAX + NONCE_MAX + seedlen + 6];\n    size_t len;\n    size_t i;\n    size_t offset;\n\n    assert(no_of_bytes_to_return <= sizeof(temp));\n    assert(input_string_len + 5 <= sizeof(conj));\n\n    len = div_round_up(no_of_bytes_to_return, outlen);\n    for (i = 1; i <= len; ++i) {\n        offset = (i - 1) * outlen;\n        counter = (uint8_t)i;\n        conj[0] = counter;\n        store_be32((uint32_t)no_of_bytes_to_return * 8, conj + 1);\n        memcpy(conj + 5, input_string, input_string_len);\n        crypto_SHA1(conj, input_string_len + 5, temp + offset);\n    }\n\n    memcpy(output_string, temp, no_of_bytes_to_return);\n}\n\n/* assume personalization_string is zero length string */\nstatic void Hash_DRBG_Instantiate(Hash_DRBG_CTX *ctx,\n                                  uint8_t *entropy_input,\n                                  size_t entropy_input_len,\n                                  uint8_t *nonce,\n                                  size_t nonce_len)\n{\n    uint8_t seed_material[ENTROPY_MAX + NONCE_MAX];\n    uint8_t seed0[seedlen + 1];\n    uint8_t *seed = seed0 + 1;\n\n    assert(entropy_input_len <= ENTROPY_MAX);\n    assert(nonce_len <= NONCE_MAX);\n    assert(nonce != NULL || nonce_len == 0);\n\n    memcpy(seed_material, entropy_input, entropy_input_len);\n    if (nonce != NULL)\n        memcpy(seed_material + entropy_input_len, nonce, nonce_len);\n    Hash_df(seed_material, entropy_input_len + nonce_len, seed, seedlen);\n    seed0[0] = 0;\n\n    memcpy(ctx->V, seed, seedlen);\n    Hash_df(seed0, sizeof(seed0), ctx->C, seedlen);\n    ctx->reseed_counter = 1;\n}\n\n/* assume additional_input is zero length string */\nstatic void Hash_DRBG_Reseed(Hash_DRBG_CTX *ctx,\n                             uint8_t *entropy_input,\n                             size_t entropy_input_len)\n{\n    uint8_t seed_material[1 + seedlen + ENTROPY_MAX];\n    uint8_t seed0[seedlen + 1];\n    uint8_t *seed = seed0 + 1;\n\n    assert(entropy_input_len <= ENTROPY_MAX);\n\n    seed_material[0] = 1;\n    memcpy(seed_material + 1, ctx->V, seedlen);\n    memcpy(seed_material + 1 + seedlen, entropy_input, entropy_input_len);\n    Hash_df(seed_material, entropy_input_len + seedlen + 1, seed, seedlen);\n    seed0[0] = 0;\n\n    memcpy(ctx->V, seed, seedlen);\n    Hash_df(seed0, sizeof(seed0), ctx->C, seedlen);\n    ctx->reseed_counter = 1;\n}\n\nstatic void\nHashgen(uint8_t *V, uint8_t *output, size_t requested_number_of_bytes)\n{\n    uint8_t data[seedlen];\n    uint8_t W[GENERATE_MAX];\n    uint8_t i1 = 1;\n    size_t m;\n    size_t i;\n    size_t offset;\n\n    assert(requested_number_of_bytes <= sizeof(W));\n\n    m = div_round_up(requested_number_of_bytes, outlen);\n    memcpy(data, V, seedlen);\n    for (i = 1; i <= m; ++i) {\n        offset = (i - 1) * outlen;\n        crypto_SHA1(data, seedlen, W + offset);\n        /* increase data by 1 */\n        arr_add(data, sizeof(data), &i1, 1);\n    }\n\n    memcpy(output, W, requested_number_of_bytes);\n}\n\n/* assume additional_input is zero length string */\nstatic int Hash_DRBG_Generate(Hash_DRBG_CTX *ctx,\n                              uint8_t *output,\n                              size_t requested_number_of_bytes)\n{\n    uint8_t H[outlen];\n    uint8_t V3[seedlen + 1];\n    uint8_t reseed_counter[4];\n\n    if (ctx->reseed_counter > reseed_interval || ctx->reseed_counter == 0)\n        return RESEED_NEEDED;\n\n    Hashgen(ctx->V, output, requested_number_of_bytes);\n\n    V3[0] = 3;\n    memcpy(V3 + 1, ctx->V, seedlen);\n    crypto_SHA1(V3, sizeof(V3), H);\n    arr_add(ctx->V, sizeof(ctx->V), ctx->C, sizeof(ctx->C));\n    arr_add(ctx->V, sizeof(ctx->V), H, sizeof(H));\n    store_be32(ctx->reseed_counter, reseed_counter);\n    arr_add(ctx->V, sizeof(ctx->V), reseed_counter, sizeof(reseed_counter));\n\n    ++ctx->reseed_counter;\n    return 0;\n}\n\n#define ENTROPY_ACCUMULATE(ptr, last, type, arg)          \\\n    do {                                                  \\\n        type __arg = (type)(arg);                         \\\n        if ((char *)ptr + sizeof(__arg) < (char *)last) { \\\n            *(type *)ptr = __arg;                         \\\n            ptr = (void *)((char *)ptr + sizeof(__arg));  \\\n        }                                                 \\\n    } while (0)\n\nstatic void xmpp_rand_reseed(xmpp_rand_t *rand)\n{\n    uint8_t entropy[ENTROPY_MAX];\n    uint8_t *ptr = entropy;\n    const uint8_t *last = entropy + sizeof(entropy);\n    size_t len;\n\n    /* entropy:\n     *  1. time_stamp()\n     *  2. clock(3)\n     *  3. xmpp_rand_t address to make unique seed within one process\n     *  4. counter to make unique seed within one context\n     *  5. stack address\n     *  6. local ports of every connection in list (getsockname)\n     *  7. other non-constant info that can be retieved from socket\n     *\n     *  rand(3) can't be used as it isn't thread-safe.\n     *  XXX 6 and 7 are not implemented yet.\n     */\n\n    ENTROPY_ACCUMULATE(ptr, last, uint64_t, time_stamp());\n    ENTROPY_ACCUMULATE(ptr, last, clock_t, clock());\n    ENTROPY_ACCUMULATE(ptr, last, void *, rand);\n    ENTROPY_ACCUMULATE(ptr, last, unsigned, ++rand->reseed_count);\n    ENTROPY_ACCUMULATE(ptr, last, void *, &entropy);\n    len = ptr - entropy;\n\n    if (rand->inited) {\n        Hash_DRBG_Reseed(&rand->ctx, entropy, len);\n    } else {\n        Hash_DRBG_Instantiate(&rand->ctx, entropy, len, NULL, 0);\n        rand->inited = 1;\n    }\n}\n\nxmpp_rand_t *xmpp_rand_new(xmpp_ctx_t *ctx)\n{\n    xmpp_rand_t *out = strophe_alloc(ctx, sizeof(*out));\n    if (out != NULL) {\n        memset(out, 0, sizeof(*out));\n    }\n    return out;\n}\n\nvoid xmpp_rand_free(xmpp_ctx_t *ctx, xmpp_rand_t *rand)\n{\n    strophe_free(ctx, rand);\n}\n\nvoid xmpp_rand_bytes(xmpp_rand_t *rand, unsigned char *output, size_t len)\n{\n    int rc;\n    size_t gen, tot = 0;\n    while (tot < len) {\n        gen = len - tot;\n        if (gen > GENERATE_MAX)\n            gen = GENERATE_MAX;\n        rc = Hash_DRBG_Generate(&rand->ctx, (uint8_t *)output + tot, gen);\n        if (rc == RESEED_NEEDED) {\n            xmpp_rand_reseed(rand);\n            rc = Hash_DRBG_Generate(&rand->ctx, (uint8_t *)output + tot, gen);\n            assert(rc == 0);\n        }\n        tot += gen;\n    }\n}\n\n#else\n\nstatic int _read_getrandom(void *p, size_t n)\n{\n    unsigned char *q = (unsigned char *)p;\n    while (n > 0u) {\n        ssize_t ret = getrandom(q, n, 0);\n        if (ret < 0) {\n            if (errno == EINTR) {\n                continue;\n            }\n            return 1;\n        }\n        q += ret;\n        n -= (size_t)ret;\n    }\n    return 0;\n}\n\nstruct _xmpp_rand_t {\n    char nothing;\n};\n\nstatic xmpp_rand_t _xmpp_rand;\n\nxmpp_rand_t *xmpp_rand_new(xmpp_ctx_t *ctx)\n{\n    UNUSED(ctx);\n    return &_xmpp_rand;\n}\n\nvoid xmpp_rand_free(xmpp_ctx_t *ctx, xmpp_rand_t *rand)\n{\n    UNUSED(ctx);\n    assert(rand == &_xmpp_rand);\n}\n\nvoid xmpp_rand_bytes(xmpp_rand_t *rand, unsigned char *output, size_t len)\n{\n    assert(rand == &_xmpp_rand);\n    assert(_read_getrandom(output, len) == 0);\n}\n\n#endif\n\nint xmpp_rand(xmpp_rand_t *rand)\n{\n    int result;\n\n    xmpp_rand_bytes(rand, (unsigned char *)&result, sizeof(result));\n    return result;\n}\n\nstatic void rand_byte2hex(unsigned char byte, char *hex)\n{\n    static const char hex_tbl[16] = {'0', '1', '2', '3', '4', '5', '6', '7',\n                                     '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};\n\n    hex[0] = hex_tbl[(byte >> 4) & 0x0f];\n    hex[1] = hex_tbl[byte & 0x0f];\n}\n\nvoid xmpp_rand_nonce(xmpp_rand_t *rand, char *output, size_t len)\n{\n    size_t i;\n    const size_t rand_len = len / 2;\n\n    /*\n     * We don't want to use any allocation here, because this function\n     * can't fail. Also we want to avoid VLA.\n     * Current implementation uses half of the output buffer for random buffer\n     * generation and then converts it to HEX representation.\n     */\n\n    if (rand_len > 0) {\n        xmpp_rand_bytes(rand, (unsigned char *)output, rand_len);\n        for (i = rand_len; i > 0; --i)\n            rand_byte2hex(output[i - 1], &output[(i - 1) * 2]);\n    }\n    if (len > 0)\n        output[len - 1] = '\\0';\n}\n"
  },
  {
    "path": "src/resolver.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* resolver.c\n * strophe XMPP client library -- DNS resolver\n *\n * Copyright (C) 2015 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/** @file\n *  DNS resolver.\n */\n\n#if !defined(_WIN32) && !defined(HAVE_CARES)\n#include <netinet/in.h>\n#include <arpa/nameser.h>\n#include <resolv.h>\n#endif /* _WIN32 && HAVE_CARES */\n\n#ifdef HAVE_CARES\n#include <ares.h>\n/* for select(2) */\n#ifdef _WIN32\n#include <winsock2.h>\n#else /* _WIN32 */\n#include <sys/time.h>\n#include <sys/types.h>\n#include <unistd.h>\n#endif /* !_WIN32 */\n#endif /* HAVE_CARES */\n\n#include <string.h> /* strncpy */\n\n#include \"ostypes.h\"\n#include \"snprintf.h\"\n#include \"util.h\" /* xmpp_min */\n#include \"resolver.h\"\n\n#define MESSAGE_HEADER_LEN 12\n#define MESSAGE_RESPONSE 1\n#define MESSAGE_T_SRV 33\n#define MESSAGE_C_IN 1\n\n/*******************************************************************************\n * Forward declarations.\n ******************************************************************************/\n\n#ifdef HAVE_CARES\nstatic int resolver_ares_srv_lookup_buf(xmpp_ctx_t *ctx,\n                                        const unsigned char *buf,\n                                        size_t len,\n                                        resolver_srv_rr_t **srv_rr_list);\nstatic int resolver_ares_srv_lookup(xmpp_ctx_t *ctx,\n                                    const char *fulldomain,\n                                    resolver_srv_rr_t **srv_rr_list);\n#endif /* HAVE_CARES */\n\n#ifndef HAVE_CARES\nstatic int resolver_raw_srv_lookup_buf(xmpp_ctx_t *ctx,\n                                       const unsigned char *buf,\n                                       size_t len,\n                                       resolver_srv_rr_t **srv_rr_list);\n#endif /* !HAVE_CARES */\n\n#if defined(_WIN32) && !defined(HAVE_CARES)\nstatic int resolver_win32_srv_lookup(xmpp_ctx_t *ctx,\n                                     const char *fulldomain,\n                                     resolver_srv_rr_t **srv_rr_list);\nstatic int resolver_win32_srv_query(const char *fulldomain,\n                                    unsigned char *buf,\n                                    size_t len);\n#endif /* _WIN32 && !HAVE_CARES */\n\n/*******************************************************************************\n * Implementation.\n ******************************************************************************/\n\nvoid resolver_initialize(void)\n{\n#ifdef HAVE_CARES\n    ares_library_init(ARES_LIB_INIT_ALL);\n#endif\n}\n\nvoid resolver_shutdown(void)\n{\n#ifdef HAVE_CARES\n    ares_library_cleanup();\n#endif\n}\n\nresolver_srv_rr_t *resolver_srv_rr_new(xmpp_ctx_t *ctx,\n                                       const char *host,\n                                       unsigned short port,\n                                       unsigned short prio,\n                                       unsigned short weight)\n{\n    resolver_srv_rr_t *rr = strophe_alloc(ctx, sizeof(*rr));\n    if (rr) {\n        memset(rr, 0, sizeof(*rr));\n        rr->port = port;\n        rr->priority = prio;\n        rr->weight = weight;\n        if (host) {\n            snprintf(rr->target, sizeof(rr->target), \"%s\", host);\n        }\n    }\n    return rr;\n}\n\nstatic void resolver_srv_list_sort(resolver_srv_rr_t **srv_rr_list)\n{\n    resolver_srv_rr_t *rr_head;\n    resolver_srv_rr_t *rr_current;\n    resolver_srv_rr_t *rr_next;\n    resolver_srv_rr_t *rr_prev;\n    int swap;\n\n    rr_head = *srv_rr_list;\n\n    if ((rr_head == NULL) || (rr_head->next == NULL)) {\n        /* Empty or single record list */\n        return;\n    }\n\n    do {\n        rr_prev = NULL;\n        rr_current = rr_head;\n        rr_next = rr_head->next;\n        swap = 0;\n        while (rr_next != NULL) {\n            /*\n             * RFC2052: A client MUST attempt to contact the target host\n             * with the lowest-numbered priority it can reach.\n             * RFC2052: When selecting a target host among the\n             * those that have the same priority, the chance of trying\n             * this one first SHOULD be proportional to its weight.\n             */\n            if ((rr_current->priority > rr_next->priority) ||\n                (rr_current->priority == rr_next->priority &&\n                 rr_current->weight < rr_next->weight)) {\n                /* Swap node */\n                swap = 1;\n                if (rr_prev != NULL) {\n                    rr_prev->next = rr_next;\n                } else {\n                    /* Swap head node */\n                    rr_head = rr_next;\n                }\n                rr_current->next = rr_next->next;\n                rr_next->next = rr_current;\n\n                rr_prev = rr_next;\n                rr_next = rr_current->next;\n            } else {\n                /* Next node */\n                rr_prev = rr_current;\n                rr_current = rr_next;\n                rr_next = rr_next->next;\n            }\n        }\n    } while (swap != 0);\n\n    *srv_rr_list = rr_head;\n}\n\nint resolver_srv_lookup_buf(xmpp_ctx_t *ctx,\n                            const unsigned char *buf,\n                            size_t len,\n                            resolver_srv_rr_t **srv_rr_list)\n{\n    int set;\n\n#ifdef HAVE_CARES\n    set = resolver_ares_srv_lookup_buf(ctx, buf, len, srv_rr_list);\n#else\n    set = resolver_raw_srv_lookup_buf(ctx, buf, len, srv_rr_list);\n    if (set != XMPP_DOMAIN_FOUND && *srv_rr_list != NULL) {\n        resolver_srv_free(ctx, *srv_rr_list);\n        *srv_rr_list = NULL;\n    }\n#endif\n    resolver_srv_list_sort(srv_rr_list);\n\n    return set;\n}\n\nint resolver_srv_lookup(xmpp_ctx_t *ctx,\n                        const char *service,\n                        const char *proto,\n                        const char *domain,\n                        resolver_srv_rr_t **srv_rr_list)\n{\n#define RESOLVER_BUF_MAX 65536\n    unsigned char *buf;\n    char fulldomain[2048];\n    int len;\n    int set = XMPP_DOMAIN_NOT_FOUND;\n\n    (void)buf;\n    (void)len;\n\n    strophe_snprintf(fulldomain, sizeof(fulldomain), \"_%s._%s.%s\", service,\n                     proto, domain);\n\n    *srv_rr_list = NULL;\n\n#ifdef HAVE_CARES\n\n    set = resolver_ares_srv_lookup(ctx, fulldomain, srv_rr_list);\n\n#else /* HAVE_CARES */\n\n#ifdef _WIN32\n    set = resolver_win32_srv_lookup(ctx, fulldomain, srv_rr_list);\n    if (set == XMPP_DOMAIN_FOUND)\n        return set;\n#endif /* _WIN32 */\n\n    buf = strophe_alloc(ctx, RESOLVER_BUF_MAX);\n    if (buf == NULL)\n        return XMPP_DOMAIN_NOT_FOUND;\n\n#ifdef _WIN32\n    len = resolver_win32_srv_query(fulldomain, buf, RESOLVER_BUF_MAX);\n#else  /* _WIN32 */\n    len = res_query(fulldomain, MESSAGE_C_IN, MESSAGE_T_SRV, buf,\n                    RESOLVER_BUF_MAX);\n#endif /* _WIN32 */\n\n    if (len > 0)\n        set = resolver_srv_lookup_buf(ctx, buf, (size_t)len, srv_rr_list);\n\n    strophe_free(ctx, buf);\n\n#endif /* HAVE_CARES */\n\n    return set;\n}\n\nvoid resolver_srv_free(xmpp_ctx_t *ctx, resolver_srv_rr_t *srv_rr_list)\n{\n    resolver_srv_rr_t *rr;\n\n    while (srv_rr_list != NULL) {\n        rr = srv_rr_list->next;\n        strophe_free(ctx, srv_rr_list);\n        srv_rr_list = rr;\n    }\n}\n\n#ifndef HAVE_CARES\n/*******************************************************************************\n * Resolver raw implementation.\n *\n * This code is common for both unix and win32.\n ******************************************************************************/\n\nstruct message_header {\n    uint16_t id;\n    uint8_t octet2;\n    uint8_t octet3;\n    uint16_t qdcount;\n    uint16_t ancount;\n    uint16_t nscount;\n    uint16_t arcount;\n};\n\n/* the same as ntohs(), but receives pointer to the value */\nstatic uint16_t xmpp_ntohs_ptr(const void *ptr)\n{\n    const uint8_t *p = (const uint8_t *)ptr;\n\n    return (uint16_t)((p[0] << 8U) + p[1]);\n}\n\nstatic uint8_t message_header_qr(const struct message_header *header)\n{\n    return (header->octet2 >> 7) & 1;\n}\n\nstatic uint8_t message_header_rcode(const struct message_header *header)\n{\n    return header->octet3 & 0x0f;\n}\n\n/*\n * Append a label or a dot to the target name with buffer overflow checks.\n * Returns length of the non-truncated resulting string, may be bigger than\n * name_max.\n */\nstatic size_t message_name_append_safe(char *name,\n                                       size_t name_len,\n                                       size_t name_max,\n                                       const char *tail,\n                                       size_t tail_len)\n{\n    size_t copy_len;\n\n    copy_len = name_max > name_len ? name_max - name_len : 0;\n    copy_len = xmpp_min(tail_len, copy_len);\n    if (copy_len > 0)\n        memcpy(&name[name_len], tail, copy_len);\n\n    return name_len + tail_len;\n}\n\n/* Returns length of the compressed name. This is NOT the same as strlen(). */\nstatic unsigned message_name_get(const unsigned char *buf,\n                                 size_t buf_len,\n                                 unsigned buf_offset,\n                                 char *name,\n                                 size_t name_max)\n{\n    size_t name_len = 0;\n    unsigned i = buf_offset;\n    unsigned pointer;\n    unsigned rc;\n    unsigned char label_len;\n\n    while (1) {\n        if (i >= buf_len)\n            return 0;\n        label_len = buf[i++];\n        if (label_len == 0)\n            break;\n\n        /* Label */\n        if ((label_len & 0xc0) == 0) {\n            if (i + label_len - 1 >= buf_len)\n                return 0;\n            if (name != NULL) {\n                name_len = message_name_append_safe(name, name_len, name_max,\n                                                    (char *)&buf[i], label_len);\n                name_len =\n                    message_name_append_safe(name, name_len, name_max, \".\", 1);\n            }\n            i += label_len;\n\n            /* Pointer */\n        } else if ((label_len & 0xc0) == 0xc0) {\n            if (i >= buf_len)\n                return 0;\n            pointer = (label_len & 0x3f) << 8 | buf[i++];\n            /* Prevent infinite looping */\n            if (pointer >= buf_offset)\n                return 0;\n            if (name != NULL && name_len >= name_max && name_max > 0) {\n                /* We have filled the name buffer. Don't pass it recursively. */\n                name[name_max - 1] = '\\0';\n                name = NULL;\n                name_max = 0;\n            }\n            rc = message_name_get(\n                buf, buf_len, pointer, name != NULL ? &name[name_len] : NULL,\n                name_max > name_len ? name_max - name_len : 0);\n            if (rc == 0)\n                return 0;\n            /* Pointer is always the last. */\n            break;\n\n            /* The 10 and 01 combinations are reserved for future use. */\n        } else {\n            return 0;\n        }\n    }\n    if (label_len == 0) {\n        if (name_len == 0)\n            name_len = 1;\n        /*\n         * At this point name_len is length of the resulting name,\n         * including '\\0'. This value can be exported to allocate buffer\n         * of precise size.\n         */\n        if (name != NULL && name_max > 0) {\n            /*\n             * Overwrite leading '.' with a '\\0'. If the resulting name is\n             * bigger than name_max it is truncated.\n             */\n            name[xmpp_min(name_len, name_max) - 1] = '\\0';\n        }\n    }\n\n    return i - buf_offset;\n}\n\nstatic unsigned\nmessage_name_len(const unsigned char *buf, size_t buf_len, unsigned buf_offset)\n{\n    return message_name_get(buf, buf_len, buf_offset, NULL, SIZE_MAX);\n}\n\n#define BUF_OVERFLOW_CHECK(ptr, len)                  \\\n    do {                                              \\\n        if ((ptr) >= (len)) {                         \\\n            if (*srv_rr_list != NULL)                 \\\n                resolver_srv_free(ctx, *srv_rr_list); \\\n            *srv_rr_list = NULL;                      \\\n            return XMPP_DOMAIN_NOT_FOUND;             \\\n        }                                             \\\n    } while (0)\n\nstatic int resolver_raw_srv_lookup_buf(xmpp_ctx_t *ctx,\n                                       const unsigned char *buf,\n                                       size_t len,\n                                       resolver_srv_rr_t **srv_rr_list)\n{\n    unsigned i;\n    unsigned j;\n    unsigned name_len;\n    unsigned rdlength;\n    uint16_t type;\n    uint16_t class;\n    struct message_header header;\n    resolver_srv_rr_t *rr;\n\n    *srv_rr_list = NULL;\n\n    if (len < MESSAGE_HEADER_LEN)\n        return XMPP_DOMAIN_NOT_FOUND;\n\n    header.id = xmpp_ntohs_ptr(&buf[0]);\n    header.octet2 = buf[2];\n    header.octet3 = buf[3];\n    header.qdcount = xmpp_ntohs_ptr(&buf[4]);\n    header.ancount = xmpp_ntohs_ptr(&buf[6]);\n    header.nscount = xmpp_ntohs_ptr(&buf[8]);\n    header.arcount = xmpp_ntohs_ptr(&buf[10]);\n    if (message_header_qr(&header) != MESSAGE_RESPONSE ||\n        message_header_rcode(&header) != 0) {\n        return XMPP_DOMAIN_NOT_FOUND;\n    }\n    j = MESSAGE_HEADER_LEN;\n\n    /* skip question section */\n    for (i = 0; i < header.qdcount; ++i) {\n        BUF_OVERFLOW_CHECK(j, len);\n        name_len = message_name_len(buf, len, j);\n        /* error in name format */\n        if (name_len == 0)\n            return XMPP_DOMAIN_NOT_FOUND;\n        j += name_len + 4;\n    }\n\n    for (i = 0; i < header.ancount; ++i) {\n        BUF_OVERFLOW_CHECK(j, len);\n        name_len = message_name_len(buf, len, j);\n        /* error in name format */\n        if (name_len == 0)\n            return XMPP_DOMAIN_NOT_FOUND;\n        j += name_len;\n        BUF_OVERFLOW_CHECK(j + 16, len);\n        type = xmpp_ntohs_ptr(&buf[j]);\n        class = xmpp_ntohs_ptr(&buf[j + 2]);\n        rdlength = xmpp_ntohs_ptr(&buf[j + 8]);\n        j += 10;\n        if (type == MESSAGE_T_SRV && class == MESSAGE_C_IN) {\n            rr = resolver_srv_rr_new(ctx, NULL, 0, 0, 0);\n            if (rr) {\n                rr->next = *srv_rr_list;\n                rr->priority = xmpp_ntohs_ptr(&buf[j]);\n                rr->weight = xmpp_ntohs_ptr(&buf[j + 2]);\n                rr->port = xmpp_ntohs_ptr(&buf[j + 4]);\n                name_len = message_name_get(buf, len, j + 6, rr->target,\n                                            sizeof(rr->target));\n                if (name_len > 0)\n                    *srv_rr_list = rr;\n                else\n                    strophe_free(ctx, rr); /* skip broken record */\n            }\n        }\n        j += rdlength;\n    }\n\n    return *srv_rr_list != NULL ? XMPP_DOMAIN_FOUND : XMPP_DOMAIN_NOT_FOUND;\n}\n\n#endif /* !HAVE_CARES */\n\n#ifdef HAVE_CARES\n/*******************************************************************************\n * Resolver implementation using c-ares library.\n ******************************************************************************/\n\nstruct resolver_ares_ctx {\n    xmpp_ctx_t *ctx;\n    int result;\n    resolver_srv_rr_t *srv_rr_list;\n};\n\nstatic int resolver_ares_srv_lookup_buf(xmpp_ctx_t *ctx,\n                                        const unsigned char *buf,\n                                        size_t len,\n                                        resolver_srv_rr_t **srv_rr_list)\n{\n    struct ares_srv_reply *srv;\n    struct ares_srv_reply *item;\n    resolver_srv_rr_t *rr;\n    int rc;\n\n    *srv_rr_list = NULL;\n\n    rc = ares_parse_srv_reply(buf, len, &srv);\n    if (rc != ARES_SUCCESS)\n        return XMPP_DOMAIN_NOT_FOUND;\n\n    item = srv;\n    while (item != NULL) {\n        rr = strophe_alloc(ctx, sizeof(*rr));\n        if (rr == NULL)\n            break;\n        rr->next = *srv_rr_list;\n        rr->priority = item->priority;\n        rr->weight = item->weight;\n        rr->port = item->port;\n        strncpy(rr->target, item->host, sizeof(rr->target) - 1);\n        rr->target[sizeof(rr->target) - 1] = '\\0';\n        *srv_rr_list = rr;\n        item = item->next;\n    }\n    ares_free_data(srv);\n\n    return *srv_rr_list == NULL ? XMPP_DOMAIN_NOT_FOUND : XMPP_DOMAIN_FOUND;\n}\n\nstatic void ares_srv_lookup_callback(\n    void *arg, int status, int timeouts, unsigned char *buf, int len)\n{\n    struct resolver_ares_ctx *actx = arg;\n\n    (void)timeouts;\n\n    if (status != ARES_SUCCESS)\n        actx->result = XMPP_DOMAIN_NOT_FOUND;\n    else\n        actx->result = resolver_ares_srv_lookup_buf(actx->ctx, buf, len,\n                                                    &actx->srv_rr_list);\n}\n\nstatic int resolver_ares_srv_lookup(xmpp_ctx_t *ctx,\n                                    const char *fulldomain,\n                                    resolver_srv_rr_t **srv_rr_list)\n{\n    struct resolver_ares_ctx actx;\n    ares_channel chan;\n    struct timeval tv;\n    struct timeval *tvp;\n    fd_set rfds;\n    fd_set wfds;\n    int nfds;\n    int rc;\n\n    actx.ctx = ctx;\n    actx.result = XMPP_DOMAIN_NOT_FOUND;\n    actx.srv_rr_list = NULL;\n\n    rc = ares_init(&chan);\n    if (rc == ARES_SUCCESS) {\n        ares_query(chan, fulldomain, MESSAGE_C_IN, MESSAGE_T_SRV,\n                   ares_srv_lookup_callback, &actx);\n        while (1) {\n            FD_ZERO(&rfds);\n            FD_ZERO(&wfds);\n            nfds = ares_fds(chan, &rfds, &wfds);\n            if (nfds == 0)\n                break;\n            tvp = ares_timeout(chan, NULL, &tv);\n            select(nfds, &rfds, &wfds, NULL, tvp);\n            ares_process(chan, &rfds, &wfds);\n        }\n        ares_destroy(chan);\n    }\n\n    *srv_rr_list = actx.srv_rr_list;\n    return actx.result;\n}\n\n#endif /* HAVE_CARES */\n\n#if defined(_WIN32) && !defined(HAVE_CARES)\n/*******************************************************************************\n * Next part was copied from sock.c and contains old win32 code.\n *\n * The idea is to get raw response from a name server and pass it to\n * resolver_srv_lookup_buf(). In fact, resolver_win32_srv_query() replaces\n * the call of res_query().\n * Dnsapi code is moved to a separated function resolver_srv_win32_lookup() and\n * changed to meet new API.\n *\n * XXX If the code is compiled it should work like before.\n ******************************************************************************/\n\n#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <windns.h>\n#include <iphlpapi.h>\n\nstruct dnsquery_header {\n    unsigned short id;\n    unsigned char qr;\n    unsigned char opcode;\n    unsigned char aa;\n    unsigned char tc;\n    unsigned char rd;\n    unsigned char ra;\n    unsigned char z;\n    unsigned char rcode;\n    unsigned short qdcount;\n    unsigned short ancount;\n    unsigned short nscount;\n    unsigned short arcount;\n};\n\nstruct dnsquery_question {\n    char qname[1024];\n    unsigned short qtype;\n    unsigned short qclass;\n};\n\nstatic void netbuf_add_16bitnum(unsigned char *buf,\n                                int buflen,\n                                int *offset,\n                                unsigned short num)\n{\n    unsigned char *start = buf + *offset;\n    unsigned char *p = start;\n\n    /* assuming big endian */\n    *p++ = (num >> 8) & 0xff;\n    *p++ = (num) & 0xff;\n\n    *offset += 2;\n}\n\nstatic void\nnetbuf_add_domain_name(unsigned char *buf, int buflen, int *offset, char *name)\n{\n    unsigned char *start = buf + *offset;\n    unsigned char *p = start;\n    unsigned char *wordstart, *wordend;\n\n    wordstart = (unsigned char *)name;\n\n    while (*wordstart) {\n        int len;\n        wordend = wordstart;\n        while (*wordend && *wordend != '.') {\n            wordend++;\n        }\n\n        len = (int)(wordend - wordstart);\n\n        if (len > 0x3F) {\n            len = 0x3F;\n        }\n\n        *p++ = len;\n\n        while (wordstart != wordend) {\n            *p++ = *wordstart++;\n        }\n\n        if (*wordstart == '.') {\n            wordstart++;\n        }\n    }\n\n    *p++ = '\\0';\n\n    *offset += (int)(p - start);\n}\n\nstatic void netbuf_add_dnsquery_header(unsigned char *buf,\n                                       int buflen,\n                                       int *offset,\n                                       struct dnsquery_header *header)\n{\n    unsigned char *p;\n\n    netbuf_add_16bitnum(buf, buflen, offset, header->id);\n\n    p = buf + *offset;\n    *p++ = ((header->qr & 0x01) << 7) | ((header->opcode & 0x0F) << 3) |\n           ((header->aa & 0x01) << 2) | ((header->tc & 0x01) << 1) |\n           ((header->rd & 0x01));\n    *p++ = ((header->ra & 0x01) << 7) | ((header->z & 0x07) << 4) |\n           ((header->rcode & 0x0F));\n    *offset += 2;\n\n    netbuf_add_16bitnum(buf, buflen, offset, header->qdcount);\n    netbuf_add_16bitnum(buf, buflen, offset, header->ancount);\n    netbuf_add_16bitnum(buf, buflen, offset, header->nscount);\n    netbuf_add_16bitnum(buf, buflen, offset, header->arcount);\n}\n\nstatic void netbuf_add_dnsquery_question(unsigned char *buf,\n                                         int buflen,\n                                         int *offset,\n                                         struct dnsquery_question *question)\n{\n    netbuf_add_domain_name(buf, buflen, offset, question->qname);\n    netbuf_add_16bitnum(buf, buflen, offset, question->qtype);\n    netbuf_add_16bitnum(buf, buflen, offset, question->qclass);\n}\n\nstatic int resolver_win32_srv_lookup(xmpp_ctx_t *ctx,\n                                     const char *fulldomain,\n                                     resolver_srv_rr_t **srv_rr_list)\n{\n    resolver_srv_rr_t *rr;\n    HINSTANCE hdnsapi = NULL;\n\n    DNS_STATUS(WINAPI * pDnsQuery_A)\n    (PCSTR, WORD, DWORD, PIP4_ARRAY, DNS_RECORDA **, PVOID *);\n    void(WINAPI * pDnsRecordListFree)(DNS_RECORDA *, DNS_FREE_TYPE);\n\n    if (hdnsapi = LoadLibrary(\"dnsapi.dll\")) {\n        pDnsQuery_A = (void *)GetProcAddress(hdnsapi, \"DnsQuery_A\");\n        pDnsRecordListFree =\n            (void *)GetProcAddress(hdnsapi, \"DnsRecordListFree\");\n\n        if (pDnsQuery_A && pDnsRecordListFree) {\n            DNS_RECORDA *dnsrecords = NULL;\n            DNS_STATUS error;\n\n            error = pDnsQuery_A(fulldomain, DNS_TYPE_SRV, DNS_QUERY_STANDARD,\n                                NULL, &dnsrecords, NULL);\n\n            if (error == 0) {\n                DNS_RECORDA *current = dnsrecords;\n\n                while (current) {\n                    if (current->wType == DNS_TYPE_SRV) {\n                        rr = strophe_alloc(ctx, sizeof(*rr));\n                        if (rr == NULL)\n                            break;\n                        rr->next = *srv_rr_list;\n                        rr->port = current->Data.Srv.wPort;\n                        rr->priority = current->Data.Srv.wPriority;\n                        rr->weight = current->Data.Srv.wWeight;\n                        strophe_snprintf(rr->target, sizeof(rr->target), \"%s\",\n                                         current->Data.Srv.pNameTarget);\n                        *srv_rr_list = rr;\n                    }\n                    current = current->pNext;\n                }\n            }\n\n            pDnsRecordListFree(dnsrecords, DnsFreeRecordList);\n        }\n\n        FreeLibrary(hdnsapi);\n    }\n    resolver_srv_list_sort(srv_rr_list);\n\n    return *srv_rr_list != NULL ? XMPP_DOMAIN_FOUND : XMPP_DOMAIN_NOT_FOUND;\n}\n\nstatic int\nresolver_win32_srv_query(const char *fulldomain, unsigned char *buf, size_t len)\n{\n    int set = 0;\n    int insize = 0;\n\n    /* if dnsapi didn't work/isn't there, try querying the dns server manually\n     */\n    if (!set) {\n        struct dnsquery_header header;\n        struct dnsquery_question question;\n        int offset = 0;\n        int addrlen;\n        sock_t sock;\n        struct sockaddr_in dnsaddr;\n        char dnsserverips[16][256];\n        int numdnsservers = 0;\n        int j;\n\n        /* Try getting the DNS server ips from GetNetworkParams() in iphlpapi\n         * first */\n        if (!numdnsservers) {\n            HINSTANCE hiphlpapi = NULL;\n            DWORD(WINAPI * pGetNetworkParams)(PFIXED_INFO, PULONG);\n\n            if (hiphlpapi = LoadLibrary(\"Iphlpapi.dll\")) {\n                pGetNetworkParams =\n                    (void *)GetProcAddress(hiphlpapi, \"GetNetworkParams\");\n\n                if (pGetNetworkParams) {\n                    FIXED_INFO *fi;\n                    ULONG len;\n                    DWORD error;\n                    char buffer[65535];\n\n                    len = 65535;\n                    fi = (FIXED_INFO *)buffer;\n\n                    if ((error = pGetNetworkParams(fi, &len)) ==\n                        ERROR_SUCCESS) {\n                        IP_ADDR_STRING *pias = &(fi->DnsServerList);\n\n                        while (pias && numdnsservers < 16) {\n                            strcpy(dnsserverips[numdnsservers++],\n                                   pias->IpAddress.String);\n                            pias = pias->Next;\n                        }\n                    }\n                }\n            }\n            FreeLibrary(hiphlpapi);\n        }\n\n        /* Next, try getting the DNS server ips from the registry */\n        if (!numdnsservers) {\n            HKEY search;\n            LONG error;\n\n            error = RegOpenKeyEx(\n                HKEY_LOCAL_MACHINE,\n                \"SYSTEM\\\\CurrentControlSet\\\\Services\\\\Tcpip\\\\Parameters\", 0,\n                KEY_READ, &search);\n\n            if (error != ERROR_SUCCESS) {\n                error = RegOpenKeyEx(\n                    HKEY_LOCAL_MACHINE,\n                    \"SYSTEM\\\\CurrentControlSet\\\\Services\\\\VxD\\\\MSTCP\", 0,\n                    KEY_READ, &search);\n            }\n\n            if (error == ERROR_SUCCESS) {\n                char name[512];\n                DWORD len = 512;\n\n                error = RegQueryValueEx(search, \"NameServer\", NULL, NULL,\n                                        (LPBYTE)name, &len);\n\n                if (error != ERROR_SUCCESS) {\n                    error = RegQueryValueEx(search, \"DhcpNameServer\", NULL,\n                                            NULL, (LPBYTE)name, &len);\n                }\n\n                if (error == ERROR_SUCCESS) {\n                    char *parse = \"0123456789.\", *start, *end;\n                    start = name;\n                    end = name;\n                    name[len] = '\\0';\n\n                    while (*start && numdnsservers < 16) {\n                        while (strchr(parse, *end)) {\n                            end++;\n                        }\n\n                        strncpy(dnsserverips[numdnsservers++], start,\n                                end - start);\n\n                        while (*end && !strchr(parse, *end)) {\n                            end++;\n                        }\n\n                        start = end;\n                    }\n                }\n            }\n\n            RegCloseKey(search);\n        }\n\n        if (!numdnsservers) {\n            HKEY searchlist;\n            LONG error;\n\n            error = RegOpenKeyEx(HKEY_LOCAL_MACHINE,\n                                 \"SYSTEM\\\\CurrentControlSet\\\\Services\\\\Tcpip\\\\P\"\n                                 \"arameters\\\\Interfaces\",\n                                 0, KEY_READ, &searchlist);\n\n            if (error == ERROR_SUCCESS) {\n                unsigned int i;\n                DWORD numinterfaces = 0;\n\n                RegQueryInfoKey(searchlist, NULL, NULL, NULL, &numinterfaces,\n                                NULL, NULL, NULL, NULL, NULL, NULL, NULL);\n\n                for (i = 0; i < numinterfaces; i++) {\n                    char name[512];\n                    DWORD len = 512;\n                    HKEY searchentry;\n\n                    RegEnumKeyEx(searchlist, i, (LPTSTR)name, &len, NULL, NULL,\n                                 NULL, NULL);\n\n                    if (RegOpenKeyEx(searchlist, name, 0, KEY_READ,\n                                     &searchentry) == ERROR_SUCCESS) {\n                        if (RegQueryValueEx(searchentry, \"DhcpNameServer\", NULL,\n                                            NULL, (LPBYTE)name,\n                                            &len) == ERROR_SUCCESS) {\n                            char *parse = \"0123456789.\", *start, *end;\n                            start = name;\n                            end = name;\n                            name[len] = '\\0';\n\n                            while (*start && numdnsservers < 16) {\n                                while (strchr(parse, *end)) {\n                                    end++;\n                                }\n\n                                strncpy(dnsserverips[numdnsservers++], start,\n                                        end - start);\n\n                                while (*end && !strchr(parse, *end)) {\n                                    end++;\n                                }\n\n                                start = end;\n                            }\n                        } else if (RegQueryValueEx(searchentry, \"NameServer\",\n                                                   NULL, NULL, (LPBYTE)name,\n                                                   &len) == ERROR_SUCCESS) {\n                            char *parse = \"0123456789.\", *start, *end;\n                            start = name;\n                            end = name;\n                            name[len] = '\\0';\n\n                            while (*start && numdnsservers < 16) {\n                                while (strchr(parse, *end)) {\n                                    end++;\n                                }\n\n                                strncpy(dnsserverips[numdnsservers++], start,\n                                        end - start);\n\n                                while (*end && !strchr(parse, *end)) {\n                                    end++;\n                                }\n\n                                start = end;\n                            }\n                        }\n                        RegCloseKey(searchentry);\n                    }\n                }\n                RegCloseKey(searchlist);\n            }\n        }\n\n        /* If we have a DNS server, use it */\n        if (numdnsservers) {\n            ULONG nonblocking = 1;\n            int i;\n\n            memset(&header, 0, sizeof(header));\n            header.id = 12345; /* FIXME: Get a better id here */\n            header.rd = 1;\n            header.qdcount = 1;\n\n            netbuf_add_dnsquery_header(buf, (int)len, &offset, &header);\n\n            memset(&question, 0, sizeof(question));\n            strncpy(question.qname, fulldomain, 1024);\n            question.qtype = MESSAGE_T_SRV; /* SRV */\n            question.qclass = MESSAGE_C_IN; /* INTERNET! */\n\n            netbuf_add_dnsquery_question(buf, (int)len, &offset, &question);\n\n            insize = 0;\n            for (i = 0; i < numdnsservers && insize <= 0; i++) {\n                sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);\n                ioctlsocket(sock, FIONBIO, &nonblocking);\n\n                memset(&dnsaddr, 0, sizeof(dnsaddr));\n\n                dnsaddr.sin_family = AF_INET;\n                dnsaddr.sin_port = htons(53);\n                dnsaddr.sin_addr.s_addr = inet_addr(dnsserverips[i]);\n\n                addrlen = sizeof(dnsaddr);\n                sendto(sock, (char *)buf, offset, 0,\n                       (struct sockaddr *)&dnsaddr, addrlen);\n                for (j = 0; j < 50; j++) {\n                    insize = recvfrom(sock, (char *)buf, (int)len, 0,\n                                      (struct sockaddr *)&dnsaddr, &addrlen);\n                    if (insize == SOCKET_ERROR) {\n                        if (sock_error(NULL) == WSAEWOULDBLOCK) {\n                            Sleep(100);\n                        } else {\n                            break;\n                        }\n                    } else {\n                        break;\n                    }\n                }\n\n                closesocket(sock);\n            }\n            set = insize > 0;\n        }\n    }\n\n    return set ? insize : -1;\n}\n\n#endif /* _WIN32 && !HAVE_CARES */\n"
  },
  {
    "path": "src/resolver.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* resolver.h\n * strophe XMPP client library -- DNS resolver\n *\n * Copyright (C) 2015 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/** @file\n *  DNS resolver.\n */\n\n#ifndef __LIBSTROPHE_RESOLVER_H__\n#define __LIBSTROPHE_RESOLVER_H__\n\n#include \"ostypes.h\"\n#include \"common.h\"\n\ntypedef enum {\n    XMPP_DOMAIN_NOT_FOUND,\n    XMPP_DOMAIN_FOUND,\n    XMPP_DOMAIN_ALTDOMAIN\n} xmpp_domain_state_t;\n\ntypedef struct resolver_srv_rr_struc {\n    uint16_t priority;\n    uint16_t weight;\n    uint16_t port;\n    char target[MAX_DOMAIN_LEN];\n    struct resolver_srv_rr_struc *next;\n} resolver_srv_rr_t;\n\nvoid resolver_initialize(void);\nvoid resolver_shutdown(void);\n\nresolver_srv_rr_t *resolver_srv_rr_new(xmpp_ctx_t *ctx,\n                                       const char *host,\n                                       unsigned short port,\n                                       unsigned short prio,\n                                       unsigned short weight);\n\n/** Perform lookup for RFC1035 message format.\n *  This function allocates all elements.\n *\n *  @param ctx a Strophe context object\n *  @param buf message in RFC1035 format\n *  @param len length of the message\n *  @param srv_rr_list is the result\n *\n *  @return XMPP_DOMAIN_FOUND on success or XMPP_DOMAIN_NOT_FOUND on fail\n */\nint resolver_srv_lookup_buf(xmpp_ctx_t *ctx,\n                            const unsigned char *buf,\n                            size_t len,\n                            resolver_srv_rr_t **srv_rr_list);\n/** Resolve SRV record.\n *\n *  @param ctx a Strophe context object\n *  @param service service of the SRV record\n *  @param proto protocol of the SRV record\n *  @param domain resolving domain\n *  @param srv_rr_list is the result\n *\n *  @return XMPP_DOMAIN_FOUND on success or XMPP_DOMAIN_NOT_FOUND on fail\n */\nint resolver_srv_lookup(xmpp_ctx_t *ctx,\n                        const char *service,\n                        const char *proto,\n                        const char *domain,\n                        resolver_srv_rr_t **srv_rr_list);\n\n/** Release a list returned by resolver_srv_lookup() or\n *  resolver_srv_lookup_buf().\n *\n *  @param ctx a Strophe context object\n *  @param srv_rr_list a list allocated by lookup functions\n */\nvoid resolver_srv_free(xmpp_ctx_t *ctx, resolver_srv_rr_t *srv_rr_list);\n\n#endif /* __LIBSTROPHE_RESOLVER_H__ */\n"
  },
  {
    "path": "src/sasl.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* sasl.c\n** strophe XMPP client library -- SASL authentication helpers\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  SASL authentication.\n */\n\n#include <stdlib.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"ostypes.h\"\n#include \"sasl.h\"\n#include \"md5.h\"\n#include \"scram.h\"\n#include \"util.h\"\n\n/* strtok_s() has appeared in visual studio 2005.\n   Use own implementation for older versions. */\n#ifdef _MSC_VER\n#if (_MSC_VER >= 1400)\n#define strtok_r strtok_s\n#else\n#define strtok_r xmpp_strtok_r\n#endif\n#endif /* _MSC_VER */\n\n/** generate authentication string for the SASL PLAIN mechanism */\nchar *sasl_plain(xmpp_ctx_t *ctx, const char *authid, const char *password)\n{\n    size_t idlen, passlen;\n    size_t msglen;\n    char *result = NULL;\n    char *msg;\n\n    /* our message is Base64(authzid,\\0,authid,\\0,password)\n       if there is no authzid, that field is left empty */\n\n    idlen = strlen(authid);\n    passlen = strlen(password);\n    msglen = 2 + idlen + passlen;\n    msg = strophe_alloc(ctx, msglen);\n    if (msg != NULL) {\n        msg[0] = '\\0';\n        memcpy(msg + 1, authid, idlen);\n        msg[1 + idlen] = '\\0';\n        memcpy(msg + 1 + idlen + 1, password, passlen);\n        result = xmpp_base64_encode(ctx, (unsigned char *)msg, msglen);\n        strophe_free(ctx, msg);\n    }\n\n    return result;\n}\n\n/** helpers for digest auth */\n\n/* create a new, null-terminated string from a substring */\nstatic char *_make_string(xmpp_ctx_t *ctx, const char *s, unsigned len)\n{\n    char *result;\n\n    result = strophe_alloc(ctx, len + 1);\n    if (result != NULL) {\n        memcpy(result, s, len);\n        result[len] = '\\0';\n    }\n    return result;\n}\n\n/* create a new, null-terminated string quoting another string */\nstatic char *_make_quoted(xmpp_ctx_t *ctx, const char *s)\n{\n    char *result;\n    size_t len = strlen(s);\n\n    result = strophe_alloc(ctx, len + 3);\n    if (result != NULL) {\n        result[0] = '\"';\n        memcpy(result + 1, s, len);\n        result[len + 1] = '\"';\n        result[len + 2] = '\\0';\n    }\n    return result;\n}\n\n/* split key, value pairs into a hash */\nstatic hash_t *_parse_digest_challenge(xmpp_ctx_t *ctx, const char *msg)\n{\n    hash_t *result;\n    unsigned char *text;\n    char *key, *value;\n    unsigned char *s, *t;\n\n    text = (unsigned char *)xmpp_base64_decode_str(ctx, msg, strlen(msg));\n    if (text == NULL) {\n        strophe_error(ctx, \"SASL\", \"couldn't Base64 decode challenge!\");\n        return NULL;\n    }\n\n    result = hash_new(ctx, 10, strophe_free);\n    if (result != NULL) {\n        s = text;\n        while (*s != '\\0') {\n            /* skip any leading commas and spaces */\n            while ((*s == ',') || (*s == ' '))\n                s++;\n            /* accumulate a key ending at '=' */\n            t = s;\n            while ((*t != '=') && (*t != '\\0'))\n                t++;\n            if (*t == '\\0')\n                break; /* bad string */\n            key = _make_string(ctx, (char *)s, (t - s));\n            if (key == NULL)\n                break;\n            /* advance our start pointer past the key */\n            s = t + 1;\n            t = s;\n            /* if we see quotes, grab the string in between */\n            if ((*s == '\\'') || (*s == '\"')) {\n                t++;\n                while ((*t != *s) && (*t != '\\0'))\n                    t++;\n                value = _make_string(ctx, (char *)s + 1, (t - s - 1));\n                if (*t == *s) {\n                    s = t + 1;\n                } else {\n                    s = t;\n                }\n                /* otherwise, accumulate a value ending in ',' or '\\0' */\n            } else {\n                while ((*t != ',') && (*t != '\\0'))\n                    t++;\n                value = _make_string(ctx, (char *)s, (t - s));\n                s = t;\n            }\n            if (value == NULL) {\n                strophe_free(ctx, key);\n                break;\n            }\n            /* TODO: check for collisions per spec */\n            hash_add(result, key, value);\n            /* hash table now owns the value, free the key */\n            strophe_free(ctx, key);\n        }\n    }\n    strophe_free(ctx, text);\n\n    return result;\n}\n\n/** expand a 16 byte MD5 digest to a 32 byte hex representation */\nstatic void _digest_to_hex(const char *digest, char *hex)\n{\n    int i;\n    const char hexdigit[] = \"0123456789abcdef\";\n\n    for (i = 0; i < 16; i++) {\n        *hex++ = hexdigit[(digest[i] >> 4) & 0x0F];\n        *hex++ = hexdigit[digest[i] & 0x0F];\n    }\n}\n\n/** append 'key=\"value\"' to a buffer, growing as necessary */\nstatic char *\n_add_key(xmpp_ctx_t *ctx, hash_t *table, const char *key, char *buf, int quote)\n{\n    int olen, nlen;\n    int keylen, valuelen;\n    const char *value, *qvalue;\n    char *c;\n\n    /* allocate a zero-length string if necessary */\n    if (buf == NULL) {\n        buf = strophe_alloc(ctx, 1);\n        buf[0] = '\\0';\n    }\n    if (buf == NULL)\n        return NULL;\n\n    /* get current string length */\n    olen = strlen(buf);\n    value = hash_get(table, key);\n    if (value == NULL) {\n        strophe_error(ctx, \"SASL\", \"couldn't retrieve value for '%s'\", key);\n        value = \"\";\n    }\n    if (quote) {\n        qvalue = _make_quoted(ctx, value);\n    } else {\n        qvalue = value;\n    }\n    /* added length is key + '=' + value */\n    /*   (+ ',' if we're not the first entry   */\n    keylen = strlen(key);\n    valuelen = strlen(qvalue);\n    nlen = (olen ? 1 : 0) + keylen + 1 + valuelen + 1;\n    buf = strophe_realloc(ctx, buf, olen + nlen);\n\n    if (buf != NULL) {\n        c = buf + olen;\n        if (olen)\n            *c++ = ',';\n        memcpy(c, key, keylen);\n        c += keylen;\n        *c++ = '=';\n        memcpy(c, qvalue, valuelen);\n        c += valuelen;\n        *c++ = '\\0';\n    }\n\n    if (quote)\n        strophe_free(ctx, (char *)qvalue);\n\n    return buf;\n}\n\n/** generate auth response string for the SASL DIGEST-MD5 mechanism */\nchar *sasl_digest_md5(xmpp_ctx_t *ctx,\n                      const char *challenge,\n                      const char *jid,\n                      const char *password)\n{\n    hash_t *table;\n    char *result = NULL;\n    char *node, *domain, *realm;\n    char *value;\n    char *response;\n    struct MD5Context MD5;\n    unsigned char digest[16], HA1[16], HA2[16];\n    char hex[32];\n    char cnonce[13];\n\n    /* our digest response is\n    Hex( KD( HEX(MD5(A1)),\n      nonce ':' nc ':' cnonce ':' qop ':' HEX(MD5(A2))\n    ))\n\n       where KD(k, s) = MD5(k ':' s),\n    A1 = MD5( node ':' realm ':' password ) ':' nonce ':' cnonce\n    A2 = \"AUTHENTICATE\" ':' \"xmpp/\" domain\n\n       If there is an authzid it is ':'-appended to A1 */\n\n    /* parse the challenge */\n    table = _parse_digest_challenge(ctx, challenge);\n    if (table == NULL) {\n        strophe_error(ctx, \"SASL\", \"couldn't parse digest challenge\");\n        return NULL;\n    }\n\n    node = xmpp_jid_node(ctx, jid);\n    domain = xmpp_jid_domain(ctx, jid);\n\n    /* generate default realm of domain if one didn't come from the\n       server */\n    realm = hash_get(table, \"realm\");\n    if (realm == NULL || strlen(realm) == 0) {\n        hash_add(table, \"realm\", strophe_strdup(ctx, domain));\n        realm = hash_get(table, \"realm\");\n    }\n\n    /* add our response fields */\n    hash_add(table, \"username\", strophe_strdup(ctx, node));\n    xmpp_rand_nonce(ctx->rand, cnonce, sizeof(cnonce));\n    hash_add(table, \"cnonce\", strophe_strdup(ctx, cnonce));\n    hash_add(table, \"nc\", strophe_strdup(ctx, \"00000001\"));\n    if (hash_get(table, \"qop\") == NULL)\n        hash_add(table, \"qop\", strophe_strdup(ctx, \"auth\"));\n    value = strophe_alloc(ctx, 5 + strlen(domain) + 1);\n    memcpy(value, \"xmpp/\", 5);\n    memcpy(value + 5, domain, strlen(domain));\n    value[5 + strlen(domain)] = '\\0';\n    hash_add(table, \"digest-uri\", value);\n\n    /* generate response */\n\n    /* construct MD5(node : realm : password) */\n    MD5Init(&MD5);\n    MD5Update(&MD5, (unsigned char *)node, strlen(node));\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    MD5Update(&MD5, (unsigned char *)realm, strlen(realm));\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    MD5Update(&MD5, (unsigned char *)password, strlen(password));\n    MD5Final(digest, &MD5);\n\n    /* digest now contains the first field of A1 */\n\n    MD5Init(&MD5);\n    MD5Update(&MD5, digest, 16);\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    value = hash_get(table, \"nonce\");\n    MD5Update(&MD5, (unsigned char *)value, strlen(value));\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    value = hash_get(table, \"cnonce\");\n    MD5Update(&MD5, (unsigned char *)value, strlen(value));\n    MD5Final(digest, &MD5);\n\n    /* now digest is MD5(A1) */\n    memcpy(HA1, digest, 16);\n\n    /* construct MD5(A2) */\n    MD5Init(&MD5);\n    MD5Update(&MD5, (unsigned char *)\"AUTHENTICATE:\", 13);\n    value = hash_get(table, \"digest-uri\");\n    MD5Update(&MD5, (unsigned char *)value, strlen(value));\n    if (strcmp(hash_get(table, \"qop\"), \"auth\") != 0) {\n        MD5Update(&MD5, (unsigned char *)\":00000000000000000000000000000000\",\n                  33);\n    }\n    MD5Final(digest, &MD5);\n\n    memcpy(HA2, digest, 16);\n\n    /* construct response */\n    MD5Init(&MD5);\n    _digest_to_hex((char *)HA1, hex);\n    MD5Update(&MD5, (unsigned char *)hex, 32);\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    value = hash_get(table, \"nonce\");\n    MD5Update(&MD5, (unsigned char *)value, strlen(value));\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    value = hash_get(table, \"nc\");\n    MD5Update(&MD5, (unsigned char *)value, strlen(value));\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    value = hash_get(table, \"cnonce\");\n    MD5Update(&MD5, (unsigned char *)value, strlen(value));\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    value = hash_get(table, \"qop\");\n    MD5Update(&MD5, (unsigned char *)value, strlen(value));\n    MD5Update(&MD5, (unsigned char *)\":\", 1);\n    _digest_to_hex((char *)HA2, hex);\n    MD5Update(&MD5, (unsigned char *)hex, 32);\n    MD5Final(digest, &MD5);\n\n    response = strophe_alloc(ctx, 32 + 1);\n    _digest_to_hex((char *)digest, hex);\n    memcpy(response, hex, 32);\n    response[32] = '\\0';\n    hash_add(table, \"response\", response);\n\n    /* construct reply */\n    result = NULL;\n    result = _add_key(ctx, table, \"username\", result, 1);\n    result = _add_key(ctx, table, \"realm\", result, 1);\n    result = _add_key(ctx, table, \"nonce\", result, 1);\n    result = _add_key(ctx, table, \"cnonce\", result, 1);\n    result = _add_key(ctx, table, \"nc\", result, 0);\n    result = _add_key(ctx, table, \"qop\", result, 0);\n    result = _add_key(ctx, table, \"digest-uri\", result, 1);\n    result = _add_key(ctx, table, \"response\", result, 0);\n    result = _add_key(ctx, table, \"charset\", result, 0);\n\n    strophe_free(ctx, node);\n    strophe_free(ctx, domain);\n    hash_release(table); /* also frees value strings */\n\n    /* reuse response for the base64 encode of our result */\n    response = xmpp_base64_encode(ctx, (unsigned char *)result, strlen(result));\n    strophe_free(ctx, result);\n\n    return response;\n}\n\n/** generate auth response string for the SASL SCRAM mechanism */\nchar *sasl_scram(xmpp_ctx_t *ctx,\n                 const struct hash_alg *alg,\n                 const char *channel_binding,\n                 const char *challenge,\n                 const char *first_bare,\n                 const char *jid,\n                 const char *password)\n{\n    uint8_t key[SCRAM_DIGEST_SIZE];\n    uint8_t sign[SCRAM_DIGEST_SIZE];\n    char *r = NULL;\n    char *s = NULL;\n    char *i = NULL;\n    unsigned char *sval;\n    size_t sval_len;\n    long ival;\n    char *tmp;\n    char *ptr;\n    char *saveptr = NULL;\n    char *response;\n    char *auth;\n    char *response_b64;\n    char *sign_b64;\n    char *result = NULL;\n    size_t response_len;\n    size_t auth_len;\n    int l;\n\n    UNUSED(jid);\n\n    tmp = strophe_strdup(ctx, challenge);\n    if (!tmp) {\n        return NULL;\n    }\n\n    ptr = strtok_r(tmp, \",\", &saveptr);\n    while (ptr) {\n        if (strncmp(ptr, \"r=\", 2) == 0) {\n            r = ptr;\n        } else if (strncmp(ptr, \"s=\", 2) == 0) {\n            s = ptr + 2;\n        } else if (strncmp(ptr, \"i=\", 2) == 0) {\n            i = ptr + 2;\n        }\n        ptr = strtok_r(NULL, \",\", &saveptr);\n    }\n\n    if (!r || !s || !i) {\n        goto out;\n    }\n\n    xmpp_base64_decode_bin(ctx, s, strlen(s), &sval, &sval_len);\n    if (!sval) {\n        goto out;\n    }\n    ival = strtol(i, &saveptr, 10);\n\n    /* \"c=<channel_binding>,\" + r + \",p=\" + sign_b64 + '\\0' */\n    response_len = 3 + strlen(channel_binding) + strlen(r) + 3 +\n                   ((alg->digest_size + 2) / 3 * 4) + 1;\n    response = strophe_alloc(ctx, response_len);\n    if (!response) {\n        goto out_sval;\n    }\n\n    auth_len = 3 + response_len + strlen(first_bare) + strlen(challenge);\n    auth = strophe_alloc(ctx, auth_len);\n    if (!auth) {\n        goto out_response;\n    }\n\n    l = strophe_snprintf(response, response_len, \"c=%s,%s\", channel_binding, r);\n    if (l < 0 || (size_t)l >= response_len) {\n        goto out_auth;\n    }\n    l = strophe_snprintf(auth, auth_len, \"%s,%s,%s\", first_bare, challenge,\n                         response);\n    if (l < 0 || (size_t)l >= auth_len) {\n        goto out_auth;\n    }\n\n    SCRAM_ClientKey(alg, (uint8_t *)password, strlen(password), (uint8_t *)sval,\n                    sval_len, (uint32_t)ival, key);\n    SCRAM_ClientSignature(alg, key, (uint8_t *)auth, strlen(auth), sign);\n    SCRAM_ClientProof(alg, key, sign, sign);\n\n    sign_b64 = xmpp_base64_encode(ctx, sign, alg->digest_size);\n    if (!sign_b64) {\n        goto out_auth;\n    }\n\n    /* Check for buffer overflow */\n    if (strlen(response) + strlen(sign_b64) + 3 + 1 > response_len) {\n        strophe_free(ctx, sign_b64);\n        goto out_auth;\n    }\n    strcat(response, \",p=\");\n    strcat(response, sign_b64);\n    strophe_free(ctx, sign_b64);\n\n    response_b64 =\n        xmpp_base64_encode(ctx, (unsigned char *)response, strlen(response));\n    if (!response_b64) {\n        goto out_auth;\n    }\n    result = response_b64;\n\nout_auth:\n    strophe_free(ctx, auth);\nout_response:\n    strophe_free(ctx, response);\nout_sval:\n    strophe_free(ctx, sval);\nout:\n    strophe_free(ctx, tmp);\n    return result;\n}\n"
  },
  {
    "path": "src/sasl.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* sasl.h\n** strophe XMPP client library -- SASL authentication helpers\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n * SASL authentication helpers.\n */\n\n#ifndef __LIBSTROPHE_SASL_H__\n#define __LIBSTROPHE_SASL_H__\n\n#include \"strophe.h\"\n#include \"scram.h\"\n\n/** low-level sasl routines */\n\nchar *sasl_plain(xmpp_ctx_t *ctx, const char *authid, const char *password);\nchar *sasl_digest_md5(xmpp_ctx_t *ctx,\n                      const char *challenge,\n                      const char *jid,\n                      const char *password);\nchar *sasl_scram(xmpp_ctx_t *ctx,\n                 const struct hash_alg *alg,\n                 const char *channel_binding,\n                 const char *challenge,\n                 const char *first_bare,\n                 const char *jid,\n                 const char *password);\n\n#endif /* _LIBXMPP_SASL_H__ */\n"
  },
  {
    "path": "src/scram.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* scram.c\n * strophe XMPP client library\n *\n * SCRAM-SHA1 helper functions according to RFC5802\n * HMAC-SHA1 implementation according to RFC2104\n *\n * Copyright (C) 2013 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/** @file\n *  SCRAM-SHA1 helper functions.\n */\n\n#include <assert.h>\n#include <string.h>\n\n#include \"common.h\"\n#include \"sha1.h\"\n#include \"sha256.h\"\n#include \"sha512.h\"\n#include \"ostypes.h\"\n\n#include \"scram.h\"\n\n#define HMAC_BLOCK_SIZE_MAX 128\n\nstatic const uint8_t ipad = 0x36;\nstatic const uint8_t opad = 0x5C;\n\nconst struct hash_alg scram_sha1 = {\n    \"SCRAM-SHA-1\",\n    SASL_MASK_SCRAMSHA1,\n    SHA1_DIGEST_SIZE,\n    (void (*)(const uint8_t *, size_t, uint8_t *))crypto_SHA1,\n    (void (*)(void *))crypto_SHA1_Init,\n    (void (*)(void *, const uint8_t *, size_t))crypto_SHA1_Update,\n    (void (*)(void *, uint8_t *))crypto_SHA1_Final};\n\nconst struct hash_alg scram_sha1_plus = {\n    \"SCRAM-SHA-1-PLUS\",\n    SASL_MASK_SCRAMSHA1_PLUS,\n    SHA1_DIGEST_SIZE,\n    (void (*)(const uint8_t *, size_t, uint8_t *))crypto_SHA1,\n    (void (*)(void *))crypto_SHA1_Init,\n    (void (*)(void *, const uint8_t *, size_t))crypto_SHA1_Update,\n    (void (*)(void *, uint8_t *))crypto_SHA1_Final};\n\nconst struct hash_alg scram_sha256 = {\n    \"SCRAM-SHA-256\",\n    SASL_MASK_SCRAMSHA256,\n    SHA256_DIGEST_SIZE,\n    (void (*)(const uint8_t *, size_t, uint8_t *))sha256_hash,\n    (void (*)(void *))sha256_init,\n    (void (*)(void *, const uint8_t *, size_t))sha256_process,\n    (void (*)(void *, uint8_t *))sha256_done};\n\nconst struct hash_alg scram_sha256_plus = {\n    \"SCRAM-SHA-256-PLUS\",\n    SASL_MASK_SCRAMSHA256_PLUS,\n    SHA256_DIGEST_SIZE,\n    (void (*)(const uint8_t *, size_t, uint8_t *))sha256_hash,\n    (void (*)(void *))sha256_init,\n    (void (*)(void *, const uint8_t *, size_t))sha256_process,\n    (void (*)(void *, uint8_t *))sha256_done};\n\nconst struct hash_alg scram_sha512 = {\n    \"SCRAM-SHA-512\",\n    SASL_MASK_SCRAMSHA512,\n    SHA512_DIGEST_SIZE,\n    (void (*)(const uint8_t *, size_t, uint8_t *))sha512_hash,\n    (void (*)(void *))sha512_init,\n    (void (*)(void *, const uint8_t *, size_t))sha512_process,\n    (void (*)(void *, uint8_t *))sha512_done};\n\nconst struct hash_alg scram_sha512_plus = {\n    \"SCRAM-SHA-512-PLUS\",\n    SASL_MASK_SCRAMSHA512_PLUS,\n    SHA512_DIGEST_SIZE,\n    (void (*)(const uint8_t *, size_t, uint8_t *))sha512_hash,\n    (void (*)(void *))sha512_init,\n    (void (*)(void *, const uint8_t *, size_t))sha512_process,\n    (void (*)(void *, uint8_t *))sha512_done};\n\n/* The order of this list defines the order in which the SCRAM algorithms are\n * tried if the server supports them.\n * Their order is derived from\n * https://datatracker.ietf.org/doc/html/draft-ietf-kitten-password-storage\n */\nconst struct hash_alg *scram_algs[] = {\n    /* *1 */\n    &scram_sha512_plus,\n    /* *1 */\n    &scram_sha256_plus,\n    /* *1 */\n    &scram_sha1_plus,\n    /* *1 */\n    &scram_sha512,\n    /* *1 */\n    &scram_sha256,\n    /* *1 */\n    &scram_sha1,\n};\n/* *1 - I want to use clang-format here, but by default it will put multiple\n * elements per line if there's no comment. Currently clang-format also doesn't\n * have an option to enforce it to behave like that, besides by putting comments\n * between each element (or I couldn't find a way to do it). In order to prevent\n * clang-format from re-formatting the array I added the comments above and\n * wrote this lengthy description.\n */\nconst size_t scram_algs_num = sizeof(scram_algs) / sizeof(scram_algs[0]);\n\nunion common_hash_ctx {\n    SHA1_CTX sha1;\n    sha256_context sha256;\n    sha512_context sha512;\n};\n\nstatic void crypto_HMAC(const struct hash_alg *alg,\n                        const uint8_t *key,\n                        size_t key_len,\n                        const uint8_t *text,\n                        size_t len,\n                        uint8_t *digest)\n{\n    uint8_t key_pad[HMAC_BLOCK_SIZE_MAX];\n    uint8_t key_ipad[HMAC_BLOCK_SIZE_MAX];\n    uint8_t key_opad[HMAC_BLOCK_SIZE_MAX];\n    uint8_t sha_digest[SCRAM_DIGEST_SIZE];\n    size_t blocksize;\n    size_t i;\n    union common_hash_ctx ctx;\n\n    assert(alg->digest_size <= HMAC_BLOCK_SIZE_MAX);\n    blocksize = alg->digest_size < 48 ? 64 : 128;\n\n    memset(key_pad, 0, blocksize);\n    if (key_len <= blocksize) {\n        memcpy(key_pad, key, key_len);\n    } else {\n        /* according to RFC2104 */\n        alg->hash(key, key_len, key_pad);\n    }\n\n    for (i = 0; i < blocksize; i++) {\n        key_ipad[i] = key_pad[i] ^ ipad;\n        key_opad[i] = key_pad[i] ^ opad;\n    }\n\n    alg->init((void *)&ctx);\n    alg->update((void *)&ctx, key_ipad, blocksize);\n    alg->update((void *)&ctx, text, len);\n    alg->final((void *)&ctx, sha_digest);\n\n    alg->init((void *)&ctx);\n    alg->update((void *)&ctx, key_opad, blocksize);\n    alg->update((void *)&ctx, sha_digest, alg->digest_size);\n    alg->final((void *)&ctx, digest);\n}\n\nstatic void SCRAM_Hi(const struct hash_alg *alg,\n                     const uint8_t *text,\n                     size_t len,\n                     const uint8_t *salt,\n                     size_t salt_len,\n                     uint32_t i,\n                     uint8_t *digest)\n{\n    size_t k;\n    uint32_t j;\n    uint8_t tmp[128];\n\n    static uint8_t int1[] = {0x0, 0x0, 0x0, 0x1};\n\n    /* assume salt + INT(1) isn't longer than sizeof(tmp) */\n    assert(salt_len <= sizeof(tmp) - sizeof(int1));\n\n    memset(digest, 0, alg->digest_size);\n    if (i == 0) {\n        return;\n    }\n\n    memcpy(tmp, salt, salt_len);\n    memcpy(&tmp[salt_len], int1, sizeof(int1));\n\n    /* 'text' for Hi is a 'key' for HMAC */\n    crypto_HMAC(alg, text, len, tmp, salt_len + sizeof(int1), digest);\n    memcpy(tmp, digest, alg->digest_size);\n\n    for (j = 1; j < i; j++) {\n        crypto_HMAC(alg, text, len, tmp, alg->digest_size, tmp);\n        for (k = 0; k < alg->digest_size; k++) {\n            digest[k] ^= tmp[k];\n        }\n    }\n}\n\nvoid SCRAM_ClientKey(const struct hash_alg *alg,\n                     const uint8_t *password,\n                     size_t len,\n                     const uint8_t *salt,\n                     size_t salt_len,\n                     uint32_t i,\n                     uint8_t *key)\n{\n    uint8_t salted[SCRAM_DIGEST_SIZE];\n\n    /* XXX: Normalize(password) is omitted */\n\n    SCRAM_Hi(alg, password, len, salt, salt_len, i, salted);\n    crypto_HMAC(alg, salted, alg->digest_size, (uint8_t *)\"Client Key\",\n                strlen(\"Client Key\"), key);\n}\n\nvoid SCRAM_ClientSignature(const struct hash_alg *alg,\n                           const uint8_t *ClientKey,\n                           const uint8_t *AuthMessage,\n                           size_t len,\n                           uint8_t *sign)\n{\n    uint8_t stored[SCRAM_DIGEST_SIZE];\n\n    alg->hash(ClientKey, alg->digest_size, stored);\n    crypto_HMAC(alg, stored, alg->digest_size, AuthMessage, len, sign);\n}\n\nvoid SCRAM_ClientProof(const struct hash_alg *alg,\n                       const uint8_t *ClientKey,\n                       const uint8_t *ClientSignature,\n                       uint8_t *proof)\n{\n    size_t i;\n    for (i = 0; i < alg->digest_size; i++) {\n        proof[i] = ClientKey[i] ^ ClientSignature[i];\n    }\n}\n"
  },
  {
    "path": "src/scram.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* scram.h\n * strophe XMPP client library -- SCRAM helper functions\n *\n * Copyright (C) 2013 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/** @file\n *  SCRAM helper functions.\n */\n\n#ifndef __LIBSTROPHE_SCRAM_H__\n#define __LIBSTROPHE_SCRAM_H__\n\n/* make sure the stdint.h types are available */\n#include \"ostypes.h\"\n\n/* Maximum possible digest size. Used for buffers allocation. */\n#include \"sha512.h\"\n#define SCRAM_DIGEST_SIZE SHA512_DIGEST_SIZE\n\nstruct hash_alg {\n    const char *scram_name;\n    int mask;\n    size_t digest_size;\n    void (*hash)(const uint8_t *, size_t, uint8_t *);\n    void (*init)(void *);\n    void (*update)(void *, const uint8_t *, size_t);\n    void (*final)(void *, uint8_t *);\n};\n\nextern const struct hash_alg *scram_algs[];\nextern const size_t scram_algs_num;\n\nvoid SCRAM_ClientKey(const struct hash_alg *alg,\n                     const uint8_t *password,\n                     size_t len,\n                     const uint8_t *salt,\n                     size_t salt_len,\n                     uint32_t i,\n                     uint8_t *key);\n\nvoid SCRAM_ClientSignature(const struct hash_alg *alg,\n                           const uint8_t *ClientKey,\n                           const uint8_t *AuthMessage,\n                           size_t len,\n                           uint8_t *sign);\n\nvoid SCRAM_ClientProof(const struct hash_alg *alg,\n                       const uint8_t *ClientKey,\n                       const uint8_t *ClientSignature,\n                       uint8_t *proof);\n\n#endif /* __LIBSTROPHE_SCRAM_H__ */\n"
  },
  {
    "path": "src/sha.h",
    "content": "/* public api for steve reid's public domain SHA-1 implementation */\n/* this file is in the public domain */\n\n/** @file\n *  SHA-1 hash API.\n */\n\n#ifndef __LIBSTROPHE_SHA_H__\n#define __LIBSTROPHE_SHA_H__\n\n#include <string.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* make sure the stdint.h types are available */\n#include \"ostypes.h\"\n\n#if defined(__BIG_ENDIAN__) ||                                   \\\n    (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \\\n     __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)\n\n#define STORE32H(x, y)      \\\n    do {                    \\\n        uint32_t __t = (x); \\\n        memcpy(y, &__t, 4); \\\n    } while (0)\n\n#define LOAD32H(x, y)       \\\n    do {                    \\\n        memcpy(&(x), y, 4); \\\n        x &= 0xFFFFFFFF;    \\\n    } while (0)\n\n#define STORE64H(x, y)      \\\n    do {                    \\\n        uint64_t __t = (x); \\\n        memcpy(y, &__t, 8); \\\n    } while (0)\n\n#define LOAD64H(x, y)       \\\n    do {                    \\\n        memcpy(&(x), y, 8); \\\n    } while (0)\n\n#elif defined(__LITTLE_ENDIAN__) ||                                 \\\n    (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \\\n     __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)\n\n#define STORE32H(x, y)                         \\\n    do {                                       \\\n        (y)[0] = (uint8_t)(((x) >> 24) & 255); \\\n        (y)[1] = (uint8_t)(((x) >> 16) & 255); \\\n        (y)[2] = (uint8_t)(((x) >> 8) & 255);  \\\n        (y)[3] = (uint8_t)((x) & 255);         \\\n    } while (0)\n\n#define LOAD32H(x, y)                                                     \\\n    do {                                                                  \\\n        x = ((uint32_t)((y)[0] & 255) << 24) |                            \\\n            ((uint32_t)((y)[1] & 255) << 16) |                            \\\n            ((uint32_t)((y)[2] & 255) << 8) | ((uint32_t)((y)[3] & 255)); \\\n    } while (0)\n\n#define STORE64H(x, y)                         \\\n    do {                                       \\\n        (y)[0] = (uint8_t)(((x) >> 56) & 255); \\\n        (y)[1] = (uint8_t)(((x) >> 48) & 255); \\\n        (y)[2] = (uint8_t)(((x) >> 40) & 255); \\\n        (y)[3] = (uint8_t)(((x) >> 32) & 255); \\\n        (y)[4] = (uint8_t)(((x) >> 24) & 255); \\\n        (y)[5] = (uint8_t)(((x) >> 16) & 255); \\\n        (y)[6] = (uint8_t)(((x) >> 8) & 255);  \\\n        (y)[7] = (uint8_t)((x) & 255);         \\\n    } while (0)\n\n#define LOAD64H(x, y)                                                         \\\n    do {                                                                      \\\n        x = (((uint64_t)((y)[0] & 255)) << 56) |                              \\\n            (((uint64_t)((y)[1] & 255)) << 48) |                              \\\n            (((uint64_t)((y)[2] & 255)) << 40) |                              \\\n            (((uint64_t)((y)[3] & 255)) << 32) |                              \\\n            (((uint64_t)((y)[4] & 255)) << 24) |                              \\\n            (((uint64_t)((y)[5] & 255)) << 16) |                              \\\n            (((uint64_t)((y)[6] & 255)) << 8) | (((uint64_t)((y)[7] & 255))); \\\n    } while (0)\n\n#else\n#error Unknown endianness not supported\n#endif\n\n#ifdef _MSC_VER\n#define CONST64(n) n##ui64\n#else\n#define CONST64(n) n##ULL\n#endif\n\n#define RORc(x, y)                                               \\\n    (((((uint32_t)(x) & 0xFFFFFFFFUL) >> (uint32_t)((y) & 31)) | \\\n      ((uint32_t)(x) << (uint32_t)((32 - ((y) & 31)) & 31))) &   \\\n     0xFFFFFFFFUL)\n#define ROR64c(x, y)                                                           \\\n    (((((x) & CONST64(0xFFFFFFFFFFFFFFFF)) >> ((uint64_t)(y) & CONST64(63))) | \\\n      ((x) << (((uint64_t)64 - ((y) & 63)) & 63))) &                           \\\n     CONST64(0xFFFFFFFFFFFFFFFF))\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __LIBSTROPHE_SHA_H__ */\n"
  },
  {
    "path": "src/sha1.c",
    "content": "/** @file\n *  SHA-1 hash.\n */\n\n/*\nSHA-1 in C\nBy Steve Reid <sreid@sea-to-sky.net>\n100% Public Domain\n\n-----------------\nModified 7/98\nBy James H. Brown <jbrown@burgoyne.com>\nStill 100% Public Domain\n\nCorrected a problem which generated improper hash values on 16 bit machines\nRoutine SHA1Update changed from\n    void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned int\nlen)\nto\n    void SHA1Update(SHA1_CTX* context, unsigned char* data, unsigned\nlong len)\n\nThe 'len' parameter was declared an int which works fine on 32 bit machines.\nHowever, on 16 bit machines an int is too small for the shifts being done\nagainst\nit.  This caused the hash function to generate incorrect values if len was\ngreater than 8191 (8K - 1) due to the 'len << 3' on line 3 of SHA1Update().\n\nSince the file IO in main() reads 16K at a time, any file 8K or larger would\nbe guaranteed to generate the wrong hash (e.g. Test Vector #3, a million\n\"a\"s).\n\nI also changed the declaration of variables i & j in SHA1Update to\nunsigned long from unsigned int for the same reason.\n\nThese changes should make no difference to any 32 bit implementations since\nan\nint and a long are the same size in those environments.\n\n--\nI also corrected a few compiler warnings generated by Borland C.\n1. Added #include <process.h> for exit() prototype\n2. Removed unused variable 'j' in SHA1Final\n3. Changed exit(0) to return(0) at end of main.\n\nALL changes I made can be located by searching for comments containing 'JHB'\n-----------------\nModified 8/98\nBy Steve Reid <sreid@sea-to-sky.net>\nStill 100% public domain\n\n1- Removed #include <process.h> and used return() instead of exit()\n2- Fixed overwriting of finalcount in SHA1Final() (discovered by Chris Hall)\n3- Changed email address from steve@edmweb.com to sreid@sea-to-sky.net\n\n-----------------\nModified 4/01\nBy Saul Kravitz <Saul.Kravitz@celera.com>\nStill 100% PD\nModified to run on Compaq Alpha hardware.\n\n-----------------\nModified 07/2002\nBy Ralph Giles <giles@artofcode.com>\nStill 100% public domain\nmodified for use with stdint types, autoconf\ncode cleanup, removed attribution comments\nswitched SHA1Final() argument order for consistency\nuse SHA1_ prefix for public api\nmove public api to sha1.h\n*/\n\n#include <string.h>\n\n#include \"ostypes.h\"\n#include \"sha1.h\"\n\nstatic uint32_t host_to_be(uint32_t i);\nstatic void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64]);\n\n#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))\n\n/* blk0() and blk() perform the initial expand. */\n/* I got the idea of expanding during the round function from SSLeay */\n#define blk0(i) (block->l[i] = host_to_be(block->l[i]))\n#define blk(i)                                                                 \\\n    (block->l[i & 15] = rol(block->l[(i + 13) & 15] ^ block->l[(i + 8) & 15] ^ \\\n                                block->l[(i + 2) & 15] ^ block->l[i & 15],     \\\n                            1))\n\n/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */\n#define R0(v, w, x, y, z, i)                                     \\\n    z += ((w & (x ^ y)) ^ y) + blk0(i) + 0x5A827999 + rol(v, 5); \\\n    w = rol(w, 30);\n#define R1(v, w, x, y, z, i)                                    \\\n    z += ((w & (x ^ y)) ^ y) + blk(i) + 0x5A827999 + rol(v, 5); \\\n    w = rol(w, 30);\n#define R2(v, w, x, y, z, i)                            \\\n    z += (w ^ x ^ y) + blk(i) + 0x6ED9EBA1 + rol(v, 5); \\\n    w = rol(w, 30);\n#define R3(v, w, x, y, z, i)                                          \\\n    z += (((w | x) & y) | (w & x)) + blk(i) + 0x8F1BBCDC + rol(v, 5); \\\n    w = rol(w, 30);\n#define R4(v, w, x, y, z, i)                            \\\n    z += (w ^ x ^ y) + blk(i) + 0xCA62C1D6 + rol(v, 5); \\\n    w = rol(w, 30);\n\nstatic uint32_t host_to_be(uint32_t i)\n{\n#define le_to_be(i) ((rol((i), 24) & 0xFF00FF00) | (rol((i), 8) & 0x00FF00FF))\n#if defined(__BIG_ENDIAN__) ||                                   \\\n    (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \\\n     __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)\n    return i;\n#elif defined(__LITTLE_ENDIAN__) ||                                 \\\n    (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \\\n     __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)\n    return le_to_be(i);\n#else /* fallback to run-time check */\n    static const union {\n        uint32_t u;\n        unsigned char c;\n    } check = {1};\n    return check.c ? le_to_be(i) : i;\n#endif\n#undef le_to_be\n}\n\nstatic void *(*volatile SHA1_explicit_memset)(void *, int, size_t) = &memset;\n\nstatic void SHA1_cleanse(void *p, size_t len)\n{\n    SHA1_explicit_memset(p, 0, len);\n}\n\n/* Hash a single 512-bit block. This is the core of the algorithm. */\nstatic void SHA1_Transform(uint32_t state[5], const uint8_t buffer[64])\n{\n    uint32_t a, b, c, d, e;\n    typedef union {\n        uint8_t c[64];\n        uint32_t l[16];\n    } CHAR64LONG16;\n    CHAR64LONG16 *block;\n\n    static uint8_t workspace[64];\n    block = (CHAR64LONG16 *)workspace;\n    memcpy(block, buffer, 64);\n\n    /* Copy context->state[] to working vars */\n    a = state[0];\n    b = state[1];\n    c = state[2];\n    d = state[3];\n    e = state[4];\n\n    /* 4 rounds of 20 operations each. Loop unrolled. */\n    /* clang-format off */\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    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);\n    /* clang-format on */\n\n    /* Add the working vars back into context.state[] */\n    state[0] += a;\n    state[1] += b;\n    state[2] += c;\n    state[3] += d;\n    state[4] += e;\n\n    /* Wipe variables */\n    SHA1_cleanse(&a, sizeof(a));\n    SHA1_cleanse(&b, sizeof(b));\n    SHA1_cleanse(&c, sizeof(c));\n    SHA1_cleanse(&d, sizeof(d));\n    SHA1_cleanse(&e, sizeof(e));\n}\n\n/* SHA1Init - Initialize new context */\nvoid crypto_SHA1_Init(SHA1_CTX *context)\n{\n    /* SHA1 initialization constants */\n    context->state[0] = 0x67452301;\n    context->state[1] = 0xEFCDAB89;\n    context->state[2] = 0x98BADCFE;\n    context->state[3] = 0x10325476;\n    context->state[4] = 0xC3D2E1F0;\n    context->count[0] = context->count[1] = 0;\n}\n\n/* Run your data through this. */\nvoid crypto_SHA1_Update(SHA1_CTX *context, const uint8_t *data, size_t len)\n{\n    size_t i, j;\n\n    j = (context->count[0] >> 3) & 63;\n    if ((context->count[0] += (uint32_t)len << 3) < ((uint32_t)len << 3))\n        context->count[1]++;\n    context->count[1] += (uint32_t)(len >> 29);\n    if ((j + len) > 63) {\n        memcpy(&context->buffer[j], data, (i = 64 - j));\n        SHA1_Transform(context->state, context->buffer);\n        for (; i + 63 < len; i += 64) {\n            SHA1_Transform(context->state, data + i);\n        }\n        j = 0;\n    } else\n        i = 0;\n    memcpy(&context->buffer[j], &data[i], len - i);\n}\n\n/* Add padding and return the message digest. */\nvoid crypto_SHA1_Final(SHA1_CTX *context, uint8_t *digest)\n{\n    uint32_t i;\n    uint8_t finalcount[8];\n\n    for (i = 0; i < 8; i++) {\n        finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)] >>\n                                         ((3 - (i & 3)) * 8)) &\n                                        255); /* Endian independent */\n    }\n    crypto_SHA1_Update(context, (uint8_t *)\"\\200\", 1);\n    while ((context->count[0] & 504) != 448) {\n        crypto_SHA1_Update(context, (uint8_t *)\"\\0\", 1);\n    }\n    /* Should cause a SHA1_Transform() */\n    crypto_SHA1_Update(context, finalcount, 8);\n    for (i = 0; i < SHA1_DIGEST_SIZE; i++) {\n        digest[i] =\n            (uint8_t)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);\n    }\n\n    /* Wipe variables */\n    SHA1_cleanse(context->buffer, 64);\n    SHA1_cleanse(context->state, 20);\n    SHA1_cleanse(context->count, 8);\n    SHA1_cleanse(finalcount, 8); /* SWR */\n\n    SHA1_Transform(context->state, context->buffer);\n}\n\nvoid crypto_SHA1(const uint8_t *data, size_t len, uint8_t *digest)\n{\n    SHA1_CTX ctx;\n    crypto_SHA1_Init(&ctx);\n    crypto_SHA1_Update(&ctx, data, len);\n    crypto_SHA1_Final(&ctx, digest);\n}\n"
  },
  {
    "path": "src/sha1.h",
    "content": "/* public api for steve reid's public domain SHA-1 implementation */\n/* this file is in the public domain */\n\n/** @file\n *  SHA-1 hash API.\n */\n\n#ifndef __LIBSTROPHE_SHA1_H__\n#define __LIBSTROPHE_SHA1_H__\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* make sure the stdint.h types are available */\n#include \"ostypes.h\"\n\ntypedef struct {\n    uint32_t state[5];\n    uint32_t count[2];\n    uint8_t buffer[64];\n} SHA1_CTX;\n\n#define SHA1_DIGEST_SIZE 20\n\nvoid crypto_SHA1_Init(SHA1_CTX *context);\nvoid crypto_SHA1_Update(SHA1_CTX *context, const uint8_t *data, size_t len);\nvoid crypto_SHA1_Final(SHA1_CTX *context, uint8_t *digest);\nvoid crypto_SHA1(const uint8_t *data, size_t len, uint8_t *digest);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __LIBSTROPHE_SHA1_H__ */\n"
  },
  {
    "path": "src/sha256.c",
    "content": "/*\n * Code originally from LibTomCrypt -- Licensed under the Public Domain/WTFPL2.0\n */\n\n#include \"sha256.h\"\n#include \"sha.h\"\n\n/* Various logical functions */\n#define Ch(x, y, z) (z ^ (x & (y ^ z)))\n#define Maj(x, y, z) (((x | y) & z) | (x & y))\n#define S(x, n) RORc((x), (n))\n#define R(x, n) (((x) & 0xFFFFFFFFUL) >> (n))\n#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))\n#define Sigma1(x) (S(x, 6) ^ S(x, 11) ^ S(x, 25))\n#define Gamma0(x) (S(x, 7) ^ S(x, 18) ^ R(x, 3))\n#define Gamma1(x) (S(x, 17) ^ S(x, 19) ^ R(x, 10))\n\nstatic void sha256_compress(sha256_context *md, const uint8_t *buf)\n{\n    uint32_t S[8], W[64], t0, t1;\n    int i;\n\n    /* copy state into S */\n    for (i = 0; i < 8; i++) {\n        S[i] = md->state[i];\n    }\n\n    /* copy the state into 512-bits into W[0..15] */\n    for (i = 0; i < 16; i++) {\n        LOAD32H(W[i], buf + (4 * i));\n    }\n\n    /* fill W[16..63] */\n    for (i = 16; i < 64; i++) {\n        W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];\n    }\n\n    /* Compress */\n#define RND(a, b, c, d, e, f, g, h, i, ki)        \\\n    t0 = h + Sigma1(e) + Ch(e, f, g) + ki + W[i]; \\\n    t1 = Sigma0(a) + Maj(a, b, c);                \\\n    d += t0;                                      \\\n    h = t0 + t1;\n\n    RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], 0, 0x428a2f98);\n    RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], 1, 0x71374491);\n    RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], 2, 0xb5c0fbcf);\n    RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], 3, 0xe9b5dba5);\n    RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], 4, 0x3956c25b);\n    RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], 5, 0x59f111f1);\n    RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], 6, 0x923f82a4);\n    RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], 7, 0xab1c5ed5);\n    RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], 8, 0xd807aa98);\n    RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], 9, 0x12835b01);\n    RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], 10, 0x243185be);\n    RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], 11, 0x550c7dc3);\n    RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], 12, 0x72be5d74);\n    RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], 13, 0x80deb1fe);\n    RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], 14, 0x9bdc06a7);\n    RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], 15, 0xc19bf174);\n    RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], 16, 0xe49b69c1);\n    RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], 17, 0xefbe4786);\n    RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], 18, 0x0fc19dc6);\n    RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], 19, 0x240ca1cc);\n    RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], 20, 0x2de92c6f);\n    RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], 21, 0x4a7484aa);\n    RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], 22, 0x5cb0a9dc);\n    RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], 23, 0x76f988da);\n    RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], 24, 0x983e5152);\n    RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], 25, 0xa831c66d);\n    RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], 26, 0xb00327c8);\n    RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], 27, 0xbf597fc7);\n    RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], 28, 0xc6e00bf3);\n    RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], 29, 0xd5a79147);\n    RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], 30, 0x06ca6351);\n    RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], 31, 0x14292967);\n    RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], 32, 0x27b70a85);\n    RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], 33, 0x2e1b2138);\n    RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], 34, 0x4d2c6dfc);\n    RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], 35, 0x53380d13);\n    RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], 36, 0x650a7354);\n    RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], 37, 0x766a0abb);\n    RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], 38, 0x81c2c92e);\n    RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], 39, 0x92722c85);\n    RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], 40, 0xa2bfe8a1);\n    RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], 41, 0xa81a664b);\n    RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], 42, 0xc24b8b70);\n    RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], 43, 0xc76c51a3);\n    RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], 44, 0xd192e819);\n    RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], 45, 0xd6990624);\n    RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], 46, 0xf40e3585);\n    RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], 47, 0x106aa070);\n    RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], 48, 0x19a4c116);\n    RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], 49, 0x1e376c08);\n    RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], 50, 0x2748774c);\n    RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], 51, 0x34b0bcb5);\n    RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], 52, 0x391c0cb3);\n    RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], 53, 0x4ed8aa4a);\n    RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], 54, 0x5b9cca4f);\n    RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], 55, 0x682e6ff3);\n    RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], 56, 0x748f82ee);\n    RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], 57, 0x78a5636f);\n    RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], 58, 0x84c87814);\n    RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], 59, 0x8cc70208);\n    RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], 60, 0x90befffa);\n    RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], 61, 0xa4506ceb);\n    RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], 62, 0xbef9a3f7);\n    RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], 63, 0xc67178f2);\n\n#undef RND\n\n    /* feedback */\n    for (i = 0; i < 8; i++) {\n        md->state[i] = md->state[i] + S[i];\n    }\n}\n\nvoid sha256_init(sha256_context *md)\n{\n    md->curlen = 0;\n    md->length = 0;\n    md->state[0] = 0x6A09E667UL;\n    md->state[1] = 0xBB67AE85UL;\n    md->state[2] = 0x3C6EF372UL;\n    md->state[3] = 0xA54FF53AUL;\n    md->state[4] = 0x510E527FUL;\n    md->state[5] = 0x9B05688CUL;\n    md->state[6] = 0x1F83D9ABUL;\n    md->state[7] = 0x5BE0CD19UL;\n}\n\nvoid sha256_process(sha256_context *md, const uint8_t *in, size_t inlen)\n{\n    size_t n;\n    if (md->curlen > sizeof(md->buf)) {\n        return;\n    }\n    if ((md->length + inlen) < md->length) {\n        return;\n    }\n    while (inlen > 0) {\n        if (md->curlen == 0 && inlen >= 64) {\n            sha256_compress(md, in);\n            md->length += 64 * 8;\n            in += 64;\n            inlen -= 64;\n        } else {\n            n = (((inlen) < ((64 - md->curlen))) ? (inlen)\n                                                 : ((64 - md->curlen)));\n            memcpy(md->buf + md->curlen, in, (size_t)n);\n            md->curlen += n;\n            in += n;\n            inlen -= n;\n            if (md->curlen == 64) {\n                sha256_compress(md, md->buf);\n                md->length += 8 * 64;\n                md->curlen = 0;\n            }\n        }\n    }\n}\n\nvoid sha256_done(sha256_context *md, uint8_t *out)\n{\n    int i;\n\n    if (md->curlen >= sizeof(md->buf)) {\n        return;\n    }\n\n    /* increase the length of the message */\n    md->length += md->curlen * 8;\n\n    /* append the '1' bit */\n    md->buf[md->curlen++] = (uint8_t)0x80;\n\n    /* if the length is currently above 56 bytes we append zeros\n     * then compress.  Then we can fall back to padding zeros and length\n     * encoding like normal.\n     */\n    if (md->curlen > 56) {\n        while (md->curlen < 64) {\n            md->buf[md->curlen++] = (uint8_t)0;\n        }\n        sha256_compress(md, md->buf);\n        md->curlen = 0;\n    }\n\n    /* pad upto 56 bytes of zeroes */\n    while (md->curlen < 56) {\n        md->buf[md->curlen++] = (uint8_t)0;\n    }\n\n    /* store length */\n    STORE64H(md->length, md->buf + 56);\n    sha256_compress(md, md->buf);\n\n    /* copy output */\n    for (i = 0; i < 8; i++) {\n        STORE32H(md->state[i], out + (4 * i));\n    }\n}\n\nvoid sha256_hash(const uint8_t *data, size_t len, uint8_t *digest)\n{\n    sha256_context md;\n    sha256_init(&md);\n    sha256_process(&md, data, len);\n    sha256_done(&md, digest);\n}\n"
  },
  {
    "path": "src/sha256.h",
    "content": "/* public api for LibTomCrypt SHA-256 implementation */\n\n/** @file\n *  SHA-256 hash API.\n */\n\n#ifndef __LIBSTROPHE_SHA256_H__\n#define __LIBSTROPHE_SHA256_H__\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* make sure the stdint.h types are available */\n#include \"ostypes.h\"\n\ntypedef struct {\n    uint64_t length;\n    uint32_t state[8], curlen;\n    uint8_t buf[64];\n} sha256_context;\n\n#define SHA256_DIGEST_SIZE 32\n\nvoid sha256_init(sha256_context *md);\nvoid sha256_process(sha256_context *md, const uint8_t *in, size_t inlen);\nvoid sha256_done(sha256_context *md, uint8_t *out);\n\nvoid sha256_hash(const uint8_t *data, size_t len, uint8_t *digest);\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __LIBSTROPHE_SHA256_H__ */\n"
  },
  {
    "path": "src/sha512.c",
    "content": "/*\n * Code originally from LibTomCrypt -- Licensed under the Public Domain/WTFPL2.0\n */\n\n#include \"sha512.h\"\n#include \"sha.h\"\n\n/* the K array */\nstatic const uint64_t K[80] = {\n    CONST64(0x428a2f98d728ae22), CONST64(0x7137449123ef65cd),\n    CONST64(0xb5c0fbcfec4d3b2f), CONST64(0xe9b5dba58189dbbc),\n    CONST64(0x3956c25bf348b538), CONST64(0x59f111f1b605d019),\n    CONST64(0x923f82a4af194f9b), CONST64(0xab1c5ed5da6d8118),\n    CONST64(0xd807aa98a3030242), CONST64(0x12835b0145706fbe),\n    CONST64(0x243185be4ee4b28c), CONST64(0x550c7dc3d5ffb4e2),\n    CONST64(0x72be5d74f27b896f), CONST64(0x80deb1fe3b1696b1),\n    CONST64(0x9bdc06a725c71235), CONST64(0xc19bf174cf692694),\n    CONST64(0xe49b69c19ef14ad2), CONST64(0xefbe4786384f25e3),\n    CONST64(0x0fc19dc68b8cd5b5), CONST64(0x240ca1cc77ac9c65),\n    CONST64(0x2de92c6f592b0275), CONST64(0x4a7484aa6ea6e483),\n    CONST64(0x5cb0a9dcbd41fbd4), CONST64(0x76f988da831153b5),\n    CONST64(0x983e5152ee66dfab), CONST64(0xa831c66d2db43210),\n    CONST64(0xb00327c898fb213f), CONST64(0xbf597fc7beef0ee4),\n    CONST64(0xc6e00bf33da88fc2), CONST64(0xd5a79147930aa725),\n    CONST64(0x06ca6351e003826f), CONST64(0x142929670a0e6e70),\n    CONST64(0x27b70a8546d22ffc), CONST64(0x2e1b21385c26c926),\n    CONST64(0x4d2c6dfc5ac42aed), CONST64(0x53380d139d95b3df),\n    CONST64(0x650a73548baf63de), CONST64(0x766a0abb3c77b2a8),\n    CONST64(0x81c2c92e47edaee6), CONST64(0x92722c851482353b),\n    CONST64(0xa2bfe8a14cf10364), CONST64(0xa81a664bbc423001),\n    CONST64(0xc24b8b70d0f89791), CONST64(0xc76c51a30654be30),\n    CONST64(0xd192e819d6ef5218), CONST64(0xd69906245565a910),\n    CONST64(0xf40e35855771202a), CONST64(0x106aa07032bbd1b8),\n    CONST64(0x19a4c116b8d2d0c8), CONST64(0x1e376c085141ab53),\n    CONST64(0x2748774cdf8eeb99), CONST64(0x34b0bcb5e19b48a8),\n    CONST64(0x391c0cb3c5c95a63), CONST64(0x4ed8aa4ae3418acb),\n    CONST64(0x5b9cca4f7763e373), CONST64(0x682e6ff3d6b2b8a3),\n    CONST64(0x748f82ee5defb2fc), CONST64(0x78a5636f43172f60),\n    CONST64(0x84c87814a1f0ab72), CONST64(0x8cc702081a6439ec),\n    CONST64(0x90befffa23631e28), CONST64(0xa4506cebde82bde9),\n    CONST64(0xbef9a3f7b2c67915), CONST64(0xc67178f2e372532b),\n    CONST64(0xca273eceea26619c), CONST64(0xd186b8c721c0c207),\n    CONST64(0xeada7dd6cde0eb1e), CONST64(0xf57d4f7fee6ed178),\n    CONST64(0x06f067aa72176fba), CONST64(0x0a637dc5a2c898a6),\n    CONST64(0x113f9804bef90dae), CONST64(0x1b710b35131c471b),\n    CONST64(0x28db77f523047d84), CONST64(0x32caab7b40c72493),\n    CONST64(0x3c9ebe0a15c9bebc), CONST64(0x431d67c49c100d4c),\n    CONST64(0x4cc5d4becb3e42b6), CONST64(0x597f299cfc657e2a),\n    CONST64(0x5fcb6fab3ad6faec), CONST64(0x6c44198c4a475817)};\n\n/* Various logical functions */\n#define Ch(x, y, z) (z ^ (x & (y ^ z)))\n#define Maj(x, y, z) (((x | y) & z) | (x & y))\n#define S(x, n) ROR64c(x, n)\n#define R(x, n) (((x) & CONST64(0xFFFFFFFFFFFFFFFF)) >> ((uint64_t)n))\n#define Sigma0(x) (S(x, 28) ^ S(x, 34) ^ S(x, 39))\n#define Sigma1(x) (S(x, 14) ^ S(x, 18) ^ S(x, 41))\n#define Gamma0(x) (S(x, 1) ^ S(x, 8) ^ R(x, 7))\n#define Gamma1(x) (S(x, 19) ^ S(x, 61) ^ R(x, 6))\n\n/* compress 1024-bits */\nstatic void sha512_compress(sha512_context *md, const uint8_t *buf)\n{\n    uint64_t S[8], W[80], t0, t1;\n    int i;\n\n    /* copy state into S */\n    for (i = 0; i < 8; i++) {\n        S[i] = md->state[i];\n    }\n\n    /* copy the state into 1024-bits into W[0..15] */\n    for (i = 0; i < 16; i++) {\n        LOAD64H(W[i], buf + (8 * i));\n    }\n\n    /* fill W[16..79] */\n    for (i = 16; i < 80; i++) {\n        W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];\n    }\n\n    /* Compress */\n#define RND(a, b, c, d, e, f, g, h, i)              \\\n    t0 = h + Sigma1(e) + Ch(e, f, g) + K[i] + W[i]; \\\n    t1 = Sigma0(a) + Maj(a, b, c);                  \\\n    d += t0;                                        \\\n    h = t0 + t1;\n\n    for (i = 0; i < 80; i += 8) {\n        RND(S[0], S[1], S[2], S[3], S[4], S[5], S[6], S[7], i + 0);\n        RND(S[7], S[0], S[1], S[2], S[3], S[4], S[5], S[6], i + 1);\n        RND(S[6], S[7], S[0], S[1], S[2], S[3], S[4], S[5], i + 2);\n        RND(S[5], S[6], S[7], S[0], S[1], S[2], S[3], S[4], i + 3);\n        RND(S[4], S[5], S[6], S[7], S[0], S[1], S[2], S[3], i + 4);\n        RND(S[3], S[4], S[5], S[6], S[7], S[0], S[1], S[2], i + 5);\n        RND(S[2], S[3], S[4], S[5], S[6], S[7], S[0], S[1], i + 6);\n        RND(S[1], S[2], S[3], S[4], S[5], S[6], S[7], S[0], i + 7);\n    }\n\n    /* feedback */\n    for (i = 0; i < 8; i++) {\n        md->state[i] = md->state[i] + S[i];\n    }\n}\n\nvoid sha512_init(sha512_context *md)\n{\n    md->curlen = 0;\n    md->length = 0;\n    md->state[0] = CONST64(0x6a09e667f3bcc908);\n    md->state[1] = CONST64(0xbb67ae8584caa73b);\n    md->state[2] = CONST64(0x3c6ef372fe94f82b);\n    md->state[3] = CONST64(0xa54ff53a5f1d36f1);\n    md->state[4] = CONST64(0x510e527fade682d1);\n    md->state[5] = CONST64(0x9b05688c2b3e6c1f);\n    md->state[6] = CONST64(0x1f83d9abfb41bd6b);\n    md->state[7] = CONST64(0x5be0cd19137e2179);\n}\n\nvoid sha512_process(sha512_context *md, const uint8_t *in, size_t inlen)\n{\n    size_t n;\n    if (md->curlen > sizeof(md->buf)) {\n        return;\n    }\n    if ((md->length + inlen) < md->length) {\n        return;\n    }\n    while (inlen > 0) {\n        if (md->curlen == 0 && inlen >= 128) {\n            sha512_compress(md, in);\n            md->length += 128 * 8;\n            in += 128;\n            inlen -= 128;\n        } else {\n            n = (((inlen) < ((128u - md->curlen))) ? (inlen)\n                                                   : ((128u - md->curlen)));\n            memcpy(md->buf + md->curlen, in, (size_t)n);\n            md->curlen += n;\n            in += n;\n            inlen -= n;\n            if (md->curlen == 128) {\n                sha512_compress(md, md->buf);\n                md->length += 8 * 128;\n                md->curlen = 0;\n            }\n        }\n    }\n}\n\nvoid sha512_done(sha512_context *md, uint8_t *out)\n{\n    int i;\n\n    if (md->curlen >= sizeof(md->buf)) {\n        return;\n    }\n\n    /* increase the length of the message */\n    md->length += md->curlen * CONST64(8);\n\n    /* append the '1' bit */\n    md->buf[md->curlen++] = (uint8_t)0x80;\n\n    /* if the length is currently above 112 bytes we append zeros\n     * then compress.  Then we can fall back to padding zeros and length\n     * encoding like normal.\n     */\n    if (md->curlen > 112) {\n        while (md->curlen < 128) {\n            md->buf[md->curlen++] = (uint8_t)0;\n        }\n        sha512_compress(md, md->buf);\n        md->curlen = 0;\n    }\n\n    /* pad upto 120 bytes of zeroes\n     * note: that from 112 to 120 is the 64 MSB of the length.  We assume that\n     * you won't hash > 2^64 bits of data... :-)\n     */\n    while (md->curlen < 120) {\n        md->buf[md->curlen++] = (uint8_t)0;\n    }\n\n    /* store length */\n    STORE64H(md->length, md->buf + 120);\n    sha512_compress(md, md->buf);\n\n    /* copy output */\n    for (i = 0; i < 8; i++) {\n        STORE64H(md->state[i], out + (8 * i));\n    }\n}\n\nvoid sha512_hash(const uint8_t *data, size_t len, uint8_t *digest)\n{\n    sha512_context md;\n    sha512_init(&md);\n    sha512_process(&md, data, len);\n    sha512_done(&md, digest);\n}\n"
  },
  {
    "path": "src/sha512.h",
    "content": "/* public api for LibTomCrypt SHA-512 implementation */\n\n/** @file\n *  SHA-512 hash API.\n */\n\n#ifndef __LIBSTROPHE_SHA512_H__\n#define __LIBSTROPHE_SHA512_H__\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* make sure the stdint.h types are available */\n#include \"ostypes.h\"\n\ntypedef struct {\n    uint64_t length, state[8];\n    uint8_t curlen;\n    uint8_t buf[128];\n} sha512_context;\n\n#define SHA512_DIGEST_SIZE 64\n\nvoid sha512_init(sha512_context *cc);\nvoid sha512_process(sha512_context *cc, const uint8_t *data, size_t len);\nvoid sha512_done(sha512_context *cc, uint8_t *dst);\n\nvoid sha512_hash(const uint8_t *data, size_t len, uint8_t *digest);\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __LIBSTROPHE_SHA512_H__ */\n"
  },
  {
    "path": "src/snprintf.c",
    "content": "/*\n * Copyright Patrick Powell 1995\n * This code is based on code written by Patrick Powell (papowell@astart.com)\n * It may be used for any purpose as long as this notice remains intact\n * on all source code distributions\n */\n\n/**************************************************************\n * Original:\n * Patrick Powell Tue Apr 11 09:48:21 PDT 1995\n * A bombproof version of doprnt (dopr) included.\n * Sigh.  This sort of thing is always nasty do deal with.  Note that\n * the version here does not include floating point...\n *\n * snprintf() is used instead of sprintf() as it does limit checks\n * for string length.  This covers a nasty loophole.\n *\n * The other functions are there to prevent NULL pointers from\n * causing nast effects.\n *\n * More Recently:\n *  Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43\n *  This was ugly.  It is still ugly.  I opted out of floating point\n *  numbers, but the formatter understands just about everything\n *  from the normal C string format, at least as far as I can tell from\n *  the Solaris 2.5 printf(3S) man page.\n *\n *  Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1\n *    Ok, added some minimal floating point support, which means this\n *    probably requires libm on most operating systems.  Don't yet\n *    support the exponent (e,E) and sigfig (g,G).  Also, fmtint()\n *    was pretty badly broken, it just wasn't being exercised in ways\n *    which showed it, so that's been fixed.  Also, formated the code\n *    to mutt conventions, and removed dead code left over from the\n *    original.  Also, there is now a builtin-test, just compile with:\n *           gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm\n *    and run snprintf for results.\n *\n *  Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i\n *    The PGP code was using unsigned hexadecimal formats.\n *    Unfortunately, unsigned formats simply didn't work.\n *\n *  Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8\n *    The original code assumed that both snprintf() and vsnprintf() were\n *    missing.  Some systems only have snprintf() but not vsnprintf(), so\n *    the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.\n *\n *  Andrew Tridgell (tridge@samba.org) Oct 1998\n *    fixed handling of %.0f\n *    added test for HAVE_LONG_DOUBLE\n *\n *  Russ Allbery <rra@stanford.edu> 2000-08-26\n *    fixed return value to comply with C99\n *    fixed handling of snprintf(NULL, ...)\n *\n **************************************************************/\n\n/** @file\n *  A snprintf implementation.\n */\n\n/* JAM: we don't need this - #include \"config.h\" */\n\n/* JAM: changed declarations to strophe_snprintf and strophe_vsnprintf to\n   avoid namespace collision. */\n\n#include \"snprintf.h\"\n\n/* varargs declarations: */\n\n#include <stdarg.h>\n#define VA_LOCAL_DECL va_list ap\n#define VA_START(f) va_start(ap, f)\n#define VA_END va_end(ap)\n\n#ifndef HAVE_VSNPRINTF\n\n#include <string.h>\n#include <ctype.h>\n#include <sys/types.h>\n\n#ifdef HAVE_LONG_DOUBLE\n#define LDOUBLE long double\n#else\n#define LDOUBLE double\n#endif\n\nstatic int dopr(char *buffer, size_t maxlen, const char *format, va_list args);\nstatic int fmtstr(char *buffer,\n                  size_t *currlen,\n                  size_t maxlen,\n                  char *value,\n                  int flags,\n                  int min,\n                  int max);\nstatic int fmtint(char *buffer,\n                  size_t *currlen,\n                  size_t maxlen,\n                  long value,\n                  int base,\n                  int min,\n                  int max,\n                  int flags);\nstatic int fmtfp(char *buffer,\n                 size_t *currlen,\n                 size_t maxlen,\n                 LDOUBLE fvalue,\n                 int min,\n                 int max,\n                 int flags);\nstatic int dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c);\n\n/*\n * dopr(): poor man's version of doprintf\n */\n\n/* format read states */\n#define DP_S_DEFAULT 0\n#define DP_S_FLAGS 1\n#define DP_S_MIN 2\n#define DP_S_DOT 3\n#define DP_S_MAX 4\n#define DP_S_MOD 5\n#define DP_S_CONV 6\n#define DP_S_DONE 7\n\n/* format flags - Bits */\n#define DP_F_MINUS (1 << 0)\n#define DP_F_PLUS (1 << 1)\n#define DP_F_SPACE (1 << 2)\n#define DP_F_NUM (1 << 3)\n#define DP_F_ZERO (1 << 4)\n#define DP_F_UP (1 << 5)\n#define DP_F_UNSIGNED (1 << 6)\n\n/* Conversion Flags */\n#define DP_C_SHORT 1\n#define DP_C_LONG 2\n#define DP_C_LDOUBLE 3\n\n#define char_to_int(p) (p - '0')\n#define MAX(p, q) ((p >= q) ? p : q)\n#define MIN(p, q) ((p <= q) ? p : q)\n\nstatic int dopr(char *buffer, size_t maxlen, const char *format, va_list args)\n{\n    char ch;\n    long value;\n    LDOUBLE fvalue;\n    char *strvalue;\n    int min;\n    int max;\n    int state;\n    int flags;\n    int cflags;\n    int total;\n    size_t currlen;\n\n    state = DP_S_DEFAULT;\n    currlen = flags = cflags = min = 0;\n    max = -1;\n    ch = *format++;\n    total = 0;\n\n    while (state != DP_S_DONE) {\n        if (ch == '\\0')\n            state = DP_S_DONE;\n\n        switch (state) {\n        case DP_S_DEFAULT:\n            if (ch == '%')\n                state = DP_S_FLAGS;\n            else\n                total += dopr_outch(buffer, &currlen, maxlen, ch);\n            ch = *format++;\n            break;\n        case DP_S_FLAGS:\n            switch (ch) {\n            case '-':\n                flags |= DP_F_MINUS;\n                ch = *format++;\n                break;\n            case '+':\n                flags |= DP_F_PLUS;\n                ch = *format++;\n                break;\n            case ' ':\n                flags |= DP_F_SPACE;\n                ch = *format++;\n                break;\n            case '#':\n                flags |= DP_F_NUM;\n                ch = *format++;\n                break;\n            case '0':\n                flags |= DP_F_ZERO;\n                ch = *format++;\n                break;\n            default:\n                state = DP_S_MIN;\n                break;\n            }\n            break;\n        case DP_S_MIN:\n            if (isdigit(ch)) {\n                min = 10 * min + char_to_int(ch);\n                ch = *format++;\n            } else if (ch == '*') {\n                min = va_arg(args, int);\n                ch = *format++;\n                state = DP_S_DOT;\n            } else\n                state = DP_S_DOT;\n            break;\n        case DP_S_DOT:\n            if (ch == '.') {\n                state = DP_S_MAX;\n                ch = *format++;\n            } else\n                state = DP_S_MOD;\n            break;\n        case DP_S_MAX:\n            if (isdigit(ch)) {\n                if (max < 0)\n                    max = 0;\n                max = 10 * max + char_to_int(ch);\n                ch = *format++;\n            } else if (ch == '*') {\n                max = va_arg(args, int);\n                ch = *format++;\n                state = DP_S_MOD;\n            } else\n                state = DP_S_MOD;\n            break;\n        case DP_S_MOD:\n            /* Currently, we don't support Long Long, bummer */\n            switch (ch) {\n            case 'h':\n                cflags = DP_C_SHORT;\n                ch = *format++;\n                break;\n            case 'l':\n                cflags = DP_C_LONG;\n                ch = *format++;\n                break;\n            case 'L':\n                cflags = DP_C_LDOUBLE;\n                ch = *format++;\n                break;\n            default:\n                break;\n            }\n            state = DP_S_CONV;\n            break;\n        case DP_S_CONV:\n            switch (ch) {\n            case 'd':\n            case 'i':\n                if (cflags == DP_C_SHORT)\n                    value = va_arg(args, int);\n                else if (cflags == DP_C_LONG)\n                    value = va_arg(args, long int);\n                else\n                    value = va_arg(args, int);\n                total += fmtint(buffer, &currlen, maxlen, value, 10, min, max,\n                                flags);\n                break;\n            case 'o':\n                flags |= DP_F_UNSIGNED;\n                if (cflags == DP_C_SHORT)\n                    value = va_arg(args, int);\n                else if (cflags == DP_C_LONG)\n                    value = va_arg(args, unsigned long int);\n                else\n                    value = va_arg(args, unsigned int);\n                total +=\n                    fmtint(buffer, &currlen, maxlen, value, 8, min, max, flags);\n                break;\n            case 'u':\n                flags |= DP_F_UNSIGNED;\n                if (cflags == DP_C_SHORT)\n                    value = va_arg(args, int);\n                else if (cflags == DP_C_LONG)\n                    value = va_arg(args, unsigned long int);\n                else\n                    value = va_arg(args, unsigned int);\n                total += fmtint(buffer, &currlen, maxlen, value, 10, min, max,\n                                flags);\n                break;\n            case 'X':\n                flags |= DP_F_UP;\n                //-fallthrough\n            case 'x':\n                flags |= DP_F_UNSIGNED;\n                if (cflags == DP_C_SHORT)\n                    value = va_arg(args, int);\n                else if (cflags == DP_C_LONG)\n                    value = va_arg(args, unsigned long int);\n                else\n                    value = va_arg(args, unsigned int);\n                total += fmtint(buffer, &currlen, maxlen, value, 16, min, max,\n                                flags);\n                break;\n            case 'f':\n                if (cflags == DP_C_LDOUBLE)\n                    fvalue = va_arg(args, LDOUBLE);\n                else\n                    fvalue = va_arg(args, double);\n                /* um, floating point? */\n                total +=\n                    fmtfp(buffer, &currlen, maxlen, fvalue, min, max, flags);\n                break;\n            case 'E':\n                flags |= DP_F_UP;\n                //-fallthrough\n            case 'e':\n                if (cflags == DP_C_LDOUBLE)\n                    fvalue = va_arg(args, LDOUBLE);\n                else\n                    fvalue = va_arg(args, double);\n                break;\n            case 'G':\n                flags |= DP_F_UP;\n                //-fallthrough\n            case 'g':\n                if (cflags == DP_C_LDOUBLE)\n                    fvalue = va_arg(args, LDOUBLE);\n                else\n                    fvalue = va_arg(args, double);\n                break;\n            case 'c':\n                total +=\n                    dopr_outch(buffer, &currlen, maxlen, va_arg(args, int));\n                break;\n            case 's':\n                strvalue = va_arg(args, char *);\n                total +=\n                    fmtstr(buffer, &currlen, maxlen, strvalue, flags, min, max);\n                break;\n            case 'p':\n                strvalue = va_arg(args, void *);\n                total += fmtint(buffer, &currlen, maxlen, (long)strvalue, 16,\n                                min, max, flags);\n                break;\n            case 'n':\n                if (cflags == DP_C_SHORT) {\n                    short int *num;\n                    num = va_arg(args, short int *);\n                    *num = currlen;\n                } else if (cflags == DP_C_LONG) {\n                    long int *num;\n                    num = va_arg(args, long int *);\n                    *num = currlen;\n                } else {\n                    int *num;\n                    num = va_arg(args, int *);\n                    *num = currlen;\n                }\n                break;\n            case '%':\n                total += dopr_outch(buffer, &currlen, maxlen, ch);\n                break;\n            case 'w':\n                /* not supported yet, treat as next char */\n                ch = *format++;\n                break;\n            default:\n                /* Unknown, skip */\n                break;\n            }\n            ch = *format++;\n            state = DP_S_DEFAULT;\n            flags = cflags = min = 0;\n            max = -1;\n            break;\n        case DP_S_DONE:\n            break;\n        default:\n            /* hmm? */\n            break; /* some picky compilers need this */\n        }\n    }\n    if (buffer != NULL && maxlen > 0) {\n        if (currlen < maxlen - 1)\n            buffer[currlen] = '\\0';\n        else\n            buffer[maxlen - 1] = '\\0';\n    }\n    return total;\n}\n\nstatic int fmtstr(char *buffer,\n                  size_t *currlen,\n                  size_t maxlen,\n                  char *value,\n                  int flags,\n                  int min,\n                  int max)\n{\n    int padlen, strln; /* amount to pad */\n    int cnt = 0;\n    int total = 0;\n\n    if (value == 0) {\n        value = \"<NULL>\";\n    }\n\n    for (strln = 0; value[strln]; ++strln)\n        ; /* strlen */\n    if (max >= 0 && max < strln)\n        strln = max;\n    padlen = min - strln;\n    if (padlen < 0)\n        padlen = 0;\n    if (flags & DP_F_MINUS)\n        padlen = -padlen; /* Left Justify */\n\n    while (padlen > 0) {\n        total += dopr_outch(buffer, currlen, maxlen, ' ');\n        --padlen;\n    }\n    while (*value && ((max < 0) || (cnt < max))) {\n        total += dopr_outch(buffer, currlen, maxlen, *value++);\n        ++cnt;\n    }\n    while (padlen < 0) {\n        total += dopr_outch(buffer, currlen, maxlen, ' ');\n        ++padlen;\n    }\n    return total;\n}\n\n/* Have to handle DP_F_NUM (ie 0x and 0 alternates) */\n\nstatic int fmtint(char *buffer,\n                  size_t *currlen,\n                  size_t maxlen,\n                  long value,\n                  int base,\n                  int min,\n                  int max,\n                  int flags)\n{\n    int signvalue = 0;\n    unsigned long uvalue;\n    char convert[20];\n    int place = 0;\n    int spadlen = 0; /* amount to space pad */\n    int zpadlen = 0; /* amount to zero pad */\n    int caps = 0;\n    int total = 0;\n\n    if (max < 0)\n        max = 0;\n\n    uvalue = value;\n\n    if (!(flags & DP_F_UNSIGNED)) {\n        if (value < 0) {\n            signvalue = '-';\n            uvalue = -value;\n        } else if (flags & DP_F_PLUS) /* Do a sign (+/i) */\n            signvalue = '+';\n        else if (flags & DP_F_SPACE)\n            signvalue = ' ';\n    }\n\n    if (flags & DP_F_UP)\n        caps = 1; /* Should characters be upper case? */\n\n    do {\n        convert[place++] = (caps ? \"0123456789ABCDEF\"\n                                 : \"0123456789abcdef\")[uvalue % (unsigned)base];\n        uvalue = (uvalue / (unsigned)base);\n    } while (uvalue && (place < 20));\n    if (place == 20)\n        place--;\n    convert[place] = 0;\n\n    zpadlen = max - place;\n    spadlen = min - MAX(max, place) - (signvalue ? 1 : 0);\n    if (zpadlen < 0)\n        zpadlen = 0;\n    if (spadlen < 0)\n        spadlen = 0;\n    if (flags & DP_F_ZERO) {\n        zpadlen = MAX(zpadlen, spadlen);\n        spadlen = 0;\n    }\n    if (flags & DP_F_MINUS)\n        spadlen = -spadlen; /* Left Justifty */\n\n#ifdef DEBUG_SNPRINTF\n    dprint(1, (debugfile, \"zpad: %d, spad: %d, min: %d, max: %d, place: %d\\n\",\n               zpadlen, spadlen, min, max, place));\n#endif\n\n    /* Spaces */\n    while (spadlen > 0) {\n        total += dopr_outch(buffer, currlen, maxlen, ' ');\n        --spadlen;\n    }\n\n    /* Sign */\n    if (signvalue)\n        total += dopr_outch(buffer, currlen, maxlen, signvalue);\n\n    /* Zeros */\n    if (zpadlen > 0) {\n        while (zpadlen > 0) {\n            total += dopr_outch(buffer, currlen, maxlen, '0');\n            --zpadlen;\n        }\n    }\n\n    /* Digits */\n    while (place > 0)\n        total += dopr_outch(buffer, currlen, maxlen, convert[--place]);\n\n    /* Left Justified spaces */\n    while (spadlen < 0) {\n        total += dopr_outch(buffer, currlen, maxlen, ' ');\n        ++spadlen;\n    }\n\n    return total;\n}\n\nstatic LDOUBLE abs_val(LDOUBLE value)\n{\n    LDOUBLE result = value;\n\n    if (value < 0)\n        result = -value;\n\n    return result;\n}\n\nstatic LDOUBLE _snp_pow10(int exp)\n{\n    LDOUBLE result = 1;\n\n    while (exp) {\n        result *= 10;\n        exp--;\n    }\n\n    return result;\n}\n\nstatic long _snp_round(LDOUBLE value)\n{\n    long intpart;\n\n    intpart = value;\n    value = value - intpart;\n    if (value >= 0.5)\n        intpart++;\n\n    return intpart;\n}\n\nstatic int fmtfp(char *buffer,\n                 size_t *currlen,\n                 size_t maxlen,\n                 LDOUBLE fvalue,\n                 int min,\n                 int max,\n                 int flags)\n{\n    int signvalue = 0;\n    LDOUBLE ufvalue;\n    char iconvert[20];\n    char fconvert[20];\n    int iplace = 0;\n    int fplace = 0;\n    int padlen = 0; /* amount to pad */\n    int zpadlen = 0;\n    int caps = 0;\n    int total = 0;\n    long intpart;\n    long fracpart;\n\n    /*\n     * AIX manpage says the default is 0, but Solaris says the default\n     * is 6, and sprintf on AIX defaults to 6\n     */\n    if (max < 0)\n        max = 6;\n\n    ufvalue = abs_val(fvalue);\n\n    if (fvalue < 0)\n        signvalue = '-';\n    else if (flags & DP_F_PLUS) /* Do a sign (+/i) */\n        signvalue = '+';\n    else if (flags & DP_F_SPACE)\n        signvalue = ' ';\n\n#if 0\n  if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */\n#endif\n\n    intpart = ufvalue;\n\n    /*\n     * Sorry, we only support 9 digits past the decimal because of our\n     * conversion method\n     */\n    if (max > 9)\n        max = 9;\n\n    /* We \"cheat\" by converting the fractional part to integer by\n     * multiplying by a factor of 10\n     */\n    fracpart = _snp_round((_snp_pow10(max)) * (ufvalue - intpart));\n\n    if (fracpart >= _snp_pow10(max)) {\n        intpart++;\n        fracpart -= _snp_pow10(max);\n    }\n\n#ifdef DEBUG_SNPRINTF\n    dprint(1, (debugfile, \"fmtfp: %f =? %d.%d\\n\", fvalue, intpart, fracpart));\n#endif\n\n    /* Convert integer part */\n    do {\n        iconvert[iplace++] =\n            (caps ? \"0123456789ABCDEF\" : \"0123456789abcdef\")[intpart % 10];\n        intpart = (intpart / 10);\n    } while (intpart && (iplace < 20));\n    if (iplace == 20)\n        iplace--;\n    iconvert[iplace] = 0;\n\n    /* Convert fractional part */\n    do {\n        fconvert[fplace++] =\n            (caps ? \"0123456789ABCDEF\" : \"0123456789abcdef\")[fracpart % 10];\n        fracpart = (fracpart / 10);\n    } while (fracpart && (fplace < 20));\n    if (fplace == 20)\n        fplace--;\n    fconvert[fplace] = 0;\n\n    /* -1 for decimal point, another -1 if we are printing a sign */\n    padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0);\n    zpadlen = max - fplace;\n    if (zpadlen < 0)\n        zpadlen = 0;\n    if (padlen < 0)\n        padlen = 0;\n    if (flags & DP_F_MINUS)\n        padlen = -padlen; /* Left Justifty */\n\n    if ((flags & DP_F_ZERO) && (padlen > 0)) {\n        if (signvalue) {\n            total += dopr_outch(buffer, currlen, maxlen, signvalue);\n            --padlen;\n            signvalue = 0;\n        }\n        while (padlen > 0) {\n            total += dopr_outch(buffer, currlen, maxlen, '0');\n            --padlen;\n        }\n    }\n    while (padlen > 0) {\n        total += dopr_outch(buffer, currlen, maxlen, ' ');\n        --padlen;\n    }\n    if (signvalue)\n        total += dopr_outch(buffer, currlen, maxlen, signvalue);\n\n    while (iplace > 0)\n        total += dopr_outch(buffer, currlen, maxlen, iconvert[--iplace]);\n\n    /*\n     * Decimal point.  This should probably use locale to find the correct\n     * char to print out.\n     */\n    if (max > 0) {\n        total += dopr_outch(buffer, currlen, maxlen, '.');\n\n        while (fplace > 0)\n            total += dopr_outch(buffer, currlen, maxlen, fconvert[--fplace]);\n    }\n\n    while (zpadlen > 0) {\n        total += dopr_outch(buffer, currlen, maxlen, '0');\n        --zpadlen;\n    }\n\n    while (padlen < 0) {\n        total += dopr_outch(buffer, currlen, maxlen, ' ');\n        ++padlen;\n    }\n\n    return total;\n}\n\nstatic int dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c)\n{\n    if (*currlen + 1 < maxlen)\n        buffer[(*currlen)++] = c;\n    return 1;\n}\n\nint strophe_vsnprintf(char *str, size_t count, const char *fmt, va_list args)\n{\n    if (str != NULL && count > 0)\n        str[0] = 0;\n    return dopr(str, count, fmt, args);\n}\n#endif /* !HAVE_VSNPRINTF */\n\n#ifndef HAVE_SNPRINTF\n/* VARARGS3 */\nint strophe_snprintf(char *str, size_t count, const char *fmt, ...)\n{\n    VA_LOCAL_DECL;\n    int total;\n\n    VA_START(fmt);\n    total = strophe_vsnprintf(str, count, fmt, ap);\n    VA_END;\n    return total;\n}\n#endif /* !HAVE_SNPRINTF */\n"
  },
  {
    "path": "src/snprintf.h",
    "content": "/*\n * Copyright Patrick Powell 1995\n * This code is based on code written by Patrick Powell (papowell@astart.com)\n * It may be used for any purpose as long as this notice remains intact\n * on all source code distributions\n */\n\n/** @file\n *  Compatibility wrappers for OSes lacking snprintf(3) and/or vsnprintf(3).\n */\n\n#ifndef __LIBSTROPHE_SNPRINTF_H__\n#define __LIBSTROPHE_SNPRINTF_H__\n\n#include <stddef.h>\n#include <stdarg.h>\n\n#if defined(HAVE_SNPRINTF) || defined(HAVE_VSNPRINTF)\n#include <stdio.h>\n#endif\n\n#ifdef HAVE_SNPRINTF\n#define strophe_snprintf snprintf\n#else\nint strophe_snprintf(char *str, size_t count, const char *fmt, ...);\n#endif\n\n#ifdef HAVE_VSNPRINTF\n#define strophe_vsnprintf vsnprintf\n#else\nint strophe_vsnprintf(char *str, size_t count, const char *fmt, va_list arg);\n#endif\n\n#endif /* __LIBSTROPHE_SNPRINTF_H__ */\n"
  },
  {
    "path": "src/sock.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* sock.c\n** strophe XMPP client library -- socket abstraction implementation\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Socket abstraction.\n */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/types.h>\n\n#ifdef _WIN32\n#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <iphlpapi.h>\n#include <mstcpip.h> /* tcp_keepalive */\n#else\n#include <arpa/inet.h>\n#include <errno.h>\n#include <unistd.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/tcp.h>\n#include <netdb.h>\n#include <fcntl.h>\n#endif\n\n#include \"common.h\"\n#include \"resolver.h\"\n\nconst struct conn_interface sock_intf = {\n    sock_read,\n    sock_write,\n    /* no flush */\n    conn_int_nop,\n    /* no pending */\n    conn_int_nop,\n    sock_error,\n    sock_is_recoverable,\n    NULL,\n};\n\nstruct _xmpp_sock_t {\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    struct addrinfo *ainfo_list;\n    struct addrinfo *ainfo_cur;\n    resolver_srv_rr_t *srv_rr_list;\n    resolver_srv_rr_t *srv_rr_cur;\n    const char *host;\n    unsigned short port;\n};\n\nvoid sock_initialize(void)\n{\n#ifdef _WIN32\n    WSADATA wsad;\n    WSAStartup(0x0101, &wsad);\n#endif\n}\n\nvoid sock_shutdown(void)\n{\n#ifdef _WIN32\n    WSACleanup();\n#endif\n}\n\nint sock_error(struct conn_interface *intf)\n{\n    UNUSED(intf);\n#ifdef _WIN32\n    return WSAGetLastError();\n#else\n    return errno;\n#endif\n}\n\nstatic int _in_progress(int error)\n{\n#ifdef _WIN32\n    return (error == WSAEWOULDBLOCK || error == WSAEINPROGRESS);\n#else\n    return (error == EINPROGRESS);\n#endif\n}\n\nstatic void sock_getaddrinfo(xmpp_sock_t *xsock)\n{\n    char service[6];\n    struct addrinfo hints;\n    int rc;\n\n    if (xsock->ainfo_list) {\n        freeaddrinfo(xsock->ainfo_list);\n        xsock->ainfo_list = NULL;\n    }\n\n    if (xsock->srv_rr_cur) {\n        /* Cache host and port for debug logs. */\n        xsock->host = xsock->srv_rr_cur->target;\n        xsock->port = xsock->srv_rr_cur->port;\n\n        strophe_snprintf(service, 6, \"%u\", xsock->srv_rr_cur->port);\n        memset(&hints, 0, sizeof(struct addrinfo));\n        hints.ai_family = AF_UNSPEC;\n#ifdef AI_ADDRCONFIG\n        hints.ai_flags = AI_ADDRCONFIG;\n#endif /* AI_ADDRCONFIG */\n        hints.ai_protocol = IPPROTO_TCP;\n        hints.ai_socktype = SOCK_STREAM;\n\n        rc = getaddrinfo(xsock->srv_rr_cur->target, service, &hints,\n                         &xsock->ainfo_list);\n        if (rc != 0) {\n            strophe_debug(xsock->ctx, \"sock\",\n                          \"getaddrinfo() failed with %s (%d)\", gai_strerror(rc),\n                          rc);\n            xsock->ainfo_list = NULL;\n        }\n    }\n\n    xsock->ainfo_cur = xsock->ainfo_list;\n}\n\nxmpp_sock_t *sock_new(xmpp_conn_t *conn,\n                      const char *domain,\n                      const char *host,\n                      unsigned short port)\n{\n    xmpp_ctx_t *ctx = conn->ctx;\n    xmpp_sock_t *xsock;\n    int found = XMPP_DOMAIN_NOT_FOUND;\n\n    xsock = strophe_alloc(ctx, sizeof(*xsock));\n    if (!xsock) {\n        return NULL;\n    }\n\n    xsock->ctx = ctx;\n    xsock->conn = conn;\n    xsock->host = NULL;\n    xsock->port = 0;\n\n    if (!host) {\n        found = resolver_srv_lookup(ctx, \"xmpp-client\", \"tcp\", domain,\n                                    &xsock->srv_rr_list);\n        if (XMPP_DOMAIN_NOT_FOUND == found)\n            strophe_debug(ctx, \"sock\",\n                          \"SRV lookup failed, connecting via domain.\");\n    }\n    if (XMPP_DOMAIN_NOT_FOUND == found) {\n        /* Resolution failed or the host is provided explicitly. */\n        xsock->srv_rr_list =\n            resolver_srv_rr_new(ctx, host ? host : domain, port, 0, 0);\n    }\n    xsock->srv_rr_cur = xsock->srv_rr_list;\n\n    xsock->ainfo_list = NULL;\n    sock_getaddrinfo(xsock);\n    if (xsock->srv_rr_cur)\n        xsock->srv_rr_cur = xsock->srv_rr_cur->next;\n\n    return xsock;\n}\n\nvoid sock_free(xmpp_sock_t *xsock)\n{\n    if (!xsock)\n        return;\n\n    if (xsock->ainfo_list)\n        freeaddrinfo(xsock->ainfo_list);\n    if (xsock->srv_rr_list)\n        resolver_srv_free(xsock->ctx, xsock->srv_rr_list);\n    strophe_free(xsock->ctx, xsock);\n}\n\nstatic const char *_sockaddr2str(struct sockaddr *sa, char *buf, size_t buflen)\n{\n    buf[0] = '\\0';\n\n    switch (sa->sa_family) {\n    case AF_INET:\n        inet_ntop(AF_INET, &((struct sockaddr_in *)sa)->sin_addr, buf, buflen);\n        break;\n    case AF_INET6:\n        inet_ntop(AF_INET6, &((struct sockaddr_in6 *)sa)->sin6_addr, buf,\n                  buflen);\n        break;\n    default:\n        strophe_snprintf(buf, buflen, \"<Unknown>\");\n    }\n    return buf;\n}\n\nsock_t sock_connect(xmpp_sock_t *xsock)\n{\n    struct addrinfo *ainfo;\n    sock_t sock;\n    int rc;\n    char buf[64];\n\n    do {\n        if (!xsock->ainfo_cur) {\n            sock_getaddrinfo(xsock);\n            if (xsock->srv_rr_cur)\n                xsock->srv_rr_cur = xsock->srv_rr_cur->next;\n        }\n        if (!xsock->ainfo_cur) {\n            /* We tried all available addresses. */\n            return INVALID_SOCKET;\n        }\n\n        ainfo = xsock->ainfo_cur;\n        strophe_debug(xsock->ctx, \"sock\", \"Connecting to %s:%u via %s\",\n                      xsock->host, xsock->port,\n                      _sockaddr2str(ainfo->ai_addr, buf, sizeof(buf)));\n\n        sock = socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol);\n        if (sock != INVALID_SOCKET) {\n            rc = 0;\n            if (xsock->conn->sockopt_cb) {\n                /* Don't allow user to overwrite sockfd value. */\n                sock_t sock_copy = sock;\n                rc = xsock->conn->sockopt_cb(xsock->conn, &sock_copy);\n                if (rc != 0) {\n                    strophe_debug(xsock->ctx, \"sock\",\n                                  \"User's setsockopt callback\"\n                                  \" failed with %d (errno=%d)\",\n                                  rc, errno);\n                }\n            }\n            if (rc == 0)\n                rc = sock_set_nonblocking(sock);\n            if (rc == 0)\n                rc = connect(sock, ainfo->ai_addr, ainfo->ai_addrlen);\n            /* Assume only connect() can cause \"in progress\" error. */\n            if (rc != 0 && !_in_progress(sock_error(NULL))) {\n                sock_close(sock);\n                sock = INVALID_SOCKET;\n            }\n        }\n        strophe_debug(xsock->ctx, \"sock\", \"sock_connect() result %d\", sock);\n\n        xsock->ainfo_cur = xsock->ainfo_cur->ai_next;\n    } while (sock == INVALID_SOCKET);\n\n    return sock;\n}\n\nint sock_set_keepalive(sock_t sock,\n                       int timeout,\n                       int interval,\n                       int count,\n                       unsigned int user_timeout)\n{\n    int ret;\n    int optval = (timeout && interval) ? 1 : 0;\n\n    UNUSED(count);\n    UNUSED(user_timeout);\n\n#ifdef _WIN32\n    struct tcp_keepalive ka;\n    DWORD dw = 0;\n\n    ka.onoff = optval;\n    ka.keepalivetime = timeout * 1000;\n    ka.keepaliveinterval = interval * 1000;\n    ret = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &ka, sizeof(ka), NULL, 0, &dw,\n                   NULL, NULL);\n#else\n    ret = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));\n    if (ret < 0)\n        return ret;\n\n    if (optval) {\n#ifdef TCP_KEEPIDLE\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPIDLE, &timeout,\n                         sizeof(timeout));\n#elif defined(TCP_KEEPALIVE)\n        /* QNX receives `struct timeval' as argument, but it seems OSX does int\n         */\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPALIVE, &timeout,\n                         sizeof(timeout));\n#endif /* TCP_KEEPIDLE */\n        if (ret < 0)\n            return ret;\n#ifdef TCP_KEEPINTVL\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPINTVL, &interval,\n                         sizeof(interval));\n        if (ret < 0)\n            return ret;\n#endif /* TCP_KEEPINTVL */\n    }\n\n    if (count) {\n#ifdef TCP_KEEPCNT\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_KEEPCNT, &count, sizeof(count));\n        if (ret < 0)\n            return ret;\n#endif /* TCP_KEEPCNT */\n    }\n\n    if (user_timeout) {\n#ifdef TCP_USER_TIMEOUT\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_USER_TIMEOUT, &user_timeout,\n                         sizeof(user_timeout));\n        if (ret < 0)\n            return ret;\n#elif defined(TCP_RXT_CONNDROPTIME)\n        int rxt = user_timeout / 1000;\n        ret = setsockopt(sock, IPPROTO_TCP, TCP_RXT_CONNDROPTIME, &rxt,\n                         sizeof(rxt));\n        if (ret < 0)\n            return ret;\n#endif /* TCP_USER_TIMEOUT */\n    }\n\n#endif /* _WIN32 */\n\n    return ret;\n}\n\n/** Example sockopt callback function\n *  An example function that can be used to set reasonable default keepalive\n *  options on sockets when registered for a connection with\n *  xmpp_conn_set_sockopt_callback()\n *\n *  @param conn a Strophe connection object\n *  @param socket pointer to a socket descriptor\n *\n *  @see xmpp_sockopt_callback for details on the `socket` parameter\n *  @ingroup Connections\n */\nint xmpp_sockopt_cb_keepalive(xmpp_conn_t *conn, void *socket)\n{\n    sock_t sock = *((sock_t *)socket);\n\n    return sock_set_keepalive(\n        sock, conn->ka_timeout, conn->ka_interval, conn->ka_count,\n        conn->ka_count\n            ? (conn->ka_timeout + conn->ka_interval * conn->ka_count) * 1000\n            : 0);\n}\n\nint sock_close(sock_t sock)\n{\n#ifdef _WIN32\n    return closesocket(sock);\n#else\n    return close(sock);\n#endif\n}\n\nstatic int _sock_set_blocking_mode(sock_t sock, int blocking)\n{\n#ifdef _WIN32\n    u_long nonblock = blocking ? 0 : 1;\n    return ioctlsocket(sock, FIONBIO, &nonblock);\n#else\n    int rc;\n\n    rc = fcntl(sock, F_GETFL, NULL);\n    if (rc >= 0) {\n        rc = blocking ? rc & (~O_NONBLOCK) : rc | O_NONBLOCK;\n        rc = fcntl(sock, F_SETFL, rc);\n    }\n    return rc;\n#endif\n}\n\nint sock_set_blocking(sock_t sock)\n{\n    return _sock_set_blocking_mode(sock, 1);\n}\n\nint sock_set_nonblocking(sock_t sock)\n{\n    return _sock_set_blocking_mode(sock, 0);\n}\n\nint sock_read(struct conn_interface *intf, void *buff, size_t len)\n{\n    return recv(intf->conn->sock, buff, len, 0);\n}\n\nint sock_write(struct conn_interface *intf, const void *buff, size_t len)\n{\n    return send(intf->conn->sock, buff, len, 0);\n}\n\nint sock_is_recoverable(struct conn_interface *intf, int error)\n{\n    UNUSED(intf);\n#ifdef _WIN32\n    return (error == WSAEINTR || error == WSAEWOULDBLOCK ||\n            error == WSAEINPROGRESS);\n#else\n    return (error == EAGAIN || error == EINTR);\n#endif\n}\n\nint sock_connect_error(sock_t sock)\n{\n    struct sockaddr_storage ss;\n    struct sockaddr *sa = (struct sockaddr *)&ss;\n    socklen_t len;\n    char temp;\n\n    memset(&ss, 0, sizeof(ss));\n    len = sizeof(ss);\n    sa->sa_family = AF_UNSPEC;\n\n    /* we don't actually care about the peer name, we're just checking if\n     * we're connected or not */\n    if (getpeername(sock, sa, &len) == 0) {\n        return 0;\n    }\n\n    /* it's possible that the error wasn't ENOTCONN, so if it wasn't,\n     * return that */\n#ifdef _WIN32\n    if (sock_error(NULL) != WSAENOTCONN)\n        return sock_error(NULL);\n#else\n    if (sock_error(NULL) != ENOTCONN)\n        return sock_error(NULL);\n#endif\n\n    /* load the correct error into errno through error slippage */\n    recv(sock, &temp, 1, 0);\n\n    return sock_error(NULL);\n}\n"
  },
  {
    "path": "src/sock.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* sock.h\n** strophe XMPP client library -- socket abstraction header\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Socket abstraction API.\n */\n\n#ifndef __LIBSTROPHE_SOCK_H__\n#define __LIBSTROPHE_SOCK_H__\n\n#include <stdio.h>\n\n#ifndef _WIN32\ntypedef int sock_t;\n#define INVALID_SOCKET (-1)\n#else\n#include <winsock2.h>\n#include <ws2tcpip.h>\n#include <iphlpapi.h>\n#include <mstcpip.h> /* tcp_keepalive */\ntypedef SOCKET sock_t;\n#endif\n\nextern const struct conn_interface sock_intf;\n\ntypedef struct _xmpp_sock_t xmpp_sock_t;\n\nvoid sock_initialize(void);\nvoid sock_shutdown(void);\n\nint sock_error(struct conn_interface *intf);\n\nxmpp_sock_t *sock_new(xmpp_conn_t *conn,\n                      const char *domain,\n                      const char *host,\n                      unsigned short port);\nvoid sock_free(xmpp_sock_t *xsock);\nsock_t sock_connect(xmpp_sock_t *xsock);\nint sock_close(sock_t sock);\n\nint sock_set_blocking(sock_t sock);\nint sock_set_nonblocking(sock_t sock);\nint sock_read(struct conn_interface *intf, void *buff, size_t len);\nint sock_write(struct conn_interface *intf, const void *buff, size_t len);\nint sock_is_recoverable(struct conn_interface *intf, int error);\n/* checks for an error after connect, return 0 if connect successful */\nint sock_connect_error(sock_t sock);\nint sock_set_keepalive(sock_t sock,\n                       int timeout,\n                       int interval,\n                       int count,\n                       unsigned int user_timeout);\n\n#endif /* __LIBSTROPHE_SOCK_H__ */\n"
  },
  {
    "path": "src/stanza.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* stanza.c\n** strophe XMPP client library -- XMPP stanza object and utilities\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Stanza creation and manipulation.\n */\n\n/** @defgroup Stanza Stanza creation and manipulation\n */\n\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"hash.h\"\n#include \"parser.h\"\n\n/** Create a stanza object.\n *  This function allocates and initializes a blank stanza object.\n *  The stanza will have a reference count of one, so the caller does not\n *  need to clone it.\n *\n *  @param ctx a Strophe context object\n *\n *  @return a stanza object\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_new(xmpp_ctx_t *ctx)\n{\n    xmpp_stanza_t *stanza;\n\n    stanza = strophe_alloc(ctx, sizeof(xmpp_stanza_t));\n    if (stanza != NULL) {\n        memset(stanza, 0, sizeof(xmpp_stanza_t));\n        stanza->ref = 1;\n        stanza->ctx = ctx;\n        stanza->type = XMPP_STANZA_UNKNOWN;\n    }\n\n    return stanza;\n}\n\n/** Clone a stanza object.\n *  This function increments the reference count of the stanza object.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return the stanza object with it's reference count incremented\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_clone(xmpp_stanza_t *stanza)\n{\n    stanza->ref++;\n\n    return stanza;\n}\n\n/*\n * Copy the attributes of stanza src into stanza dst. Return -1 on error.\n */\nstatic int _stanza_copy_attributes(xmpp_stanza_t *dst, const xmpp_stanza_t *src)\n{\n    hash_iterator_t *iter;\n    const char *key;\n    const char *val;\n    int rc = XMPP_EOK;\n\n    iter = hash_iter_new(src->attributes);\n    if (!iter)\n        rc = XMPP_EMEM;\n\n    while (rc == XMPP_EOK && (key = hash_iter_next(iter))) {\n        val = hash_get(src->attributes, key);\n        if (!val)\n            rc = XMPP_EINT;\n        if (rc == XMPP_EOK)\n            rc = xmpp_stanza_set_attribute(dst, key, val);\n    }\n    hash_iter_release(iter);\n\n    if (rc != XMPP_EOK && dst->attributes) {\n        hash_release(dst->attributes);\n        dst->attributes = NULL;\n    }\n    return rc;\n}\n\n/** Copy a stanza and its children.\n *  This function copies a stanza along with all its children and returns\n *  the new stanza and children with a reference count of 1.  The returned\n *  stanza will have no parent and no siblings.  This function is useful\n *  for extracting a child stanza for inclusion in another tree.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a new Strophe stanza object\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_copy(const xmpp_stanza_t *stanza)\n{\n    xmpp_stanza_t *copy, *child, *copychild, *tail;\n\n    copy = xmpp_stanza_new(stanza->ctx);\n    if (!copy)\n        goto copy_error;\n\n    copy->type = stanza->type;\n\n    if (stanza->data) {\n        copy->data = strophe_strdup(stanza->ctx, stanza->data);\n        if (!copy->data)\n            goto copy_error;\n    }\n\n    if (stanza->attributes) {\n        if (_stanza_copy_attributes(copy, stanza) == -1)\n            goto copy_error;\n    }\n\n    tail = copy->children;\n    for (child = stanza->children; child; child = child->next) {\n        copychild = xmpp_stanza_copy(child);\n        if (!copychild)\n            goto copy_error;\n        copychild->parent = copy;\n\n        if (tail) {\n            copychild->prev = tail;\n            tail->next = copychild;\n        } else\n            copy->children = copychild;\n        tail = copychild;\n    }\n\n    return copy;\n\ncopy_error:\n    /* release all the hitherto allocated memory */\n    if (copy)\n        xmpp_stanza_release(copy);\n    return NULL;\n}\n\n/** Release a stanza object and all of its children.\n *  This function releases a stanza object and potentially all of its\n *  children, which may cause the object(s) to be freed.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return TRUE if the object was freed and FALSE otherwise\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_release(xmpp_stanza_t *stanza)\n{\n    int released = 0;\n    xmpp_stanza_t *child, *tchild;\n\n    /* release stanza */\n    if (stanza->ref > 1)\n        stanza->ref--;\n    else {\n        /* release all children */\n        child = stanza->children;\n        while (child) {\n            tchild = child;\n            child = child->next;\n            tchild->next = NULL;\n            xmpp_stanza_release(tchild);\n        }\n\n        if (stanza->attributes)\n            hash_release(stanza->attributes);\n        if (stanza->data)\n            strophe_free(stanza->ctx, stanza->data);\n        strophe_free(stanza->ctx, stanza);\n        released = 1;\n    }\n\n    return released;\n}\n\n/** Get the strophe context that the stanza is associated with.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a Strophe context\n *\n *  @ingroup Stanza\n */\nxmpp_ctx_t *xmpp_stanza_get_context(const xmpp_stanza_t *stanza)\n{\n    return stanza->ctx;\n}\n\n/** Determine if a stanza is a text node.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return TRUE if the stanza is a text node, FALSE otherwise\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_is_text(xmpp_stanza_t *stanza)\n{\n    return (stanza && stanza->type == XMPP_STANZA_TEXT);\n}\n\n/** Determine if a stanza is a tag node.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return TRUE if the stanza is a tag node, FALSE otherwise\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_is_tag(xmpp_stanza_t *stanza)\n{\n    return (stanza && stanza->type == XMPP_STANZA_TAG);\n}\n\n/* Escape a string with for use in a XML text node or attribute. Assumes that\n * the input string is encoded in UTF-8. On success, returns a pointer to a\n * buffer with the resulting data which must be xmpp_free()'d by the caller.\n * On failure, returns NULL.\n */\n\nstatic char *_escape_xml(xmpp_ctx_t *ctx, char *text)\n{\n    size_t len = 0;\n    char *src;\n    char *dst;\n    char *buf;\n    for (src = text; *src != '\\0'; src++) {\n        switch (*src) {\n        case '<': /* \"&lt;\" */\n        case '>': /* \"&gt;\" */\n            len += 4;\n            break;\n        case '&': /* \"&amp;\" */\n            len += 5;\n            break;\n        case '\"':\n            len += 6; /*\"&quot;\" */\n            break;\n        default:\n            len++;\n        }\n    }\n    if ((buf = strophe_alloc(ctx, (len + 1) * sizeof(char))) == NULL)\n        return NULL; /* Error */\n    dst = buf;\n    for (src = text; *src != '\\0'; src++) {\n        switch (*src) {\n        case '<':\n            strcpy(dst, \"&lt;\");\n            dst += 4;\n            break;\n        case '>':\n            strcpy(dst, \"&gt;\");\n            dst += 4;\n            break;\n        case '&':\n            strcpy(dst, \"&amp;\");\n            dst += 5;\n            break;\n        case '\"':\n            strcpy(dst, \"&quot;\");\n            dst += 6;\n            break;\n        default:\n            *dst = *src;\n            dst++;\n        }\n    }\n    *dst = '\\0';\n    return buf;\n}\n\n/* small helper function */\nstatic void _render_update(\n    int *written, int length, int lastwrite, size_t *left, char **ptr)\n{\n    *written += lastwrite;\n\n    if (*written >= length) {\n        *left = 0;\n        *ptr = NULL;\n    } else {\n        *left -= lastwrite;\n        *ptr = &(*ptr)[lastwrite];\n    }\n}\n\n/* always returns number of bytes written or that would have been\n * written if the buffer was large enough\n * return values < 0 indicate some error occurred,\n * and return values > buflen indicate buffer was not large enough\n */\nstatic int\n_render_stanza_recursive(xmpp_stanza_t *stanza, char *buf, size_t buflen)\n{\n    char *ptr = buf;\n    size_t left = buflen;\n    int ret, written;\n    xmpp_stanza_t *child;\n    hash_iterator_t *iter;\n    const char *key;\n    char *tmp;\n\n    written = 0;\n\n    if (stanza->type == XMPP_STANZA_UNKNOWN)\n        return XMPP_EINVOP;\n\n    if (stanza->type == XMPP_STANZA_TEXT) {\n        if (!stanza->data)\n            return XMPP_EINVOP;\n\n        tmp = _escape_xml(stanza->ctx, stanza->data);\n        if (tmp == NULL)\n            return XMPP_EMEM;\n        ret = strophe_snprintf(ptr, left, \"%s\", tmp);\n        strophe_free(stanza->ctx, tmp);\n        if (ret < 0)\n            return XMPP_EMEM;\n        _render_update(&written, buflen, ret, &left, &ptr);\n    } else { /* stanza->type == XMPP_STANZA_TAG */\n        if (!stanza->data)\n            return XMPP_EINVOP;\n\n        /* write beginning of tag and attributes */\n        ret = strophe_snprintf(ptr, left, \"<%s\", stanza->data);\n        if (ret < 0)\n            return XMPP_EMEM;\n        _render_update(&written, buflen, ret, &left, &ptr);\n\n        if (stanza->attributes && hash_num_keys(stanza->attributes) > 0) {\n            iter = hash_iter_new(stanza->attributes);\n            while ((key = hash_iter_next(iter))) {\n                if (!strcmp(key, \"xmlns\")) {\n                    /* don't output namespace if parent stanza is the same */\n                    if (stanza->parent && stanza->parent->attributes &&\n                        hash_get(stanza->parent->attributes, key) &&\n                        !strcmp(\n                            (char *)hash_get(stanza->attributes, key),\n                            (char *)hash_get(stanza->parent->attributes, key)))\n                        continue;\n                    /* or if this is the stream namespace */\n                    if (!stanza->parent &&\n                        !strcmp((char *)hash_get(stanza->attributes, key),\n                                XMPP_NS_CLIENT))\n                        continue;\n                }\n                tmp = _escape_xml(stanza->ctx,\n                                  (char *)hash_get(stanza->attributes, key));\n                if (tmp == NULL) {\n                    hash_iter_release(iter);\n                    return XMPP_EMEM;\n                }\n                ret = strophe_snprintf(ptr, left, \" %s=\\\"%s\\\"\", key, tmp);\n                strophe_free(stanza->ctx, tmp);\n                if (ret < 0) {\n                    hash_iter_release(iter);\n                    return XMPP_EMEM;\n                }\n                _render_update(&written, buflen, ret, &left, &ptr);\n            }\n            hash_iter_release(iter);\n        }\n\n        if (!stanza->children) {\n            /* write end if singleton tag */\n            ret = strophe_snprintf(ptr, left, \"/>\");\n            if (ret < 0)\n                return XMPP_EMEM;\n            _render_update(&written, buflen, ret, &left, &ptr);\n        } else {\n            /* this stanza has child stanzas */\n\n            /* write end of start tag */\n            ret = strophe_snprintf(ptr, left, \">\");\n            if (ret < 0)\n                return XMPP_EMEM;\n            _render_update(&written, buflen, ret, &left, &ptr);\n\n            /* iterate and recurse over child stanzas */\n            child = stanza->children;\n            while (child) {\n                ret = _render_stanza_recursive(child, ptr, left);\n                if (ret < 0)\n                    return ret;\n\n                _render_update(&written, buflen, ret, &left, &ptr);\n\n                child = child->next;\n            }\n\n            /* write end tag */\n            ret = strophe_snprintf(ptr, left, \"</%s>\", stanza->data);\n            if (ret < 0)\n                return XMPP_EMEM;\n\n            _render_update(&written, buflen, ret, &left, &ptr);\n        }\n    }\n\n    return written;\n}\n\n/** Render a stanza object to text.\n *  This function renders a given stanza object, along with its\n *  children, to text.  The text is returned in an allocated,\n *  null-terminated buffer.  It starts by allocating a 1024 byte buffer\n *  and reallocates more memory if that is not large enough.\n *\n *  @param stanza a Strophe stanza object\n *  @param buf a reference to a string pointer\n *  @param buflen a reference to a size_t\n *\n *  @return 0 on success (XMPP_EOK), and a number less than 0 on failure\n *      (XMPP_EMEM, XMPP_EINVOP)\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_to_text(xmpp_stanza_t *stanza, char **buf, size_t *buflen)\n{\n    char *buffer, *tmp;\n    size_t length;\n    int ret;\n\n    /* allocate a default sized buffer and attempt to render */\n    length = 1024;\n    buffer = strophe_alloc(stanza->ctx, length);\n    if (!buffer) {\n        *buf = NULL;\n        *buflen = 0;\n        return XMPP_EMEM;\n    }\n\n    ret = _render_stanza_recursive(stanza, buffer, length);\n    if (ret < 0) {\n        strophe_free(stanza->ctx, buffer);\n        *buf = NULL;\n        *buflen = 0;\n        return ret;\n    }\n\n    if ((size_t)ret > length - 1) {\n        tmp = strophe_realloc(stanza->ctx, buffer, ret + 1);\n        if (!tmp) {\n            strophe_free(stanza->ctx, buffer);\n            *buf = NULL;\n            *buflen = 0;\n            return XMPP_EMEM;\n        }\n        length = ret + 1;\n        buffer = tmp;\n\n        ret = _render_stanza_recursive(stanza, buffer, length);\n        if ((size_t)ret > length - 1) {\n            strophe_free(stanza->ctx, buffer);\n            *buf = NULL;\n            *buflen = 0;\n            return XMPP_EMEM;\n        }\n    }\n\n    buffer[length - 1] = 0;\n\n    *buf = buffer;\n    *buflen = ret;\n\n    return XMPP_EOK;\n}\n\n/** Set the name of a stanza.\n *\n *  @param stanza a Strophe stanza object\n *  @param name a string with the name of the stanza\n *\n *  @return XMPP_EOK on success, a number less than 0 on failure (XMPP_EMEM,\n *      XMPP_EINVOP)\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_name(xmpp_stanza_t *stanza, const char *name)\n{\n    if (stanza->type == XMPP_STANZA_TEXT)\n        return XMPP_EINVOP;\n\n    if (stanza->data)\n        strophe_free(stanza->ctx, stanza->data);\n\n    stanza->type = XMPP_STANZA_TAG;\n    stanza->data = strophe_strdup(stanza->ctx, name);\n\n    return stanza->data == NULL ? XMPP_EMEM : XMPP_EOK;\n}\n\n/** Get the stanza name.\n *  This function returns a pointer to the stanza name.  If the caller needs\n *  to store this data, it must make a copy.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a string with the stanza name\n *\n *  @ingroup Stanza\n */\nconst char *xmpp_stanza_get_name(xmpp_stanza_t *stanza)\n{\n    if (stanza->type == XMPP_STANZA_TEXT)\n        return NULL;\n    return stanza->data;\n}\n\n/** Count the attributes in a stanza object.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return the number of attributes for the stanza object\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_get_attribute_count(xmpp_stanza_t *stanza)\n{\n    if (stanza->attributes == NULL) {\n        return 0;\n    }\n\n    return hash_num_keys(stanza->attributes);\n}\n\n/** Get all attributes for a stanza object.\n *  This function populates the array with attributes from the stanza.  The\n *  attr array will be in the format:  attr[i] = attribute name,\n *  attr[i+1] = attribute value.\n *\n *  @param stanza a Strophe stanza object\n *  @param attr the string array to populate\n *  @param attrlen the size of the array\n *\n *  @return the number of slots used in the array, which will be 2 times the\n *      number of attributes in the stanza\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_get_attributes(xmpp_stanza_t *stanza,\n                               const char **attr,\n                               int attrlen)\n{\n    hash_iterator_t *iter;\n    const char *key;\n    int num = 0;\n\n    if (stanza->attributes == NULL) {\n        return 0;\n    }\n\n    iter = hash_iter_new(stanza->attributes);\n    while ((key = hash_iter_next(iter)) != NULL && attrlen) {\n        attr[num++] = key;\n        attrlen--;\n        if (attrlen == 0) {\n            hash_iter_release(iter);\n            return num;\n        }\n        attr[num++] = hash_get(stanza->attributes, key);\n        attrlen--;\n        if (attrlen == 0) {\n            hash_iter_release(iter);\n            return num;\n        }\n    }\n\n    hash_iter_release(iter);\n    return num;\n}\n\n/** Set an attribute for a stanza object.\n *\n *  @param stanza a Strophe stanza object\n *  @param key a string with the attribute name\n *  @param value a string with the attribute value\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_attribute(xmpp_stanza_t *stanza,\n                              const char *key,\n                              const char *value)\n{\n    char *val;\n    int rc;\n\n    if (stanza->type != XMPP_STANZA_TAG)\n        return XMPP_EINVOP;\n\n    if (!stanza->attributes) {\n        stanza->attributes = hash_new(stanza->ctx, 8, strophe_free);\n        if (!stanza->attributes)\n            return XMPP_EMEM;\n    }\n\n    val = strophe_strdup(stanza->ctx, value);\n    if (!val) {\n        return XMPP_EMEM;\n    }\n\n    rc = hash_add(stanza->attributes, key, val);\n    if (rc < 0) {\n        strophe_free(stanza->ctx, val);\n        return XMPP_EMEM;\n    }\n\n    return XMPP_EOK;\n}\n\n/** Set the stanza namespace.\n *  This is a convenience function equivalent to calling:\n *  xmpp_stanza_set_attribute(stanza, \"xmlns\", ns);\n *\n *  @param stanza a Strophe stanza object\n *  @param ns a string with the namespace\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_ns(xmpp_stanza_t *stanza, const char *ns)\n{\n    return xmpp_stanza_set_attribute(stanza, \"xmlns\", ns);\n}\n\n/** Add a child stanza to a stanza object.\n *  If do_clone is TRUE, user keeps reference to the child stanza and must call\n *  xmpp_stanza_release() to release the reference. If do_clone is FALSE, user\n *  transfers ownership and must not neither call xmpp_stanza_release() for\n *  the child stanza nor use it.\n *\n *  @param stanza a Strophe stanza object\n *  @param child the child stanza object\n *  @param do_clone TRUE to increase ref count of child (default for\n *                  xmpp_stanza_add_child())\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_add_child_ex(xmpp_stanza_t *stanza,\n                             xmpp_stanza_t *child,\n                             int do_clone)\n{\n    xmpp_stanza_t *s;\n\n    if (do_clone) {\n        /* get a reference to the child */\n        xmpp_stanza_clone(child);\n    }\n\n    child->parent = stanza;\n\n    if (!stanza->children)\n        stanza->children = child;\n    else {\n        s = stanza->children;\n        while (s->next)\n            s = s->next;\n        s->next = child;\n        child->prev = s;\n    }\n\n    return XMPP_EOK;\n}\n\n/** Add a child stanza to a stanza object.\n *  This function clones the child and appends it to the stanza object's\n *  children.\n *\n *  @param stanza a Strophe stanza object\n *  @param child the child stanza object\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_add_child(xmpp_stanza_t *stanza, xmpp_stanza_t *child)\n{\n    return xmpp_stanza_add_child_ex(stanza, child, 1);\n}\n\n/** Set the text data for a text stanza.\n *  This function copies the text given and sets the stanza object's text to\n *  it.  Attempting to use this function on a stanza that has a name will\n *  fail with XMPP_EINVOP.  This function takes the text as a null-terminated\n *  string.\n *\n *  @param stanza a Strophe stanza object\n *  @param text a string with the text\n *\n *  @return XMPP_EOK (0) on success or a number less than zero on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_text(xmpp_stanza_t *stanza, const char *text)\n{\n    if (stanza->type == XMPP_STANZA_TAG)\n        return XMPP_EINVOP;\n\n    stanza->type = XMPP_STANZA_TEXT;\n\n    if (stanza->data)\n        strophe_free(stanza->ctx, stanza->data);\n    stanza->data = strophe_strdup(stanza->ctx, text);\n\n    return stanza->data == NULL ? XMPP_EMEM : XMPP_EOK;\n}\n\n/** Set the text data for a text stanza.\n *  This function copies the text given and sets the stanza object's text to\n *  it.  Attempting to use this function on a stanza that has a name will\n *  fail with XMPP_EINVOP.  This function takes the text as buffer and a length\n *  as opposed to a null-terminated string.\n *\n *  @param stanza a Strophe stanza object\n *  @param text a buffer with the text\n *  @param size the length of the text\n *\n *  @return XMPP_EOK (0) on success and a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_text_with_size(xmpp_stanza_t *stanza,\n                                   const char *text,\n                                   size_t size)\n{\n    if (stanza->type == XMPP_STANZA_TAG)\n        return XMPP_EINVOP;\n\n    stanza->type = XMPP_STANZA_TEXT;\n\n    if (stanza->data)\n        strophe_free(stanza->ctx, stanza->data);\n    stanza->data = strophe_alloc(stanza->ctx, size + 1);\n    if (!stanza->data)\n        return XMPP_EMEM;\n\n    memcpy(stanza->data, text, size);\n    stanza->data[size] = 0;\n\n    return XMPP_EOK;\n}\n\n/** Get the 'id' attribute of the stanza object.\n *  This is a convenience function equivalent to:\n *  xmpp_stanza_get_attribute(stanza, \"id\");\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a string with the 'id' attribute value\n *\n *  @ingroup Stanza\n */\nconst char *xmpp_stanza_get_id(xmpp_stanza_t *stanza)\n{\n    return xmpp_stanza_get_attribute(stanza, \"id\");\n}\n\n/** Get the namespace attribute of the stanza object.\n *  This is a convenience function equivalent to:\n *  xmpp_stanza_get_attribute(stanza, \"xmlns\");\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a string with the 'xmlns' attribute value\n *\n *  @ingroup Stanza\n */\nconst char *xmpp_stanza_get_ns(xmpp_stanza_t *stanza)\n{\n    return xmpp_stanza_get_attribute(stanza, \"xmlns\");\n}\n\n/** Get the 'type' attribute of the stanza object.\n *  This is a convenience function equivalent to:\n *  xmpp_stanza_get_attribute(stanza, \"type\");\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a string with the 'type' attribute value\n *\n *  @ingroup Stanza\n */\nconst char *xmpp_stanza_get_type(xmpp_stanza_t *stanza)\n{\n    return xmpp_stanza_get_attribute(stanza, \"type\");\n}\n\n/** Get the 'to' attribute of the stanza object.\n *  This is a convenience function equivalent to:\n *  xmpp_stanza_get_attribute(stanza, \"to\");\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a string with the 'to' attribute value\n *\n *  @ingroup Stanza\n */\nconst char *xmpp_stanza_get_to(xmpp_stanza_t *stanza)\n{\n    return xmpp_stanza_get_attribute(stanza, \"to\");\n}\n\n/** Get the 'from' attribute of the stanza object.\n *  This is a convenience function equivalent to:\n *  xmpp_stanza_get_attribute(stanza, \"from\");\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a string with the 'from' attribute value\n *\n *  @ingroup Stanza\n */\nconst char *xmpp_stanza_get_from(xmpp_stanza_t *stanza)\n{\n    return xmpp_stanza_get_attribute(stanza, \"from\");\n}\n\n/** Get the first child of stanza following a path-like list of names.\n *  This function searches the children and their children that match\n *  the given path.\n *\n *  * \"name\" - Search 'name'\n *\n *  * \"name[@ns='foo']\" - Search 'name' which is in the namespace 'foo'\n *\n *  The Syntax to pass namespaces is inspired by the XPATH way of passing\n *  attributes.\n *\n *  The namespace syntax only supports single quotes `'`.\n *\n *  The \\ref XMPP_STANZA_NAME_IN_NS macro is provided as a helper for names\n *  in namespaces.\n *\n *  @param stanza a Strophe stanza object\n *  @param ... a var-args list that must be terminated by a NULL entry\n *\n *  @return the matching child stanza object or NULL if no match was found\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_get_child_by_path(xmpp_stanza_t *stanza, ...)\n{\n    xmpp_stanza_t *child = NULL;\n    char *p, *tok, *attr, *saveattr, *ns = NULL;\n    const char *xmlns;\n    va_list ap;\n\n    va_start(ap, stanza);\n\n    while ((p = va_arg(ap, char *)) != NULL) {\n        tok = strophe_strdup(stanza->ctx, p);\n        if (!tok) {\n            child = NULL;\n            break;\n        }\n        saveattr = ns = NULL;\n        attr = strophe_strtok_r(tok, \"[\", &saveattr);\n        if (attr) {\n            attr = strophe_strtok_r(NULL, \"]\", &saveattr);\n            if (attr) {\n                if (!strncmp(attr, \"@ns='\", 5)) {\n                    ns = attr + 5;\n                    strophe_strtok_r(ns, \"'\", &saveattr);\n                }\n            }\n        }\n        if (!child) {\n            if (strcmp(xmpp_stanza_get_name(stanza), tok))\n                goto error_out;\n\n            if (ns) {\n                xmlns = xmpp_stanza_get_ns(stanza);\n                if (!xmlns || strcmp(xmlns, ns))\n                    goto error_out;\n            }\n            child = stanza;\n        } else {\n            if (!ns)\n                child = xmpp_stanza_get_child_by_name(child, tok);\n            else\n                child = xmpp_stanza_get_child_by_name_and_ns(child, tok, ns);\n        }\nerror_out:\n        strophe_free(stanza->ctx, tok);\n        if (!child)\n            break;\n    }\n\n    va_end(ap);\n\n    return p == NULL ? child : NULL;\n}\n\n/** Get the first child of stanza with name.\n *  This function searches all the immediate children of stanza for a child\n *  stanza that matches the name.  The first matching child is returned.\n *\n *  @param stanza a Strophe stanza object\n *  @param name a string with the name to match\n *\n *  @return the matching child stanza object or NULL if no match was found\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_get_child_by_name(xmpp_stanza_t *stanza,\n                                             const char *name)\n{\n    xmpp_stanza_t *child;\n\n    for (child = stanza->children; child; child = child->next) {\n        if (child->type == XMPP_STANZA_TAG &&\n            (strcmp(name, xmpp_stanza_get_name(child)) == 0))\n            break;\n    }\n\n    return child;\n}\n\n/** Get the first child of a stanza with a given namespace.\n *  This function searches all the immediate children of a stanza for a child\n *  stanza that matches the namespace provided.  The first matching child\n *  is returned.\n *\n *  @param stanza a Strophe stanza object\n *  @param ns a string with the namespace to match\n *\n *  @return the matching child stanza object or NULL if no match was found\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_get_child_by_ns(xmpp_stanza_t *stanza,\n                                           const char *ns)\n{\n    xmpp_stanza_t *child;\n    const char *child_ns;\n\n    for (child = stanza->children; child; child = child->next) {\n        child_ns = xmpp_stanza_get_ns(child);\n        if (child_ns && strcmp(ns, child_ns) == 0)\n            break;\n    }\n\n    return child;\n}\n\n/** Get the first child of stanza with name and a given namespace.\n *  This function searches all the immediate children of stanza for a child\n *  stanza that matches the name and namespace provided.\n *  The first matching child is returned.\n *\n *  @param stanza a Strophe stanza object\n *  @param name a string with the name to match\n *  @param ns a string with the namespace to match\n *\n *  @return the matching child stanza object or NULL if no match was found\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_get_child_by_name_and_ns(xmpp_stanza_t *stanza,\n                                                    const char *name,\n                                                    const char *ns)\n{\n    xmpp_stanza_t *child;\n    const char *child_ns;\n\n    for (child = stanza->children; child; child = child->next) {\n        if (child->type == XMPP_STANZA_TAG &&\n            (strcmp(name, xmpp_stanza_get_name(child)) == 0)) {\n            child_ns = xmpp_stanza_get_ns(child);\n            if (child_ns && strcmp(ns, child_ns) == 0) {\n                break;\n            }\n        }\n    }\n\n    return child;\n}\n\n/** Get the list of children.\n *  This function returns the first child of the stanza object.  The rest\n *  of the children can be obtained by calling xmpp_stanza_get_next() to\n *  iterate over the siblings.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return the first child stanza or NULL if there are no children\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_get_children(xmpp_stanza_t *stanza)\n{\n    return stanza->children;\n}\n\n/** Get the next sibling of a stanza.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return the next sibling stanza or NULL if there are no more siblings\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_get_next(xmpp_stanza_t *stanza)\n{\n    return stanza->next;\n}\n\n/** Get the text data for a text stanza.\n *  This function copies the text data from a stanza and returns the new\n *  allocated string.  The caller is responsible for freeing this string\n *  with xmpp_free().\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return an allocated string with the text data\n *\n *  @ingroup Stanza\n */\nchar *xmpp_stanza_get_text(xmpp_stanza_t *stanza)\n{\n    size_t len, clen;\n    xmpp_stanza_t *child;\n    char *text;\n\n    if (stanza->type == XMPP_STANZA_TEXT) {\n        if (stanza->data)\n            return strophe_strdup(stanza->ctx, stanza->data);\n        else\n            return NULL;\n    }\n\n    len = 0;\n    for (child = stanza->children; child; child = child->next)\n        if (child->type == XMPP_STANZA_TEXT)\n            len += strlen(child->data);\n\n    if (len == 0)\n        return NULL;\n\n    text = (char *)strophe_alloc(stanza->ctx, len + 1);\n    if (!text)\n        return NULL;\n\n    len = 0;\n    for (child = stanza->children; child; child = child->next)\n        if (child->type == XMPP_STANZA_TEXT) {\n            clen = strlen(child->data);\n            memcpy(&text[len], child->data, clen);\n            len += clen;\n        }\n\n    text[len] = 0;\n\n    return text;\n}\n\n/** Get the text data pointer for a text stanza.\n *  This function copies returns the raw pointer to the text data in the\n *  stanza.  This should only be used in very special cases where the\n *  caller needs to translate the datatype as this will save a double\n *  allocation.  The caller should not hold onto this pointer, and is\n *  responsible for allocating a copy if it needs one.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return an string pointer to the data or NULL\n *\n *  @ingroup Stanza\n */\nconst char *xmpp_stanza_get_text_ptr(xmpp_stanza_t *stanza)\n{\n    if (stanza->type == XMPP_STANZA_TEXT)\n        return stanza->data;\n    return NULL;\n}\n\n/** Set the 'id' attribute of a stanza.\n *\n *  This is a convenience function for:\n *  xmpp_stanza_set_attribute(stanza, 'id', id);\n *\n *  @param stanza a Strophe stanza object\n *  @param id a string containing the 'id' value\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_id(xmpp_stanza_t *stanza, const char *id)\n{\n    return xmpp_stanza_set_attribute(stanza, \"id\", id);\n}\n\n/** Set the 'type' attribute of a stanza.\n *  This is a convenience function for:\n *  xmpp_stanza_set_attribute(stanza, 'type', type);\n *\n *  @param stanza a Strophe stanza object\n *  @param type a string containing the 'type' value\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_type(xmpp_stanza_t *stanza, const char *type)\n{\n    return xmpp_stanza_set_attribute(stanza, \"type\", type);\n}\n\n/** Set the 'to' attribute of a stanza.\n *\n *  This is a convenience function for:\n *  xmpp_stanza_set_attribute(stanza, 'to', to);\n *\n *  @param stanza a Strophe stanza object\n *  @param to a string containing the 'to' value\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_to(xmpp_stanza_t *stanza, const char *to)\n{\n    return xmpp_stanza_set_attribute(stanza, \"to\", to);\n}\n\n/** Set the 'from' attribute of a stanza.\n *\n *  This is a convenience function for:\n *  xmpp_stanza_set_attribute(stanza, 'from', from);\n *\n *  @param stanza a Strophe stanza object\n *  @param from a string containing the 'from' value\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_set_from(xmpp_stanza_t *stanza, const char *from)\n{\n    return xmpp_stanza_set_attribute(stanza, \"from\", from);\n}\n\n/** Get an attribute from a stanza.\n *  This function returns a pointer to the attribute value.  If the caller\n *  wishes to save this value it must make its own copy.\n *\n *  @param stanza a Strophe stanza object\n *  @param name a string containing attribute name\n *\n *  @return a string with the attribute value or NULL on an error\n *\n *  @ingroup Stanza\n */\nconst char *xmpp_stanza_get_attribute(xmpp_stanza_t *stanza, const char *name)\n{\n    if (stanza->type != XMPP_STANZA_TAG)\n        return NULL;\n\n    if (!stanza->attributes)\n        return NULL;\n\n    return hash_get(stanza->attributes, name);\n}\n\n/** Delete an attribute from a stanza.\n *\n *  @param stanza a Strophe stanza object\n *  @param name a string containing attribute name\n *\n *  @return XMPP_EOK (0) on success or a number less than 0 on failure\n *\n *  @ingroup Stanza\n */\nint xmpp_stanza_del_attribute(xmpp_stanza_t *stanza, const char *name)\n{\n    if (stanza->type != XMPP_STANZA_TAG)\n        return -1;\n\n    if (!stanza->attributes)\n        return -1;\n\n    return hash_drop(stanza->attributes, name);\n}\n\n/** Create a stanza object in reply to another.\n *  This function makes a copy of a stanza object with the attribute \"to\" set\n *  its original \"from\".\n *  The stanza will have a reference count of one, so the caller does not\n *  need to clone it.\n *\n *  @param stanza a Strophe stanza object\n *\n *  @return a new Strophe stanza object\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_reply(xmpp_stanza_t *stanza)\n{\n    xmpp_stanza_t *copy = NULL;\n    const char *from;\n    int rc;\n\n    from = xmpp_stanza_get_from(stanza);\n    if (!from)\n        goto copy_error;\n\n    copy = xmpp_stanza_new(stanza->ctx);\n    if (!copy)\n        goto copy_error;\n\n    copy->type = stanza->type;\n\n    if (stanza->data) {\n        copy->data = strophe_strdup(stanza->ctx, stanza->data);\n        if (!copy->data)\n            goto copy_error;\n    }\n\n    if (stanza->attributes) {\n        if (_stanza_copy_attributes(copy, stanza) < 0)\n            goto copy_error;\n    }\n\n    xmpp_stanza_del_attribute(copy, \"to\");\n    xmpp_stanza_del_attribute(copy, \"from\");\n    xmpp_stanza_del_attribute(copy, \"xmlns\");\n    rc = xmpp_stanza_set_to(copy, from);\n    if (rc != XMPP_EOK)\n        goto copy_error;\n\n    return copy;\n\ncopy_error:\n    if (copy)\n        xmpp_stanza_release(copy);\n    return NULL;\n}\n\n/** Create an error stanza in reply to the provided stanza.\n *\n *  Check https://tools.ietf.org/html/rfc6120#section-8.3 for details.\n *\n *  @param stanza a Strophe stanza object\n *  @param error_type type attribute in the `<error/>` child element\n *  @param condition the defined-condition (e.g. \"item-not-found\")\n *  @param text optional description, may be NULL\n *\n *  @return a new Strophe stanza object\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_reply_error(xmpp_stanza_t *stanza,\n                                       const char *error_type,\n                                       const char *condition,\n                                       const char *text)\n{\n    xmpp_ctx_t *ctx = stanza->ctx;\n    xmpp_stanza_t *reply = NULL;\n    xmpp_stanza_t *error = NULL;\n    xmpp_stanza_t *item = NULL;\n    xmpp_stanza_t *text_stanza = NULL;\n    const char *to;\n\n    if (!error_type || !condition)\n        goto quit_err;\n\n    reply = xmpp_stanza_reply(stanza);\n    if (!reply)\n        goto quit_err;\n    if (xmpp_stanza_set_type(reply, \"error\") != XMPP_EOK)\n        goto quit_err;\n    to = xmpp_stanza_get_to(stanza);\n    if (to)\n        if (xmpp_stanza_set_from(reply, to) != XMPP_EOK)\n            goto quit_err;\n\n    error = xmpp_stanza_new(ctx);\n    if (!error)\n        goto quit_err;\n    if (xmpp_stanza_set_name(error, \"error\") != XMPP_EOK)\n        goto quit_err;\n    if (xmpp_stanza_set_type(error, error_type) != XMPP_EOK)\n        goto quit_err;\n    if (xmpp_stanza_add_child(reply, error) != XMPP_EOK)\n        goto quit_err;\n    xmpp_stanza_release(error);\n\n    item = xmpp_stanza_new(ctx);\n    if (!item)\n        goto quit_err;\n    if (xmpp_stanza_set_name(item, condition) != XMPP_EOK)\n        goto quit_err;\n    if (xmpp_stanza_set_ns(item, XMPP_NS_STANZAS_IETF) != XMPP_EOK)\n        goto quit_err;\n    if (xmpp_stanza_add_child(error, item) != XMPP_EOK)\n        goto quit_err;\n    xmpp_stanza_release(item);\n\n    if (text) {\n        item = xmpp_stanza_new(ctx);\n        if (!item)\n            goto quit_err;\n        if (xmpp_stanza_set_name(item, \"text\") != XMPP_EOK)\n            goto quit_err;\n        if (xmpp_stanza_set_ns(item, XMPP_NS_STANZAS_IETF) != XMPP_EOK)\n            goto quit_err;\n        if (xmpp_stanza_add_child(error, item) != XMPP_EOK)\n            goto quit_err;\n        xmpp_stanza_release(item);\n        text_stanza = xmpp_stanza_new(ctx);\n        if (!text_stanza)\n            goto quit_err;\n        if (xmpp_stanza_set_text(text_stanza, text) != XMPP_EOK)\n            goto quit_err;\n        if (xmpp_stanza_add_child(item, text_stanza) != XMPP_EOK)\n            goto quit_err;\n        xmpp_stanza_release(text_stanza);\n    }\n\n    return reply;\n\nquit_err:\n    if (reply)\n        xmpp_stanza_release(reply);\n    if (error)\n        xmpp_stanza_release(error);\n    if (item)\n        xmpp_stanza_release(item);\n    if (text_stanza)\n        xmpp_stanza_release(text_stanza);\n    return NULL;\n}\n\nstatic xmpp_stanza_t *_stanza_new_with_attrs(xmpp_ctx_t *ctx,\n                                             const char *name,\n                                             const char *type,\n                                             const char *id,\n                                             const char *to)\n{\n    xmpp_stanza_t *stanza = xmpp_stanza_new(ctx);\n    int ret;\n\n    if (stanza) {\n        ret = xmpp_stanza_set_name(stanza, name);\n        if (ret == XMPP_EOK && type)\n            ret = xmpp_stanza_set_type(stanza, type);\n        if (ret == XMPP_EOK && id)\n            ret = xmpp_stanza_set_id(stanza, id);\n        if (ret == XMPP_EOK && to)\n            ret = xmpp_stanza_set_to(stanza, to);\n        if (ret != XMPP_EOK) {\n            xmpp_stanza_release(stanza);\n            stanza = NULL;\n        }\n    }\n    return stanza;\n}\n\n/** Create a `<message/>` stanza object with given attributes.\n *  Attributes are optional and may be NULL.\n *\n *  @param ctx a Strophe context object\n *  @param type attribute 'type'\n *  @param to attribute 'to'\n *  @param id attribute 'id'\n *\n *  @return a new Strophe stanza object\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_message_new(xmpp_ctx_t *ctx,\n                                const char *type,\n                                const char *to,\n                                const char *id)\n{\n    return _stanza_new_with_attrs(ctx, \"message\", type, id, to);\n}\n\n/** Get text from `<body/>` child element.\n *  This function returns new allocated string. The caller is responsible\n *  for freeing this string with xmpp_free().\n *\n *  @param msg well formed `<message/>` stanza\n *\n *  @return allocated string or NULL on failure (no `<body/>` element or\n *      memory allocation error)\n *\n *  @ingroup Stanza\n */\nchar *xmpp_message_get_body(xmpp_stanza_t *msg)\n{\n    xmpp_stanza_t *body;\n    const char *name;\n    char *text = NULL;\n\n    name = xmpp_stanza_get_name(msg);\n    body = xmpp_stanza_get_child_by_name(msg, \"body\");\n    if (name && strcmp(name, \"message\") == 0 && body) {\n        text = xmpp_stanza_get_text(body);\n    }\n    return text;\n}\n\n/** Add `<body/>` child element to a `<message/>` stanza with the given text.\n *\n *  @param msg a `<message>` stanza object without `<body/>` child element.\n *  @param text The text that shall be placed in the body.\n *\n *  @return 0 on success (XMPP_EOK), and a number less than 0 on failure\n *      (XMPP_EMEM, XMPP_EINVOP)\n *\n *  @ingroup Stanza\n */\nint xmpp_message_set_body(xmpp_stanza_t *msg, const char *text)\n{\n    xmpp_ctx_t *ctx = msg->ctx;\n    xmpp_stanza_t *body;\n    xmpp_stanza_t *text_stanza;\n    const char *name;\n    int ret;\n\n    /* check that msg is a `<message/>` stanza and doesn't contain `<body/>` */\n    name = xmpp_stanza_get_name(msg);\n    body = xmpp_stanza_get_child_by_name(msg, \"body\");\n    if (!name || strcmp(name, \"message\") != 0 || body)\n        return XMPP_EINVOP;\n\n    body = xmpp_stanza_new(ctx);\n    text_stanza = xmpp_stanza_new(ctx);\n\n    ret = body && text_stanza ? XMPP_EOK : XMPP_EMEM;\n    if (ret == XMPP_EOK)\n        ret = xmpp_stanza_set_name(body, \"body\");\n    if (ret == XMPP_EOK)\n        ret = xmpp_stanza_set_text(text_stanza, text);\n    if (ret == XMPP_EOK)\n        ret = xmpp_stanza_add_child(body, text_stanza);\n    if (ret == XMPP_EOK)\n        ret = xmpp_stanza_add_child(msg, body);\n\n    if (text_stanza)\n        xmpp_stanza_release(text_stanza);\n    if (body)\n        xmpp_stanza_release(body);\n\n    return ret;\n}\n\n/** Create an `<iq/>` stanza object with given attributes.\n *  Attributes are optional and may be NULL.\n *\n *  @param ctx a Strophe context object\n *  @param type attribute 'type'\n *  @param id attribute 'id'\n *\n *  @return a new Strophe stanza object\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_iq_new(xmpp_ctx_t *ctx, const char *type, const char *id)\n{\n    return _stanza_new_with_attrs(ctx, \"iq\", type, id, NULL);\n}\n\n/** Create a `<presence/>` stanza object.\n *\n *  @param ctx a Strophe context object\n *\n *  @return a new Strophe stanza object\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_presence_new(xmpp_ctx_t *ctx)\n{\n    return _stanza_new_with_attrs(ctx, \"presence\", NULL, NULL, NULL);\n}\n\n/** Create an <stream:error/> stanza object with given type and error text.\n *  The error text is optional and may be NULL.\n *\n *  @param ctx a Strophe context object\n *  @param type enum of strophe_error_type_t\n *  @param text content of a 'text'\n *\n *  @return a new Strophe stanza object\n *\n *  @todo Handle errors in this function\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *\nxmpp_error_new(xmpp_ctx_t *ctx, xmpp_error_type_t type, const char *text)\n{\n    xmpp_stanza_t *error =\n        _stanza_new_with_attrs(ctx, \"stream:error\", NULL, NULL, NULL);\n    xmpp_stanza_t *error_type = xmpp_stanza_new(ctx);\n\n    switch (type) {\n    case XMPP_SE_BAD_FORMAT:\n        xmpp_stanza_set_name(error_type, \"bad-format\");\n        break;\n    case XMPP_SE_BAD_NS_PREFIX:\n        xmpp_stanza_set_name(error_type, \"bad-namespace-prefix\");\n        break;\n    case XMPP_SE_CONFLICT:\n        xmpp_stanza_set_name(error_type, \"conflict\");\n        break;\n    case XMPP_SE_CONN_TIMEOUT:\n        xmpp_stanza_set_name(error_type, \"connection-timeout\");\n        break;\n    case XMPP_SE_HOST_GONE:\n        xmpp_stanza_set_name(error_type, \"host-gone\");\n        break;\n    case XMPP_SE_HOST_UNKNOWN:\n        xmpp_stanza_set_name(error_type, \"host-unknown\");\n        break;\n    case XMPP_SE_IMPROPER_ADDR:\n        xmpp_stanza_set_name(error_type, \"improper-addressing\");\n        break;\n    case XMPP_SE_INTERNAL_SERVER_ERROR:\n        xmpp_stanza_set_name(error_type, \"internal-server-error\");\n        break;\n    case XMPP_SE_INVALID_FROM:\n        xmpp_stanza_set_name(error_type, \"invalid-from\");\n        break;\n    case XMPP_SE_INVALID_ID:\n        xmpp_stanza_set_name(error_type, \"invalid-id\");\n        break;\n    case XMPP_SE_INVALID_NS:\n        xmpp_stanza_set_name(error_type, \"invalid-namespace\");\n        break;\n    case XMPP_SE_INVALID_XML:\n        xmpp_stanza_set_name(error_type, \"invalid-xml\");\n        break;\n    case XMPP_SE_NOT_AUTHORIZED:\n        xmpp_stanza_set_name(error_type, \"not-authorized\");\n        break;\n    case XMPP_SE_POLICY_VIOLATION:\n        xmpp_stanza_set_name(error_type, \"policy-violation\");\n        break;\n    case XMPP_SE_REMOTE_CONN_FAILED:\n        xmpp_stanza_set_name(error_type, \"remote-connection-failed\");\n        break;\n    case XMPP_SE_RESOURCE_CONSTRAINT:\n        xmpp_stanza_set_name(error_type, \"resource-constraint\");\n        break;\n    case XMPP_SE_RESTRICTED_XML:\n        xmpp_stanza_set_name(error_type, \"restricted-xml\");\n        break;\n    case XMPP_SE_SEE_OTHER_HOST:\n        xmpp_stanza_set_name(error_type, \"see-other-host\");\n        break;\n    case XMPP_SE_SYSTEM_SHUTDOWN:\n        xmpp_stanza_set_name(error_type, \"system-shutdown\");\n        break;\n    case XMPP_SE_UNDEFINED_CONDITION:\n        xmpp_stanza_set_name(error_type, \"undefined-condition\");\n        break;\n    case XMPP_SE_UNSUPPORTED_ENCODING:\n        xmpp_stanza_set_name(error_type, \"unsupported-encoding\");\n        break;\n    case XMPP_SE_UNSUPPORTED_STANZA_TYPE:\n        xmpp_stanza_set_name(error_type, \"unsupported-stanza-type\");\n        break;\n    case XMPP_SE_UNSUPPORTED_VERSION:\n        xmpp_stanza_set_name(error_type, \"unsupported-version\");\n        break;\n    case XMPP_SE_XML_NOT_WELL_FORMED:\n        xmpp_stanza_set_name(error_type, \"xml-not-well-formed\");\n        break;\n    default:\n        xmpp_stanza_set_name(error_type, \"internal-server-error\");\n        break;\n    }\n\n    xmpp_stanza_set_ns(error_type, XMPP_NS_STREAMS_IETF);\n    xmpp_stanza_add_child_ex(error, error_type, 0);\n\n    if (text) {\n        xmpp_stanza_t *error_text = xmpp_stanza_new(ctx);\n        xmpp_stanza_t *content = xmpp_stanza_new(ctx);\n\n        xmpp_stanza_set_name(error_text, \"text\");\n        xmpp_stanza_set_ns(error_text, XMPP_NS_STREAMS_IETF);\n\n        xmpp_stanza_set_text(content, text);\n        xmpp_stanza_add_child_ex(error_text, content, 0);\n\n        xmpp_stanza_add_child_ex(error, error_text, 0);\n    }\n\n    return error;\n}\n\nstatic void _stub_stream_start(char *name, char **attrs, void *userdata)\n{\n    UNUSED(name);\n    UNUSED(attrs);\n    UNUSED(userdata);\n}\n\nstatic void _stub_stream_end(char *name, void *userdata)\n{\n    UNUSED(name);\n    UNUSED(userdata);\n}\n\nstatic void _stream_stanza(xmpp_stanza_t *stanza, void *userdata)\n{\n    xmpp_stanza_t **dest = userdata;\n    if (*dest == NULL) {\n        stanza = xmpp_stanza_clone(stanza);\n        *dest = stanza;\n    }\n}\n\n/** Create a stanza object from the string.\n *  This function allocates and initializes a stanza object which represents\n *  stanza located in the string.\n *  The stanza will have a reference count of one, so the caller does not\n *  need to clone it.\n *\n *  @param ctx a Strophe context object\n *  @param str stanza in NULL terminated string representation\n *\n *  @return a stanza object or NULL on an error\n *\n *  @ingroup Stanza\n */\nxmpp_stanza_t *xmpp_stanza_new_from_string(xmpp_ctx_t *ctx, const char *str)\n{\n    xmpp_stanza_t *stanza = NULL;\n    parser_t *parser;\n    int ret;\n\n    static const char *start = \"<stream>\";\n    static const char *end = \"</stream>\";\n\n    parser = parser_new(ctx, _stub_stream_start, _stub_stream_end,\n                        _stream_stanza, &stanza);\n    if (parser) {\n        ret = parser_feed(parser, (char *)start, strlen(start)) &&\n              parser_feed(parser, (char *)str, strlen(str)) &&\n              parser_feed(parser, (char *)end, strlen(end));\n        parser_free(parser);\n        if (!ret && stanza) {\n            xmpp_stanza_release(stanza);\n            stanza = NULL;\n        }\n    }\n    return stanza;\n}\n"
  },
  {
    "path": "src/tls.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* tls.c\n** strophe XMPP client library -- generic TLS functions\n**\n** Copyright (C) 2021 Steffen Jaeckel <jaeckel-floss@eyet-services.de>\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Generic TLS functionality.\n */\n\n/** @defgroup TLS SSL/TLS specific functionality\n *  These functions provide SSL/TLS specific functionality.\n */\n\n#include <errno.h>\n#include <stdarg.h>\n#include <string.h>\n\n#if !defined(_WIN32)\n#include <unistd.h>\n#endif\n\n#include \"strophe.h\"\n\n#include \"common.h\"\n#ifdef _MSC_VER\n#include <BaseTsd.h>\ntypedef SSIZE_T ssize_t;\n#endif\n\nconst struct conn_interface tls_intf = {\n    tls_read,\n    tls_write,\n    tls_clear_pending_write,\n    tls_pending,\n    tls_error,\n    tls_is_recoverable,\n    /* init conn */\n    NULL,\n};\n\nstruct _dnsname_t {\n    char **data;\n    size_t cur, max;\n};\n\nconst size_t tlscert_dnsnames_increment = 4;\n\n/** Get the Strophe context which is assigned to this certificate.\n *\n *  @param cert a Strophe TLS certificate object\n *\n *  @return the Strophe context object where this certificate originates from\n *\n *  @ingroup TLS\n */\nxmpp_ctx_t *xmpp_tlscert_get_ctx(const xmpp_tlscert_t *cert)\n{\n    return cert->ctx;\n}\n\n/** Get the Strophe connection which is assigned to this certificate.\n *\n *  @param cert a Strophe TLS certificate object\n *\n *  @return the Strophe connection object where this certificate originates from\n *\n *  @ingroup TLS\n */\nxmpp_conn_t *xmpp_tlscert_get_conn(const xmpp_tlscert_t *cert)\n{\n    return cert->conn;\n}\n\n/** Get the userdata of a Strophe connection which is assigned to this\n *  certificate.\n *\n *  @param cert a Strophe TLS certificate object\n *\n *  @return the userdata of a Strophe connection object where this certificate\n *  originates from\n *\n *  @ingroup TLS\n */\nvoid *xmpp_tlscert_get_userdata(const xmpp_tlscert_t *cert)\n{\n    if (cert->conn == NULL)\n        return NULL;\n    return cert->conn->userdata;\n}\n\n/** Get the complete PEM of this certificate.\n *\n *  @param cert a Strophe TLS certificate object\n *\n *  @return a string containing the PEM of this certificate\n *\n *  @ingroup TLS\n */\nconst char *xmpp_tlscert_get_pem(const xmpp_tlscert_t *cert)\n{\n    return cert->pem;\n}\n\n/** Get the dnsName entries out of the SubjectAlternativeNames.\n *\n *  @param cert a Strophe TLS certificate object\n *  @param n which dnsName entry\n *\n *  @return a string with the n'th dnsName\n *\n *  @ingroup TLS\n */\nconst char *xmpp_tlscert_get_dnsname(const xmpp_tlscert_t *cert, size_t n)\n{\n    if (n >= cert->dnsnames->cur)\n        return NULL;\n    return cert->dnsnames->data[n];\n}\n\n/** Get various parts of the certificate as String.\n *\n *  c.f. \\ref xmpp_cert_element_t for details.\n *\n *  @param cert a Strophe TLS certificate object\n *  @param elmnt which part of the certificate\n *\n *  @return a string with the part of the certificate\n *\n *  @ingroup TLS\n */\nconst char *xmpp_tlscert_get_string(const xmpp_tlscert_t *cert,\n                                    xmpp_cert_element_t elmnt)\n{\n    if (elmnt < 0 || elmnt >= XMPP_CERT_ELEMENT_MAX)\n        return NULL;\n    return cert->elements[elmnt];\n}\n\n/** Get a descriptive string for each xmpp_cert_element_t.\n *\n *  c.f. \\ref xmpp_cert_element_t for details.\n *\n *  @param elmnt which element\n *\n *  @return a string with the description\n *\n *  @ingroup TLS\n */\nconst char *xmpp_tlscert_get_description(xmpp_cert_element_t elmnt)\n{\n    static const char *descriptions[] = {\n        \"X.509 Version\",\n        \"SerialNumber\",\n        \"Subject\",\n        \"Issuer\",\n        \"Issued On\",\n        \"Expires On\",\n        \"Public Key Algorithm\",\n        \"Certificate Signature Algorithm\",\n        \"Certificate Fingerprint SHA-1\",\n        \"Certificate Fingerprint SHA-256\",\n        \"Public Key Fingerprint SHA-256\",\n    };\n    STROPHE_STATIC_ASSERT(\n        ARRAY_SIZE(descriptions) == XMPP_CERT_ELEMENT_MAX,\n        \"descriptions don't match the number of enum elements\");\n    if (elmnt < 0 || elmnt >= XMPP_CERT_ELEMENT_MAX)\n        return NULL;\n    return descriptions[elmnt];\n}\n\n/** Allocate and initialize a Strophe TLS certificate object.\n *\n *  @param ctx a Strophe context object\n *\n *  @return a certificate object or NULL\n */\nxmpp_tlscert_t *tlscert_new(xmpp_ctx_t *ctx)\n{\n    xmpp_tlscert_t *tlscert = strophe_alloc(ctx, sizeof(*tlscert));\n    if (!tlscert)\n        return NULL;\n    memset(tlscert, 0, sizeof(*tlscert));\n\n    tlscert->dnsnames = strophe_alloc(ctx, sizeof(*tlscert->dnsnames));\n    if (!tlscert->dnsnames) {\n        strophe_free(ctx, tlscert);\n        return NULL;\n    }\n    memset(tlscert->dnsnames, 0, sizeof(*tlscert->dnsnames));\n\n    tlscert->ctx = ctx;\n\n    return tlscert;\n}\n\n/** Free a certificate object.\n *\n *  @param cert a Strophe TLS certificate object\n *\n *  @ingroup TLS\n */\nvoid xmpp_tlscert_free(xmpp_tlscert_t *cert)\n{\n    size_t n;\n    for (n = 0; n < ARRAY_SIZE(cert->elements); ++n) {\n        if (cert->elements[n])\n            strophe_free(cert->ctx, cert->elements[n]);\n    }\n    if (cert->dnsnames->data) {\n        for (n = 0; n < cert->dnsnames->cur; ++n) {\n            if (cert->dnsnames->data[n])\n                strophe_free(cert->ctx, cert->dnsnames->data[n]);\n        }\n    }\n    strophe_free(cert->ctx, cert->dnsnames->data);\n    strophe_free(cert->ctx, cert->dnsnames);\n    if (cert->pem)\n        strophe_free(cert->ctx, cert->pem);\n    strophe_free(cert->ctx, cert);\n}\n\n/** Add a dnsName to the Strophe TLS certificate object.\n *\n *  @param cert a Strophe TLS certificate object\n *  @param dnsname dnsName that shall be stored\n *\n *  @return classic Unix style - 0=success, 1=error\n */\nint tlscert_add_dnsname(xmpp_tlscert_t *cert, const char *dnsname)\n{\n    if ((cert->dnsnames->cur + 1) >= cert->dnsnames->max) {\n        char **dnsnames =\n            strophe_realloc(cert->ctx, cert->dnsnames->data,\n                            (cert->dnsnames->max + tlscert_dnsnames_increment) *\n                                sizeof(char **));\n        if (!dnsnames)\n            return 1;\n        cert->dnsnames->data = dnsnames;\n        cert->dnsnames->max += tlscert_dnsnames_increment;\n    }\n    cert->dnsnames->data[cert->dnsnames->cur++] =\n        strophe_strdup(cert->ctx, dnsname);\n    return 0;\n}\n\nint tls_caching_password_callback(char *pw, size_t pw_max, xmpp_conn_t *conn)\n{\n    int ret;\n    unsigned char hash[XMPP_SHA1_DIGEST_SIZE];\n\n    const char *fname = conn->tls_client_cert;\n    size_t fname_len = strlen(fname);\n    xmpp_sha1_digest((void *)fname, fname_len, hash);\n    if (fname_len && fname_len == conn->password_cache.fnamelen &&\n        memcmp(hash, conn->password_cache.fname_hash, sizeof(hash)) == 0) {\n        if (conn->password_cache.passlen) {\n            memcpy(pw, conn->password_cache.pass,\n                   conn->password_cache.passlen + 1);\n            return conn->password_cache.passlen;\n        }\n    }\n    size_t max_len = pw_max == 256 ? pw_max : sizeof(conn->password_cache.pass);\n    ret = conn->password_callback(conn->password_cache.pass, max_len, conn,\n                                  conn->password_callback_userdata);\n\n    if (ret < 0 || ret >= (ssize_t)max_len) {\n        memset(conn->password_cache.pass, 0, sizeof(conn->password_cache.pass));\n        return -1;\n    }\n    conn->password_cache.pass[ret] = '\\0';\n    memcpy(pw, conn->password_cache.pass, ret + 1);\n    conn->password_cache.passlen = ret;\n    conn->password_cache.fnamelen = fname_len;\n    memcpy(conn->password_cache.fname_hash, hash, sizeof(hash));\n    return conn->password_cache.passlen;\n}\n\nvoid tls_clear_password_cache(xmpp_conn_t *conn)\n{\n    memset(&conn->password_cache, 0, sizeof(conn->password_cache));\n}\n"
  },
  {
    "path": "src/tls.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* tls.h\n** strophe XMPP client library -- TLS abstraction header\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  TLS abstraction API.\n */\n\n#ifndef __LIBSTROPHE_TLS_H__\n#define __LIBSTROPHE_TLS_H__\n\n#include \"common.h\"\n#include \"sock.h\"\n\ntypedef struct _tls tls_t;\n\ntypedef struct _dnsname_t dnsname_t;\n\nstruct _xmpp_tlscert_t {\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    char *pem;\n    char *elements[XMPP_CERT_ELEMENT_MAX];\n    dnsname_t *dnsnames;\n};\n\n/* provided by the real TLS implementation */\n\nvoid tls_initialize(void);\nvoid tls_shutdown(void);\n\ntls_t *tls_new(xmpp_conn_t *conn);\nvoid tls_free(tls_t *tls);\n\nchar *tls_id_on_xmppaddr(xmpp_conn_t *conn, unsigned int n);\nunsigned int tls_id_on_xmppaddr_num(xmpp_conn_t *conn);\n\nxmpp_tlscert_t *tls_peer_cert(xmpp_conn_t *conn);\nint tls_set_credentials(tls_t *tls, const char *cafilename);\nint tls_init_channel_binding(tls_t *tls,\n                             const char **binding_prefix,\n                             size_t *binding_prefix_len);\nconst void *tls_get_channel_binding_data(tls_t *tls, size_t *size);\n\nint tls_start(tls_t *tls);\nint tls_stop(tls_t *tls);\n\nint tls_pending(struct conn_interface *intf);\nint tls_read(struct conn_interface *intf, void *buff, size_t len);\nint tls_write(struct conn_interface *intf, const void *buff, size_t len);\nint tls_clear_pending_write(struct conn_interface *intf);\n\nint tls_error(struct conn_interface *intf);\nint tls_is_recoverable(struct conn_interface *intf, int error);\n\n/* provided by tls.c */\nextern const struct conn_interface tls_intf;\n\nxmpp_tlscert_t *tlscert_new(xmpp_ctx_t *ctx);\nint tlscert_add_dnsname(xmpp_tlscert_t *cert, const char *dnsname);\n\nint tls_caching_password_callback(char *pw, size_t pw_max, xmpp_conn_t *conn);\nvoid tls_clear_password_cache(xmpp_conn_t *conn);\n\n#endif /* __LIBSTROPHE_TLS_H__ */\n"
  },
  {
    "path": "src/tls_dummy.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* tls_dummy.c\n** strophe XMPP client library -- TLS abstraction dummy impl.\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  TLS dummy implementation.\n */\n\n#include \"common.h\"\n#include \"tls.h\"\n#include \"sock.h\"\n\nstruct _tls {\n    xmpp_ctx_t *ctx; /* do we need this? */\n    sock_t sock;\n    /* we don't implement anything */\n};\n\nvoid tls_initialize(void)\n{\n    return;\n}\n\nvoid tls_shutdown(void)\n{\n    return;\n}\n\nchar *tls_id_on_xmppaddr(xmpp_conn_t *conn, unsigned int n)\n{\n    UNUSED(conn);\n    UNUSED(n);\n    /* always fail */\n    return NULL;\n}\n\nunsigned int tls_id_on_xmppaddr_num(xmpp_conn_t *conn)\n{\n    UNUSED(conn);\n    /* always fail */\n    return 0;\n}\n\ntls_t *tls_new(xmpp_conn_t *conn)\n{\n    UNUSED(conn);\n    /* always fail */\n    return NULL;\n}\n\nvoid tls_free(tls_t *tls)\n{\n    UNUSED(tls);\n    return;\n}\n\nxmpp_tlscert_t *tls_peer_cert(xmpp_conn_t *conn)\n{\n    UNUSED(conn);\n    return NULL;\n}\n\nint tls_set_credentials(tls_t *tls, const char *cafilename)\n{\n    UNUSED(tls);\n    UNUSED(cafilename);\n    return -1;\n}\n\nint tls_init_channel_binding(tls_t *tls,\n                             const char **binding_prefix,\n                             size_t *binding_prefix_len)\n{\n    UNUSED(tls);\n    UNUSED(binding_prefix);\n    UNUSED(binding_prefix_len);\n    return -1;\n}\n\nconst void *tls_get_channel_binding_data(tls_t *tls, size_t *size)\n{\n    UNUSED(tls);\n    UNUSED(size);\n    return NULL;\n}\n\nint tls_start(tls_t *tls)\n{\n    UNUSED(tls);\n    return -1;\n}\n\nint tls_stop(tls_t *tls)\n{\n    UNUSED(tls);\n    return -1;\n}\n\nint tls_error(struct conn_interface *intf)\n{\n    UNUSED(intf);\n    return 0;\n}\n\nint tls_pending(struct conn_interface *intf)\n{\n    UNUSED(intf);\n    return 0;\n}\n\nint tls_read(struct conn_interface *intf, void *buff, size_t len)\n{\n    UNUSED(intf);\n    UNUSED(buff);\n    UNUSED(len);\n    return -1;\n}\n\nint tls_write(struct conn_interface *intf, const void *buff, size_t len)\n{\n    UNUSED(intf);\n    UNUSED(buff);\n    UNUSED(len);\n    return -1;\n}\n\nint tls_clear_pending_write(struct conn_interface *intf)\n{\n    UNUSED(intf);\n    return -1;\n}\n\nint tls_is_recoverable(struct conn_interface *intf, int error)\n{\n    UNUSED(intf);\n    UNUSED(error);\n    return 0;\n}\n"
  },
  {
    "path": "src/tls_gnutls.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* tls.c\n** strophe XMPP client library -- TLS abstraction header\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  TLS implementation with GNUTLS\n */\n\n#include <string.h>\n#include <gnutls/gnutls.h>\n#include <gnutls/x509.h>\n#include <gnutls/x509-ext.h>\n#include <gnutls/pkcs11.h>\n#include <gnutls/pkcs12.h>\n\n#include \"common.h\"\n#include \"tls.h\"\n#include \"sock.h\"\n\n#if GNUTLS_VERSION_NUMBER < 0x030702\n/* This is a very dirty workaround to make this file compile on older GnuTLS\n * We simply define our own value for the later introduced\n * `GNUTLS_CB_TLS_EXPORTER` which makes it compile, but it will fail on runtime\n * when the combination of the following options happen:\n * * GnuTLS < 3.7.2\n * * TLS 1.3\n * * A SCRAM PLUS variant to authenticate\n * We will think about fixing this once a user pops up who has that problem.\n */\n#define GNUTLS_CB_TLS_EXPORTER 3\n#endif\n\nstruct _tls {\n    xmpp_ctx_t *ctx; /* do we need this? */\n    xmpp_conn_t *conn;\n    gnutls_session_t session;\n    gnutls_certificate_credentials_t cred;\n    gnutls_x509_crt_t client_cert;\n    gnutls_datum_t channel_binding;\n    int lasterror;\n};\n\nvoid tls_initialize(void)\n{\n    /* initialize the GNU TLS global state */\n    gnutls_global_init();\n\n    /* TODO: wire in xmpp_ctx_t allocator somehow?\n       unfortunately in gnutls it's global, so we can\n       only do so much. */\n}\n\nvoid tls_shutdown(void)\n{\n    /* tear down the GNU TLS global state */\n    gnutls_global_deinit();\n}\n\nstatic int _tls_password_callback(void *userdata,\n                                  int attempt,\n                                  const char *token_url,\n                                  const char *token_label,\n                                  unsigned int flags,\n                                  char *pin,\n                                  size_t pin_max)\n{\n    xmpp_conn_t *conn = userdata;\n    UNUSED(attempt);\n    UNUSED(token_url);\n    UNUSED(token_label);\n    UNUSED(flags);\n    int ret = tls_caching_password_callback(pin, pin_max, conn);\n    return ret > 0 ? 0 : GNUTLS_E_PKCS11_PIN_ERROR;\n}\n\nstatic gnutls_x509_crt_t _tls_load_cert_x509(xmpp_conn_t *conn)\n{\n    gnutls_x509_crt_t cert;\n    gnutls_datum_t data;\n    int res;\n    if (gnutls_x509_crt_init(&cert) < 0)\n        return NULL;\n    if (gnutls_load_file(conn->tls_client_cert, &data) < 0)\n        goto error_out;\n    res = gnutls_x509_crt_import(cert, &data, GNUTLS_X509_FMT_PEM);\n    gnutls_free(data.data);\n    if (res < 0)\n        goto error_out;\n    return cert;\nerror_out:\n    gnutls_x509_crt_deinit(cert);\n    return NULL;\n}\n\nstatic gnutls_x509_crt_t _tls_load_cert_p12(xmpp_conn_t *conn)\n{\n    gnutls_pkcs12_t p12;\n    gnutls_x509_crt_t *cert = NULL;\n    gnutls_datum_t data;\n    gnutls_x509_privkey_t key;\n    unsigned int cert_num = 0, retries = 0;\n    int err = -1;\n    if (gnutls_pkcs12_init(&p12) < 0)\n        return NULL;\n    if (gnutls_load_file(conn->tls_client_cert, &data) < 0)\n        goto error_out;\n    if (gnutls_pkcs12_import(p12, &data, GNUTLS_X509_FMT_DER, 0) < 0)\n        goto error_out2;\n\n    /* First try to open file with no pass */\n    if ((err = gnutls_pkcs12_simple_parse(p12, NULL, &key, &cert, &cert_num,\n                                          NULL, NULL, NULL, 0)) == 0) {\n        goto done;\n    }\n    /* Now let's try to open file with an empty pass */\n    if ((err = gnutls_pkcs12_simple_parse(p12, \"\", &key, &cert, &cert_num, NULL,\n                                          NULL, NULL, 0)) == 0) {\n        goto done;\n    }\n\n    if (!conn->password_callback) {\n        strophe_error(conn->ctx, \"tls\", \"No password callback set\");\n        goto error_out2;\n    }\n    /* ... and only now ask the user for a password */\n    while (retries++ < conn->password_retries) {\n        char pass[GNUTLS_PKCS11_MAX_PIN_LEN];\n        int passlen =\n            _tls_password_callback(conn, 0, NULL, NULL, 0, pass, sizeof(pass));\n        if (passlen < 0)\n            continue;\n\n        err = gnutls_pkcs12_simple_parse(p12, pass, &key, &cert, &cert_num,\n                                         NULL, NULL, NULL, 0);\n        memset(pass, 0, sizeof(pass));\n        if (err == 0)\n            break;\n        tls_clear_password_cache(conn);\n        if (err != GNUTLS_E_DECRYPTION_FAILED &&\n            err != GNUTLS_E_MAC_VERIFY_FAILED) {\n            strophe_error(conn->ctx, \"tls\", \"could not read P12 file\");\n            break;\n        }\n        strophe_debug(conn->ctx, \"tls\", \"wrong password?\");\n    }\n\ndone:\n    gnutls_pkcs12_deinit(p12);\n    gnutls_free(data.data);\n    if (err < 0)\n        goto error_out;\n    gnutls_x509_privkey_deinit(key);\n    if (cert_num > 1) {\n        strophe_error(conn->ctx, \"tls\", \"Can't handle stack of %u certs\",\n                      cert_num);\n        goto error_out;\n    }\n    gnutls_x509_crt_t ret = *cert;\n    gnutls_free(cert);\n    return ret;\nerror_out2:\n    gnutls_free(data.data);\nerror_out:\n    tls_clear_password_cache(conn);\n    if (cert) {\n        for (unsigned int n = 0; n < cert_num; ++n) {\n            gnutls_x509_crt_deinit(cert[n]);\n        }\n        gnutls_free(cert);\n    }\n    return NULL;\n}\n\nstatic gnutls_x509_crt_t _tls_load_cert(xmpp_conn_t *conn)\n{\n    if (conn->tls && conn->tls->client_cert)\n        return conn->tls->client_cert;\n    if (conn->tls_client_cert && !conn->tls_client_key) {\n        return _tls_load_cert_p12(conn);\n    }\n    return _tls_load_cert_x509(conn);\n}\n\nstatic void _tls_free_cert(xmpp_conn_t *conn, gnutls_x509_crt_t cert)\n{\n    if (conn->tls && conn->tls->client_cert == cert)\n        return;\n    gnutls_x509_crt_deinit(cert);\n}\n\nstatic int _tls_get_id_on_xmppaddr(xmpp_conn_t *conn,\n                                   gnutls_x509_crt_t cert,\n                                   unsigned int n,\n                                   char **ret)\n{\n    gnutls_datum_t san;\n    size_t name_len, oid_len;\n    char oid[128], name[128];\n    name_len = oid_len = 128;\n    int res =\n        gnutls_x509_crt_get_subject_alt_name(cert, n, name, &name_len, NULL);\n    if (res == GNUTLS_SAN_OTHERNAME_XMPP) {\n        /* This is the happy flow path with fixed GnuTLS.\n         * While implementing this I stumbled over an issue in GnuTLS\n         * which lead to\n         * https://gitlab.com/gnutls/gnutls/-/merge_requests/1397\n         */\n        if (ret) {\n            *ret = strophe_strdup(conn->ctx, name);\n        }\n        return GNUTLS_SAN_OTHERNAME_XMPP;\n    }\n    if (res == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)\n        return GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE;\n    if (res != GNUTLS_SAN_OTHERNAME)\n        return GNUTLS_E_X509_UNKNOWN_SAN;\n    res = gnutls_x509_crt_get_subject_alt_othername_oid(cert, n, oid, &oid_len);\n    if (res == GNUTLS_SAN_OTHERNAME_XMPP) {\n        gnutls_datum_t xmpp_addr;\n        san.data = (unsigned char *)name;\n        san.size = name_len;\n        res = gnutls_x509_othername_to_virtual(oid, &san, NULL, &xmpp_addr);\n        if (res < 0) {\n            gnutls_free(xmpp_addr.data);\n            return GNUTLS_E_MEMORY_ERROR;\n        }\n        if (ret) {\n            *ret = strophe_strdup(conn->ctx, (char *)xmpp_addr.data);\n        }\n        gnutls_free(xmpp_addr.data);\n        return GNUTLS_SAN_OTHERNAME_XMPP;\n    }\n    return GNUTLS_E_X509_UNKNOWN_SAN;\n}\n\nstatic int _tls_id_on_xmppaddr(xmpp_conn_t *conn,\n                               gnutls_x509_crt_t cert,\n                               unsigned int n,\n                               char **ret)\n{\n    int res = GNUTLS_E_SUCCESS;\n    unsigned int i, j;\n    for (i = j = 0; res != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; ++i) {\n        res = _tls_get_id_on_xmppaddr(conn, cert, i, NULL);\n        if (res == GNUTLS_SAN_OTHERNAME_XMPP) {\n            if (j == n) {\n                res = _tls_get_id_on_xmppaddr(conn, cert, i, ret);\n                break;\n            }\n            j++;\n        }\n    }\n    return res;\n}\n\n/** Search through the SubjectAlternativeNames and return the next\n *  id-on-xmppAddr element starting from `n`.\n */\nchar *tls_id_on_xmppaddr(xmpp_conn_t *conn, unsigned int n)\n{\n    char *ret = NULL;\n    gnutls_x509_crt_t cert = _tls_load_cert(conn);\n    if (cert == NULL)\n        return NULL;\n    _tls_id_on_xmppaddr(conn, cert, n, &ret);\n    _tls_free_cert(conn, cert);\n    return ret;\n}\n\nunsigned int tls_id_on_xmppaddr_num(xmpp_conn_t *conn)\n{\n    unsigned int ret = 0, n;\n    int res = GNUTLS_E_SUCCESS;\n    gnutls_x509_crt_t cert = _tls_load_cert(conn);\n    if (cert == NULL)\n        return 0;\n    for (n = 0; res != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE; ++n) {\n        res = _tls_id_on_xmppaddr(conn, cert, n, NULL);\n        if (res == GNUTLS_SAN_OTHERNAME_XMPP)\n            ret++;\n    }\n    _tls_free_cert(conn, cert);\n    return ret;\n}\n\nstatic xmpp_tlscert_t *_x509_to_tlscert(xmpp_ctx_t *ctx, gnutls_x509_crt_t cert)\n{\n    int res;\n    char buf[512], smallbuf[64];\n    size_t size, m;\n    unsigned int algo, n;\n    gnutls_datum_t data;\n    time_t time_val;\n    xmpp_tlscert_t *tlscert = tlscert_new(ctx);\n\n    gnutls_x509_crt_export2(cert, GNUTLS_X509_FMT_PEM, &data);\n    tlscert->pem = strophe_alloc(ctx, data.size + 1);\n    memcpy(tlscert->pem, data.data, data.size);\n    tlscert->pem[data.size] = '\\0';\n    gnutls_free(data.data);\n\n    size = sizeof(buf);\n    gnutls_x509_crt_get_dn(cert, buf, &size);\n    tlscert->elements[XMPP_CERT_SUBJECT] = strophe_strdup(ctx, buf);\n    size = sizeof(buf);\n    gnutls_x509_crt_get_issuer_dn(cert, buf, &size);\n    tlscert->elements[XMPP_CERT_ISSUER] = strophe_strdup(ctx, buf);\n\n    time_val = gnutls_x509_crt_get_activation_time(cert);\n    tlscert->elements[XMPP_CERT_NOTBEFORE] =\n        strophe_strdup(ctx, ctime(&time_val));\n    tlscert->elements[XMPP_CERT_NOTBEFORE]\n                     [strlen(tlscert->elements[XMPP_CERT_NOTBEFORE]) - 1] =\n        '\\0';\n    time_val = gnutls_x509_crt_get_expiration_time(cert);\n    tlscert->elements[XMPP_CERT_NOTAFTER] =\n        strophe_strdup(ctx, ctime(&time_val));\n    tlscert->elements[XMPP_CERT_NOTAFTER]\n                     [strlen(tlscert->elements[XMPP_CERT_NOTAFTER]) - 1] = '\\0';\n\n    size = sizeof(smallbuf);\n    gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA1, smallbuf, &size);\n    hex_encode(buf, smallbuf, size);\n    tlscert->elements[XMPP_CERT_FINGERPRINT_SHA1] = strophe_strdup(ctx, buf);\n    size = sizeof(smallbuf);\n    gnutls_x509_crt_get_fingerprint(cert, GNUTLS_DIG_SHA256, smallbuf, &size);\n    hex_encode(buf, smallbuf, size);\n    tlscert->elements[XMPP_CERT_FINGERPRINT_SHA256] = strophe_strdup(ctx, buf);\n    size = sizeof(smallbuf);\n    gnutls_x509_crt_get_key_id(cert, GNUTLS_KEYID_USE_SHA256, (void *)smallbuf,\n                               &size);\n    hex_encode(buf, smallbuf, size);\n    tlscert->elements[XMPP_CERT_PUBKEY_FINGERPRINT_SHA256] =\n        strophe_strdup(ctx, buf);\n\n    strophe_snprintf(buf, sizeof(buf), \"%d\", gnutls_x509_crt_get_version(cert));\n    tlscert->elements[XMPP_CERT_VERSION] = strophe_strdup(ctx, buf);\n\n    algo = gnutls_x509_crt_get_pk_algorithm(cert, NULL);\n    tlscert->elements[XMPP_CERT_KEYALG] =\n        strophe_strdup(ctx, gnutls_pk_algorithm_get_name(algo));\n    algo = gnutls_x509_crt_get_signature_algorithm(cert);\n    tlscert->elements[XMPP_CERT_SIGALG] =\n        strophe_strdup(ctx, gnutls_sign_get_name(algo));\n\n    size = sizeof(smallbuf);\n    gnutls_x509_crt_get_serial(cert, smallbuf, &size);\n    hex_encode(buf, smallbuf, size);\n    tlscert->elements[XMPP_CERT_SERIALNUMBER] = strophe_strdup(ctx, buf);\n\n    for (n = 0, m = 0, res = 0; res != GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE;\n         ++n) {\n        size = sizeof(buf);\n        res = gnutls_x509_crt_get_subject_alt_name(cert, n, buf, &size, NULL);\n        if (res == GNUTLS_SAN_DNSNAME) {\n            if (tlscert_add_dnsname(tlscert, buf))\n                strophe_debug(ctx, \"tls\", \"Can't store dnsName(%zu): %s\", m,\n                              buf);\n            m++;\n        }\n    }\n\n    return tlscert;\n}\n\nstatic int _tls_verify(gnutls_session_t session)\n{\n    tls_t *tls = gnutls_session_get_ptr(session);\n    const gnutls_datum_t *cert_list;\n    gnutls_certificate_type_t type;\n    gnutls_datum_t out;\n    unsigned int cert_list_size = 0, status;\n    gnutls_x509_crt_t cert;\n\n    if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509)\n        return -1;\n\n    if (gnutls_certificate_verify_peers2(session, &status) < 0) {\n        strophe_error(tls->ctx, \"tls\", \"Verify peers failed\");\n        return -1;\n    }\n    type = gnutls_certificate_type_get(session);\n    if (gnutls_certificate_verification_status_print(status, type, &out, 0) <\n        0) {\n        strophe_error(tls->ctx, \"tls\", \"Status print failed\");\n        return -1;\n    }\n\n    /* Return early if the Certificate is trusted\n     * OR if we trust all Certificates */\n    if (status == 0 || tls->conn->tls_trust) {\n        gnutls_free(out.data);\n        return 0;\n    }\n\n    if (!tls->conn->certfail_handler) {\n        strophe_error(tls->ctx, \"tls\",\n                      \"No certfail handler set, canceling connection attempt\");\n        gnutls_free(out.data);\n        return -1;\n    }\n\n    cert_list = gnutls_certificate_get_peers(session, &cert_list_size);\n\n    /* OpenSSL displays the certificate chain in reverse order than GnuTLS.\n     * To show consistent behavior to the user, traverse the list from the\n     * end.\n     */\n    while (cert_list_size--) {\n        gnutls_x509_crt_init(&cert);\n\n        gnutls_x509_crt_import(cert, &cert_list[cert_list_size],\n                               GNUTLS_X509_FMT_DER);\n\n        xmpp_tlscert_t *tlscert = _x509_to_tlscert(tls->ctx, cert);\n\n        if (!tlscert) {\n            gnutls_x509_crt_deinit(cert);\n            gnutls_free(out.data);\n            return -1;\n        }\n\n        tlscert->conn = tls->conn;\n\n        if (tls->conn->certfail_handler(tlscert, (char *)out.data) == 0) {\n            xmpp_tlscert_free(tlscert);\n            gnutls_x509_crt_deinit(cert);\n            gnutls_free(out.data);\n            return -1;\n        }\n        xmpp_tlscert_free(tlscert);\n        gnutls_x509_crt_deinit(cert);\n    }\n    gnutls_free(out.data);\n    return 0;\n}\n\ntls_t *tls_new(xmpp_conn_t *conn)\n{\n    tls_t *tls = strophe_alloc(conn->ctx, sizeof(tls_t));\n\n    if (tls) {\n        memset(tls, 0, sizeof(*tls));\n        tls->ctx = conn->ctx;\n        tls->conn = conn;\n        gnutls_init(&tls->session, GNUTLS_CLIENT);\n\n        gnutls_certificate_allocate_credentials(&tls->cred);\n        tls_set_credentials(tls, NULL);\n\n        if (conn->password_callback)\n            gnutls_certificate_set_pin_function(tls->cred,\n                                                _tls_password_callback, conn);\n\n        if (conn->tls_client_cert && conn->tls_client_key) {\n            unsigned int retries = 0;\n            tls->client_cert = _tls_load_cert(conn);\n            if (!tls->client_cert) {\n                strophe_error(tls->ctx, \"tls\",\n                              \"could not read client certificate\");\n                goto error_out;\n            }\n            while (retries++ < conn->password_retries) {\n                int err = gnutls_certificate_set_x509_key_file(\n                    tls->cred, conn->tls_client_cert, conn->tls_client_key,\n                    GNUTLS_X509_FMT_PEM);\n                if (err == 0)\n                    break;\n                tls_clear_password_cache(conn);\n                if (err != GNUTLS_E_DECRYPTION_FAILED) {\n                    strophe_error(tls->ctx, \"tls\",\n                                  \"could not read private key\");\n                    goto error_out;\n                }\n                strophe_debug(tls->ctx, \"tls\", \"wrong password?\");\n            }\n        } else if (conn->tls_client_cert) {\n            unsigned int retries = 0;\n\n            while (retries++ < conn->password_retries) {\n                char pass[GNUTLS_PKCS11_MAX_PIN_LEN];\n                pass[0] = '\\0';\n                int passlen = _tls_password_callback(conn, 0, NULL, NULL, 0,\n                                                     pass, sizeof(pass));\n                if (passlen < 0)\n                    continue;\n                int err = gnutls_certificate_set_x509_simple_pkcs12_file(\n                    tls->cred, conn->tls_client_cert, GNUTLS_X509_FMT_DER,\n                    pass);\n                memset(pass, 0, sizeof(pass));\n                if (err == 0)\n                    break;\n                tls_clear_password_cache(conn);\n                if (err != GNUTLS_E_DECRYPTION_FAILED &&\n                    err != GNUTLS_E_MAC_VERIFY_FAILED) {\n                    strophe_error(tls->ctx, \"tls\", \"could not read P12 file\");\n                    goto error_out;\n                }\n                strophe_debug(tls->ctx, \"tls\", \"wrong password?\");\n            }\n        }\n\n        gnutls_certificate_set_verify_function(tls->cred, _tls_verify);\n\n        gnutls_set_default_priority(tls->session);\n        gnutls_session_set_ptr(tls->session, tls);\n\n        /* fixme: this may require setting a callback on win32? */\n        gnutls_transport_set_int(tls->session, conn->sock);\n    }\n\n    return tls;\nerror_out:\n    if (tls->client_cert)\n        gnutls_x509_crt_deinit(tls->client_cert);\n    gnutls_certificate_free_credentials(tls->cred);\n    gnutls_deinit(tls->session);\n    strophe_free(tls->ctx, tls);\n    return NULL;\n}\n\nvoid tls_free(tls_t *tls)\n{\n    gnutls_free(tls->channel_binding.data);\n    gnutls_x509_crt_deinit(tls->client_cert);\n    gnutls_deinit(tls->session);\n    gnutls_certificate_free_credentials(tls->cred);\n    strophe_free(tls->ctx, tls);\n}\n\nxmpp_tlscert_t *tls_peer_cert(xmpp_conn_t *conn)\n{\n    xmpp_tlscert_t *tlscert = NULL;\n    if (conn && conn->tls && conn->tls->session) {\n        unsigned int list_size = 0;\n        const gnutls_datum_t *der_cert =\n            gnutls_certificate_get_peers(conn->tls->session, &list_size);\n        if (der_cert && list_size) {\n            gnutls_x509_crt_t cert;\n            if (gnutls_x509_crt_init(&cert) < 0)\n                return NULL;\n            if (gnutls_x509_crt_import(cert, der_cert, GNUTLS_X509_FMT_DER) ==\n                0)\n                tlscert = _x509_to_tlscert(conn->ctx, cert);\n            gnutls_x509_crt_deinit(cert);\n        }\n    }\n    return tlscert;\n}\n\nint tls_set_credentials(tls_t *tls, const char *cafilename)\n{\n    UNUSED(cafilename);\n\n    /* set trusted credentials -- takes a .pem filename */\n    int err = gnutls_certificate_set_x509_system_trust(tls->cred);\n    if (err >= 0 && tls->conn->tls_cafile)\n        err = gnutls_certificate_set_x509_trust_file(\n            tls->cred, tls->conn->tls_cafile, GNUTLS_X509_FMT_PEM);\n    if (err >= 0 && tls->conn->tls_capath)\n        err = gnutls_certificate_set_x509_trust_dir(\n            tls->cred, tls->conn->tls_capath, GNUTLS_X509_FMT_PEM);\n    if (err >= 0) {\n        err = gnutls_credentials_set(tls->session, GNUTLS_CRD_CERTIFICATE,\n                                     tls->cred);\n    }\n    tls->lasterror = err;\n\n    return err == GNUTLS_E_SUCCESS;\n}\n\nint tls_init_channel_binding(tls_t *tls,\n                             const char **binding_prefix,\n                             size_t *binding_prefix_len)\n{\n    gnutls_channel_binding_t binding_type;\n    gnutls_protocol_t tls_version = gnutls_protocol_get_version(tls->session);\n\n    switch (tls_version) {\n    case GNUTLS_SSL3:\n    case GNUTLS_TLS1_0:\n    case GNUTLS_TLS1_1:\n    case GNUTLS_TLS1_2:\n        *binding_prefix = \"tls-unique\";\n        *binding_prefix_len = strlen(\"tls-unique\");\n        binding_type = GNUTLS_CB_TLS_UNIQUE;\n        break;\n    case GNUTLS_TLS1_3:\n        *binding_prefix = \"tls-exporter\";\n        *binding_prefix_len = strlen(\"tls-exporter\");\n        binding_type = GNUTLS_CB_TLS_EXPORTER;\n        break;\n    default:\n        strophe_error(tls->ctx, \"tls\", \"Unsupported TLS Version: %s\",\n                      gnutls_protocol_get_name(tls_version));\n        return -1;\n    }\n\n    if (tls->channel_binding.data) {\n        gnutls_free(tls->channel_binding.data);\n        tls->channel_binding.data = NULL;\n    }\n    int ret = gnutls_session_channel_binding(tls->session, binding_type,\n                                             &tls->channel_binding);\n    if (ret) {\n        strophe_error(tls->ctx, \"tls\", \"could not get channel binding: %s\",\n                      gnutls_strerror(ret));\n    }\n    return ret;\n}\n\nconst void *tls_get_channel_binding_data(tls_t *tls, size_t *size)\n{\n    if (!tls->channel_binding.data || !tls->channel_binding.size) {\n        strophe_error(tls->ctx, \"tls\", \"No channel binding data available\");\n    }\n    *size = tls->channel_binding.size;\n    return tls->channel_binding.data;\n}\n\nint tls_start(tls_t *tls)\n{\n    sock_set_blocking(tls->conn->sock);\n    tls->lasterror = gnutls_handshake(tls->session);\n    sock_set_nonblocking(tls->conn->sock);\n\n    return tls->lasterror == GNUTLS_E_SUCCESS;\n}\n\nint tls_stop(tls_t *tls)\n{\n    tls->lasterror = gnutls_bye(tls->session, GNUTLS_SHUT_RDWR);\n    return tls->lasterror == GNUTLS_E_SUCCESS;\n}\n\nint tls_error(struct conn_interface *intf)\n{\n    return intf->conn->tls->lasterror;\n}\n\nint tls_is_recoverable(struct conn_interface *intf, int error)\n{\n    UNUSED(intf);\n    return !gnutls_error_is_fatal(error);\n}\n\nint tls_pending(struct conn_interface *intf)\n{\n    return gnutls_record_check_pending(intf->conn->tls->session);\n}\n\nint tls_read(struct conn_interface *intf, void *buff, size_t len)\n{\n    int ret;\n    tls_t *tls = intf->conn->tls;\n\n    ret = gnutls_record_recv(tls->session, buff, len);\n    tls->lasterror = ret < 0 ? ret : 0;\n\n    return ret;\n}\n\nint tls_write(struct conn_interface *intf, const void *buff, size_t len)\n{\n    int ret;\n    tls_t *tls = intf->conn->tls;\n\n    ret = gnutls_record_send(tls->session, buff, len);\n    tls->lasterror = ret < 0 ? ret : 0;\n\n    return ret;\n}\n\nint tls_clear_pending_write(struct conn_interface *intf)\n{\n    UNUSED(intf);\n    return 0;\n}\n"
  },
  {
    "path": "src/tls_openssl.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* tls_openssl.c\n** strophe XMPP client library -- TLS abstraction openssl impl.\n**\n** Copyright (C) 2005-008 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  TLS implementation with OpenSSL.\n */\n\n#include <errno.h> /* EINTR */\n#include <string.h>\n\n#ifndef _WIN32\n#include <sys/select.h>\n#else\n#include <winsock2.h>\n#endif\n\n#include <openssl/ssl.h>\n#include <openssl/err.h>\n#include <openssl/opensslv.h>\n#include <openssl/x509v3.h>\n#include <openssl/pkcs12.h>\n\n#include \"common.h\"\n#include \"tls.h\"\n#include \"sock.h\"\n\n/*\n * Redefine OPENSSL_VERSION_NUMBER for LibreSSL.\n * LibreSSL and OpenSSL use different and incompatible version schemes. Solve\n * this issue in the way how nginx project did.\n */\n#if (defined LIBRESSL_VERSION_NUMBER && OPENSSL_VERSION_NUMBER == 0x20000000L)\n#undef OPENSSL_VERSION_NUMBER\n#if (LIBRESSL_VERSION_NUMBER >= 0x2080000fL)\n#define OPENSSL_VERSION_NUMBER 0x1010000fL\n#elif (LIBRESSL_VERSION_NUMBER >= 0x2070000fL)\n#define OPENSSL_VERSION_NUMBER 0x1000200fL\n#else\n#define OPENSSL_VERSION_NUMBER 0x1000107fL\n#endif\n#endif\n\n#if OPENSSL_VERSION_NUMBER < 0x30000000L\n#define STROPHE_ERR_func_error_string(e) ERR_func_error_string(e)\n#define STROPHE_SSL_get1_peer_certificate(s) SSL_get_peer_certificate(s)\n#else\n#define STROPHE_ERR_func_error_string(e) \"\"\n#define STROPHE_SSL_get1_peer_certificate(s) SSL_get1_peer_certificate(s)\n#endif\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\nstatic const unsigned char *ASN1_STRING_get0_data(ASN1_STRING *asn1)\n{\n    return ASN1_STRING_data(asn1);\n}\n#endif\n\n#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined LIBRESSL_VERSION_NUMBER\nstatic int SSL_CTX_use_cert_and_key(SSL_CTX *ctx,\n                                    X509 *x509,\n                                    EVP_PKEY *privatekey,\n                                    STACK_OF(X509) * chain,\n                                    int override)\n{\n    UNUSED(override);\n    if (!ctx)\n        return 0;\n    if (x509 && !SSL_CTX_use_certificate(ctx, x509))\n        return 0;\n    if (privatekey && !SSL_CTX_use_PrivateKey(ctx, privatekey))\n        return 0;\n#ifdef SSL_CTX_set1_chain\n    if (chain && !SSL_CTX_set1_chain(ctx, chain))\n        return 0;\n#else\n    UNUSED(chain);\n#endif\n    return 1;\n}\n#endif\n\n#if OPENSSL_VERSION_NUMBER < 0x10000000L\nstatic int GENERAL_NAME_get0_otherName(const GENERAL_NAME *gen,\n                                       ASN1_OBJECT **poid,\n                                       ASN1_TYPE **pvalue)\n{\n    if (gen->type != GEN_OTHERNAME)\n        return 0;\n    if (poid)\n        *poid = gen->d.otherName->type_id;\n    if (pvalue)\n        *pvalue = gen->d.otherName->value;\n    return 1;\n}\n#endif\n\nstruct _tls {\n    xmpp_ctx_t *ctx;\n    sock_t sock;\n    SSL_CTX *ssl_ctx;\n    SSL *ssl;\n    X509 *client_cert;\n    void *channel_binding_data;\n    size_t channel_binding_size;\n    FILE *keylogfile;\n    int lasterror;\n};\n\nenum {\n    TLS_SHUTDOWN_MAX_RETRIES = 10,\n    TLS_TIMEOUT_SEC = 0,\n    TLS_TIMEOUT_USEC = 100000,\n};\n\nstatic void _tls_sock_wait(tls_t *tls, int error);\nstatic const char *_tls_error_str(int error, const char **tbl, size_t tbl_size);\nstatic void _tls_set_error(tls_t *tls, int error);\nstatic void _tls_log_error(xmpp_ctx_t *ctx);\nstatic void _tls_dump_cert_info(tls_t *tls);\nstatic X509 *_tls_cert_read(xmpp_conn_t *conn);\nstatic X509 *\n_tls_cert_read_p12(xmpp_conn_t *conn, EVP_PKEY **pkey, STACK_OF(X509) * *ca);\nstatic int _tls_xaddr_nid(void);\nstatic int _tls_xmppaddr_to_string(GENERAL_NAME *name, char **res);\nstatic int _tls_dnsname_to_string(GENERAL_NAME *name, char **res);\nstatic GENERAL_NAMES *_tls_conn_get_names(xmpp_conn_t *conn);\nstatic GENERAL_NAMES *_tls_cert_get_names(X509 *client_cert);\n\n#define TLS_ERROR_STR(error, table) \\\n    _tls_error_str(error, table, ARRAY_SIZE(table))\n\n#define TLS_ERROR_FIELD(x) [x] = #x\nconst char *tls_errors[] = {\n    TLS_ERROR_FIELD(SSL_ERROR_NONE),\n    TLS_ERROR_FIELD(SSL_ERROR_SSL),\n    TLS_ERROR_FIELD(SSL_ERROR_WANT_READ),\n    TLS_ERROR_FIELD(SSL_ERROR_WANT_WRITE),\n    TLS_ERROR_FIELD(SSL_ERROR_WANT_X509_LOOKUP),\n    TLS_ERROR_FIELD(SSL_ERROR_SYSCALL),\n    TLS_ERROR_FIELD(SSL_ERROR_ZERO_RETURN),\n    TLS_ERROR_FIELD(SSL_ERROR_WANT_CONNECT),\n    TLS_ERROR_FIELD(SSL_ERROR_WANT_ACCEPT),\n#ifndef LIBRESSL_VERSION_NUMBER\n#if OPENSSL_VERSION_NUMBER >= 0x10100000L\n    TLS_ERROR_FIELD(SSL_ERROR_WANT_ASYNC),\n    TLS_ERROR_FIELD(SSL_ERROR_WANT_ASYNC_JOB),\n#endif\n#if OPENSSL_VERSION_NUMBER >= 0x10101000L\n    TLS_ERROR_FIELD(SSL_ERROR_WANT_CLIENT_HELLO_CB),\n#endif\n#endif /* !LIBRESSL_VERSION_NUMBER */\n};\nconst char *cert_errors[] = {\n    TLS_ERROR_FIELD(X509_V_OK),\n#if OPENSSL_VERSION_NUMBER >= 0x10002000L\n    TLS_ERROR_FIELD(X509_V_ERR_UNSPECIFIED),\n#endif\n    TLS_ERROR_FIELD(X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT),\n    TLS_ERROR_FIELD(X509_V_ERR_UNABLE_TO_GET_CRL),\n    TLS_ERROR_FIELD(X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE),\n    TLS_ERROR_FIELD(X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE),\n    TLS_ERROR_FIELD(X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY),\n    TLS_ERROR_FIELD(X509_V_ERR_CERT_SIGNATURE_FAILURE),\n    TLS_ERROR_FIELD(X509_V_ERR_CRL_SIGNATURE_FAILURE),\n    TLS_ERROR_FIELD(X509_V_ERR_CERT_NOT_YET_VALID),\n    TLS_ERROR_FIELD(X509_V_ERR_CERT_HAS_EXPIRED),\n    TLS_ERROR_FIELD(X509_V_ERR_CRL_NOT_YET_VALID),\n    TLS_ERROR_FIELD(X509_V_ERR_CRL_HAS_EXPIRED),\n    TLS_ERROR_FIELD(X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD),\n    TLS_ERROR_FIELD(X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD),\n    TLS_ERROR_FIELD(X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD),\n    TLS_ERROR_FIELD(X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD),\n    TLS_ERROR_FIELD(X509_V_ERR_OUT_OF_MEM),\n    TLS_ERROR_FIELD(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),\n    TLS_ERROR_FIELD(X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN),\n    TLS_ERROR_FIELD(X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY),\n    TLS_ERROR_FIELD(X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE),\n    TLS_ERROR_FIELD(X509_V_ERR_CERT_CHAIN_TOO_LONG),\n    TLS_ERROR_FIELD(X509_V_ERR_CERT_REVOKED),\n    TLS_ERROR_FIELD(X509_V_ERR_INVALID_CA),\n    TLS_ERROR_FIELD(X509_V_ERR_PATH_LENGTH_EXCEEDED),\n    TLS_ERROR_FIELD(X509_V_ERR_INVALID_PURPOSE),\n    TLS_ERROR_FIELD(X509_V_ERR_CERT_UNTRUSTED),\n    TLS_ERROR_FIELD(X509_V_ERR_CERT_REJECTED),\n    TLS_ERROR_FIELD(X509_V_ERR_SUBJECT_ISSUER_MISMATCH),\n    TLS_ERROR_FIELD(X509_V_ERR_AKID_SKID_MISMATCH),\n    TLS_ERROR_FIELD(X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH),\n    TLS_ERROR_FIELD(X509_V_ERR_KEYUSAGE_NO_CERTSIGN),\n    TLS_ERROR_FIELD(X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER),\n    TLS_ERROR_FIELD(X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION),\n    TLS_ERROR_FIELD(X509_V_ERR_KEYUSAGE_NO_CRL_SIGN),\n    TLS_ERROR_FIELD(X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION),\n    TLS_ERROR_FIELD(X509_V_ERR_INVALID_NON_CA),\n    TLS_ERROR_FIELD(X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED),\n    TLS_ERROR_FIELD(X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE),\n    TLS_ERROR_FIELD(X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED),\n    TLS_ERROR_FIELD(X509_V_ERR_INVALID_EXTENSION),\n    TLS_ERROR_FIELD(X509_V_ERR_INVALID_POLICY_EXTENSION),\n    TLS_ERROR_FIELD(X509_V_ERR_NO_EXPLICIT_POLICY),\n    TLS_ERROR_FIELD(X509_V_ERR_APPLICATION_VERIFICATION),\n#if OPENSSL_VERSION_NUMBER >= 0x10002000L\n    TLS_ERROR_FIELD(X509_V_ERR_DIFFERENT_CRL_SCOPE),\n    TLS_ERROR_FIELD(X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE),\n    TLS_ERROR_FIELD(X509_V_ERR_UNNESTED_RESOURCE),\n    TLS_ERROR_FIELD(X509_V_ERR_PERMITTED_VIOLATION),\n    TLS_ERROR_FIELD(X509_V_ERR_EXCLUDED_VIOLATION),\n    TLS_ERROR_FIELD(X509_V_ERR_SUBTREE_MINMAX),\n    TLS_ERROR_FIELD(X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE),\n    TLS_ERROR_FIELD(X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX),\n    TLS_ERROR_FIELD(X509_V_ERR_UNSUPPORTED_NAME_SYNTAX),\n    TLS_ERROR_FIELD(X509_V_ERR_CRL_PATH_VALIDATION_ERROR),\n#ifndef LIBRESSL_VERSION_NUMBER\n    TLS_ERROR_FIELD(X509_V_ERR_SUITE_B_INVALID_VERSION),\n    TLS_ERROR_FIELD(X509_V_ERR_SUITE_B_INVALID_ALGORITHM),\n    TLS_ERROR_FIELD(X509_V_ERR_SUITE_B_INVALID_CURVE),\n    TLS_ERROR_FIELD(X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM),\n    TLS_ERROR_FIELD(X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED),\n    TLS_ERROR_FIELD(X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256),\n#endif /* !LIBRESSL_VERSION_NUMBER */\n    TLS_ERROR_FIELD(X509_V_ERR_HOSTNAME_MISMATCH),\n    TLS_ERROR_FIELD(X509_V_ERR_EMAIL_MISMATCH),\n    TLS_ERROR_FIELD(X509_V_ERR_IP_ADDRESS_MISMATCH),\n#endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */\n#if OPENSSL_VERSION_NUMBER >= 0x10100000L\n    TLS_ERROR_FIELD(X509_V_ERR_INVALID_CALL),\n    TLS_ERROR_FIELD(X509_V_ERR_STORE_LOOKUP),\n#ifndef LIBRESSL_VERSION_NUMBER\n    TLS_ERROR_FIELD(X509_V_ERR_PATH_LOOP),\n    TLS_ERROR_FIELD(X509_V_ERR_DANE_NO_MATCH),\n    TLS_ERROR_FIELD(X509_V_ERR_EE_KEY_TOO_SMALL),\n    TLS_ERROR_FIELD(X509_V_ERR_CA_KEY_TOO_SMALL),\n    TLS_ERROR_FIELD(X509_V_ERR_CA_MD_TOO_WEAK),\n    TLS_ERROR_FIELD(X509_V_ERR_NO_VALID_SCTS),\n    TLS_ERROR_FIELD(X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION),\n#if OPENSSL_VERSION_NUMBER >= 0x10101000L\n    TLS_ERROR_FIELD(X509_V_ERR_OCSP_VERIFY_NEEDED),\n    TLS_ERROR_FIELD(X509_V_ERR_OCSP_VERIFY_FAILED),\n    TLS_ERROR_FIELD(X509_V_ERR_OCSP_CERT_UNKNOWN),\n#endif /* OPENSSL_VERSION_NUMBER >= 0x10101000L */\n#endif /* !LIBRESSL_VERSION_NUMBER */\n#endif /* OPENSSL_VERSION_NUMBER >= 0x10100000L */\n};\n#undef TLS_ERROR_FIELD\n\nvoid tls_initialize(void)\n{\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    SSL_library_init();\n    SSL_load_error_strings();\n#else\n    OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);\n#endif\n    /* init xmppAddr OID */\n    _tls_xaddr_nid();\n}\n\nvoid tls_shutdown(void)\n{\n    /*\n     * FIXME: Don't free global tables, program or other libraries may use\n     * openssl after libstrophe finalization. Maybe better leak some fixed\n     * memory rather than cause random crashes of the main program.\n     */\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n    OBJ_cleanup();\n    ERR_free_strings();\n    EVP_cleanup();\n    CRYPTO_cleanup_all_ex_data();\n#if OPENSSL_VERSION_NUMBER >= 0x10002000L\n    SSL_COMP_free_compression_methods();\n#endif\n#if OPENSSL_VERSION_NUMBER < 0x10000000L\n    ERR_remove_state(0);\n#else\n    ERR_remove_thread_state(NULL);\n#endif\n#endif\n}\n\nint tls_error(struct conn_interface *intf)\n{\n    return intf->conn->tls->lasterror;\n}\n\n/** Search through the SubjectAlternativeNames and return the next\n *  id-on-xmppAddr element starting from `n`.\n */\nchar *tls_id_on_xmppaddr(xmpp_conn_t *conn, unsigned int n)\n{\n    char *ret = NULL;\n    int i, j;\n    GENERAL_NAMES *names = _tls_conn_get_names(conn);\n    if (!names) {\n        _tls_log_error(conn->ctx);\n        return NULL;\n    }\n    int num_names = sk_GENERAL_NAME_num(names);\n    for (i = j = 0; i < num_names; ++i) {\n        char *res;\n        GENERAL_NAME *name = sk_GENERAL_NAME_value(names, i);\n        if (name == NULL)\n            break;\n        if (_tls_xmppaddr_to_string(name, &res))\n            continue;\n        if (j == (int)n) {\n            strophe_debug(conn->ctx, \"tls\",\n                          \"extracted jid %s from id-on-xmppAddr\", res);\n            ret = strophe_strdup(conn->ctx, res);\n            OPENSSL_free(res);\n            break;\n        }\n        j++;\n        OPENSSL_free(res);\n    }\n    GENERAL_NAMES_free(names);\n    return ret;\n}\n\nunsigned int tls_id_on_xmppaddr_num(xmpp_conn_t *conn)\n{\n    unsigned int ret = 0;\n    GENERAL_NAMES *names = _tls_conn_get_names(conn);\n    if (!names) {\n        _tls_log_error(conn->ctx);\n        return 0;\n    }\n    int j, num_names = sk_GENERAL_NAME_num(names);\n    for (j = 0; j < num_names; ++j) {\n        GENERAL_NAME *name = sk_GENERAL_NAME_value(names, j);\n        if (_tls_xmppaddr_to_string(name, NULL))\n            continue;\n        ret++;\n    }\n    GENERAL_NAMES_free(names);\n    return ret;\n}\n\nstatic int _convert_ASN1TIME(ASN1_TIME *ansi_time, char *buf, size_t len)\n{\n    BIO *bio = BIO_new(BIO_s_mem());\n    int rc = ASN1_TIME_print(bio, ansi_time);\n    if (rc <= 0) {\n        BIO_free(bio);\n        return 0;\n    }\n    rc = BIO_gets(bio, buf, len);\n    if (rc <= 0) {\n        BIO_free(bio);\n        return 0;\n    }\n    BIO_free(bio);\n    return 1;\n}\n\nstatic char *_asn1_time_to_str(const xmpp_ctx_t *ctx, ASN1_TIME *t)\n{\n    char buf[128];\n    int res = _convert_ASN1TIME(t, buf, sizeof(buf));\n    if (res) {\n        return strophe_strdup(ctx, buf);\n    }\n    return NULL;\n}\n\nstatic char *\n_get_fingerprint(const xmpp_ctx_t *ctx, X509 *err_cert, xmpp_cert_element_t el)\n{\n    unsigned char buf[EVP_MAX_MD_SIZE];\n    unsigned int len;\n    int (*digest_fn)(const X509 *data, const EVP_MD *type, unsigned char *md,\n                     unsigned int *len);\n    const EVP_MD *digest;\n    switch (el) {\n    case XMPP_CERT_FINGERPRINT_SHA1:\n        digest_fn = X509_digest;\n        digest = EVP_sha1();\n        break;\n    case XMPP_CERT_FINGERPRINT_SHA256:\n        digest_fn = X509_digest;\n        digest = EVP_sha256();\n        break;\n    case XMPP_CERT_PUBKEY_FINGERPRINT_SHA256:\n        digest_fn = X509_pubkey_digest;\n        digest = EVP_sha256();\n        break;\n    default:\n        return NULL;\n    }\n    if (digest_fn(err_cert, digest, buf, &len) != 0) {\n        char fingerprint[4 * EVP_MAX_MD_SIZE];\n        hex_encode(fingerprint, buf, len);\n        return strophe_strdup(ctx, fingerprint);\n    }\n    return NULL;\n}\n\nstatic char *\n_get_alg(const xmpp_ctx_t *ctx, X509 *err_cert, xmpp_cert_element_t el)\n{\n    int alg_nid = NID_undef;\n\n    switch (el) {\n    case XMPP_CERT_KEYALG: {\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n        alg_nid = OBJ_obj2nid(err_cert->cert_info->key->algor->algorithm);\n#else\n        X509_PUBKEY *pubkey = X509_get_X509_PUBKEY(err_cert);\n        ASN1_OBJECT *ppkalg = NULL;\n        if (X509_PUBKEY_get0_param(&ppkalg, NULL, NULL, NULL, pubkey)) {\n            alg_nid = OBJ_obj2nid(ppkalg);\n        }\n#endif\n    } break;\n    case XMPP_CERT_SIGALG: {\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n        alg_nid = OBJ_obj2nid(err_cert->sig_alg->algorithm);\n#else\n        const X509_ALGOR *palg;\n        const ASN1_OBJECT *obj;\n        X509_get0_signature(NULL, &palg, err_cert);\n        X509_ALGOR_get0(&obj, NULL, NULL, palg);\n        alg_nid = OBJ_obj2nid(obj);\n#endif\n    } break;\n    default:\n        break;\n    }\n    if (alg_nid != NID_undef) {\n        const char *alg = OBJ_nid2ln(alg_nid);\n        if (alg) {\n            return strophe_strdup(ctx, alg);\n        }\n    }\n    return NULL;\n}\n\nstatic xmpp_tlscert_t *_x509_to_tlscert(xmpp_ctx_t *ctx, X509 *cert)\n{\n    char *subject, *issuer, buf[32];\n    xmpp_tlscert_t *tlscert = tlscert_new(ctx);\n    if (!tlscert)\n        return NULL;\n\n    BIO *b = BIO_new(BIO_s_mem());\n    if (!b)\n        goto error_out;\n    PEM_write_bio_X509(b, cert);\n    BUF_MEM *bptr;\n    BIO_get_mem_ptr(b, &bptr);\n    tlscert->pem = strophe_alloc(ctx, bptr->length + 1);\n    if (!tlscert->pem)\n        goto error_out;\n    memcpy(tlscert->pem, bptr->data, bptr->length);\n    tlscert->pem[bptr->length] = '\\0';\n    BIO_free(b);\n\n    subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);\n    if (!subject)\n        goto error_out;\n    tlscert->elements[XMPP_CERT_SUBJECT] = strophe_strdup(ctx, subject);\n    OPENSSL_free(subject);\n    issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n    if (!issuer)\n        goto error_out;\n    tlscert->elements[XMPP_CERT_ISSUER] = strophe_strdup(ctx, issuer);\n    OPENSSL_free(issuer);\n\n    tlscert->elements[XMPP_CERT_NOTBEFORE] =\n        _asn1_time_to_str(ctx, X509_get_notBefore(cert));\n    tlscert->elements[XMPP_CERT_NOTAFTER] =\n        _asn1_time_to_str(ctx, X509_get_notAfter(cert));\n\n    tlscert->elements[XMPP_CERT_FINGERPRINT_SHA1] =\n        _get_fingerprint(ctx, cert, XMPP_CERT_FINGERPRINT_SHA1);\n    tlscert->elements[XMPP_CERT_FINGERPRINT_SHA256] =\n        _get_fingerprint(ctx, cert, XMPP_CERT_FINGERPRINT_SHA256);\n    tlscert->elements[XMPP_CERT_PUBKEY_FINGERPRINT_SHA256] =\n        _get_fingerprint(ctx, cert, XMPP_CERT_PUBKEY_FINGERPRINT_SHA256);\n\n    strophe_snprintf(buf, sizeof(buf), \"%ld\", X509_get_version(cert) + 1);\n    tlscert->elements[XMPP_CERT_VERSION] = strophe_strdup(ctx, buf);\n\n    tlscert->elements[XMPP_CERT_KEYALG] = _get_alg(ctx, cert, XMPP_CERT_KEYALG);\n    tlscert->elements[XMPP_CERT_SIGALG] = _get_alg(ctx, cert, XMPP_CERT_SIGALG);\n\n    ASN1_INTEGER *serial = X509_get_serialNumber(cert);\n    BIGNUM *bn = ASN1_INTEGER_to_BN(serial, NULL);\n    if (bn) {\n        char *serialnumber = BN_bn2hex(bn);\n        if (serialnumber) {\n            tlscert->elements[XMPP_CERT_SERIALNUMBER] =\n                strophe_strdup(ctx, serialnumber);\n            OPENSSL_free(serialnumber);\n        }\n        BN_free(bn);\n    }\n\n    GENERAL_NAMES *names = _tls_cert_get_names(cert);\n    if (names) {\n        int j, num_names = sk_GENERAL_NAME_num(names);\n        size_t n = 0;\n        for (j = 0; j < num_names; ++j) {\n            char *res;\n            GENERAL_NAME *name = sk_GENERAL_NAME_value(names, j);\n            if (_tls_dnsname_to_string(name, &res))\n                continue;\n            if (tlscert_add_dnsname(tlscert, res))\n                strophe_debug(ctx, \"tls\", \"Can't store dnsName(%zu): %s\", n,\n                              res);\n            n++;\n            OPENSSL_free(res);\n        }\n        GENERAL_NAMES_free(names);\n    }\n\n    return tlscert;\nerror_out:\n    xmpp_tlscert_free(tlscert);\n    return NULL;\n}\n\nstatic int _tls_verify(int preverify_ok, X509_STORE_CTX *x509_ctx)\n{\n    if (preverify_ok == 1)\n        return 1;\n\n    SSL *ssl = X509_STORE_CTX_get_ex_data(x509_ctx,\n                                          SSL_get_ex_data_X509_STORE_CTX_idx());\n    xmpp_conn_t *conn = SSL_get_app_data(ssl);\n\n    if (!conn->certfail_handler) {\n        strophe_error(conn->ctx, \"tls\",\n                      \"No certfail handler set, canceling connection attempt\");\n        return 0;\n    }\n\n    X509 *err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);\n\n    xmpp_tlscert_t *tlscert = _x509_to_tlscert(conn->ctx, err_cert);\n\n    if (!tlscert)\n        return 0;\n\n    tlscert->conn = conn;\n\n    strophe_debug(conn->ctx, \"tls\", \"preverify_ok:%d\\nSubject: %s\\nIssuer: %s\",\n                  preverify_ok, tlscert->elements[XMPP_CERT_SUBJECT],\n                  tlscert->elements[XMPP_CERT_ISSUER]);\n\n    int ret = conn->certfail_handler(\n        tlscert,\n        X509_verify_cert_error_string(X509_STORE_CTX_get_error(x509_ctx)));\n\n    xmpp_tlscert_free(tlscert);\n\n    return ret;\n}\n\nstatic int _tls_password_callback(char *buf, int size, int rwflag, void *u)\n{\n    UNUSED(rwflag);\n    return tls_caching_password_callback(buf, size, u);\n}\n\n#if OPENSSL_VERSION_NUMBER >= 0x10101000L\nstatic void _keylog_cb(const SSL *ssl, const char *line)\n{\n    xmpp_conn_t *conn = SSL_get_app_data(ssl);\n    fwrite(line, strlen(line), 1, conn->tls->keylogfile);\n    fputc('\\n', conn->tls->keylogfile);\n    fflush(conn->tls->keylogfile);\n}\n#endif\n\nstatic void _try_open_keylogfile(tls_t *tls)\n{\n#if OPENSSL_VERSION_NUMBER >= 0x10101000L\n    const char *first_line = \"# SSL Key logfile generated by libstrophe\\n\";\n    const char *SSLKEYLOGFILE = getenv(\"SSLKEYLOGFILE\");\n    if (!SSLKEYLOGFILE || *SSLKEYLOGFILE == '\\0')\n        return;\n    tls->keylogfile = fopen(SSLKEYLOGFILE, \"abe\");\n    if (!tls->keylogfile) {\n        strophe_warn(tls->ctx, \"tls\", \"Could not open SSL keylog file %s\",\n                     SSLKEYLOGFILE);\n        return;\n    }\n    fwrite(first_line, strlen(first_line), 1, tls->keylogfile);\n    SSL_CTX_set_keylog_callback(tls->ssl_ctx, _keylog_cb);\n#else\n    UNUSED(tls);\n#endif\n}\n\ntls_t *tls_new(xmpp_conn_t *conn)\n{\n    tls_t *tls = strophe_alloc(conn->ctx, sizeof(*tls));\n\n    if (tls) {\n        int ret;\n#if OPENSSL_VERSION_NUMBER >= 0x10002000L\n        /* Hostname verification is supported in OpenSSL 1.0.2 and newer. */\n        X509_VERIFY_PARAM *param;\n#endif\n        memset(tls, 0, sizeof(*tls));\n\n        tls->ctx = conn->ctx;\n        tls->sock = conn->sock;\n#if OPENSSL_VERSION_NUMBER < 0x10100000L\n        tls->ssl_ctx = SSL_CTX_new(SSLv23_client_method());\n#else\n        tls->ssl_ctx = SSL_CTX_new(TLS_client_method());\n#endif\n        if (tls->ssl_ctx == NULL)\n            goto err;\n\n        /* Enable bug workarounds. */\n        SSL_CTX_set_options(tls->ssl_ctx, SSL_OP_ALL);\n\n        /* Disable insecure SSL/TLS versions. */\n        SSL_CTX_set_options(tls->ssl_ctx, SSL_OP_NO_SSLv2); /* DROWN */\n        SSL_CTX_set_options(tls->ssl_ctx, SSL_OP_NO_SSLv3); /* POODLE */\n        SSL_CTX_set_options(tls->ssl_ctx, SSL_OP_NO_TLSv1); /* BEAST */\n\n        if (conn->password_callback) {\n            SSL_CTX_set_default_passwd_cb(tls->ssl_ctx, _tls_password_callback);\n            SSL_CTX_set_default_passwd_cb_userdata(tls->ssl_ctx, conn);\n        }\n\n        if (conn->tls_client_cert && conn->tls_client_key) {\n            unsigned int retries = 0;\n            tls->client_cert = _tls_cert_read(conn);\n            if (!tls->client_cert) {\n                strophe_error(tls->ctx, \"tls\",\n                              \"could not read client certificate\");\n                goto err_free_ctx;\n            }\n\n            SSL_CTX_use_certificate_file(tls->ssl_ctx, conn->tls_client_cert,\n                                         SSL_FILETYPE_PEM);\n            while (retries++ < conn->password_retries) {\n                if (SSL_CTX_use_PrivateKey_file(\n                        tls->ssl_ctx, conn->tls_client_key, SSL_FILETYPE_PEM)) {\n                    break;\n                }\n                tls_clear_password_cache(conn);\n                unsigned long err = ERR_peek_error();\n                if ((ERR_GET_LIB(err) == ERR_LIB_EVP &&\n                     ERR_GET_REASON(err) == EVP_R_BAD_DECRYPT) ||\n                    (ERR_GET_LIB(err) == ERR_LIB_PEM &&\n                     ERR_GET_REASON(err) == PEM_R_BAD_DECRYPT)) {\n                    strophe_debug(tls->ctx, \"tls\", \"wrong password?\");\n                    continue;\n                }\n                strophe_error(tls->ctx, \"tls\",\n                              \"could not use private key %d %d\",\n                              ERR_GET_LIB(err), ERR_GET_REASON(err));\n                goto err_free_ctx;\n            }\n        } else if (conn->tls_client_cert) {\n            EVP_PKEY *pkey = NULL;\n            STACK_OF(X509) *ca = NULL;\n            X509 *cert = _tls_cert_read_p12(conn, &pkey, &ca);\n            if (!cert) {\n                goto err_free_ctx;\n            }\n\n            SSL_CTX_use_cert_and_key(tls->ssl_ctx, cert, pkey, ca, 1);\n\n            if (pkey)\n                EVP_PKEY_free(pkey);\n            if (ca)\n                sk_X509_pop_free(ca, X509_free);\n            tls->client_cert = cert;\n        } else {\n            /* If the server asks for a client certificate, don't send one. */\n            SSL_CTX_set_client_cert_cb(tls->ssl_ctx, NULL);\n        }\n\n        SSL_CTX_set_mode(tls->ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);\n\n        ret = SSL_CTX_set_default_verify_paths(tls->ssl_ctx);\n        if (ret == 0 && !conn->tls_trust) {\n            /*\n             * Returns 1 on success and 0 on failure. A missing default\n             * location is still treated as a success.\n             * Ignore errors when XMPP_CONN_FLAG_TRUST_TLS is set.\n             */\n            strophe_error(tls->ctx, \"tls\",\n                          \"SSL_CTX_set_default_verify_paths() failed\");\n            goto err_free_cert;\n        }\n\n        if (conn->tls_cafile || conn->tls_capath) {\n            if (SSL_CTX_load_verify_locations(tls->ssl_ctx, conn->tls_cafile,\n                                              conn->tls_capath) == 0) {\n                strophe_error(tls->ctx, \"tls\",\n                              \"SSL_CTX_load_verify_locations() failed\");\n                goto err_free_cert;\n            }\n        }\n\n        tls->ssl = SSL_new(tls->ssl_ctx);\n        if (tls->ssl == NULL)\n            goto err_free_cert;\n\n#if OPENSSL_VERSION_NUMBER >= 0x0908060L && !defined(OPENSSL_NO_TLSEXT)\n        /* Enable SNI. */\n        SSL_set_tlsext_host_name(tls->ssl, conn->domain);\n#endif\n\n        /* Trust server's certificate when user sets the flag explicitly.\n         * Otherwise call the verification callback */\n        if (conn->tls_trust)\n            SSL_set_verify(tls->ssl, SSL_VERIFY_NONE, NULL);\n        else\n            SSL_set_verify(tls->ssl, SSL_VERIFY_PEER, _tls_verify);\n        SSL_set_app_data(tls->ssl, conn);\n#if OPENSSL_VERSION_NUMBER >= 0x10002000L\n        /* Hostname verification is supported in OpenSSL 1.0.2 and newer. */\n        param = SSL_get0_param(tls->ssl);\n\n        /*\n         * Allow only complete wildcards.  RFC 6125 discourages wildcard usage\n         * completely, and lists internationalized domain names as a reason\n         * against partial wildcards.\n         * See https://tools.ietf.org/html/rfc6125#section-7.2 for more\n         * information.\n         */\n        X509_VERIFY_PARAM_set_hostflags(param,\n                                        X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);\n        X509_VERIFY_PARAM_set1_host(param, conn->domain, 0);\n#endif\n\n        ret = SSL_set_fd(tls->ssl, conn->sock);\n        if (ret <= 0)\n            goto err_free_ssl;\n\n        _try_open_keylogfile(tls);\n    }\n\n    return tls;\n\nerr_free_ssl:\n    SSL_free(tls->ssl);\nerr_free_cert:\n    X509_free(tls->client_cert);\nerr_free_ctx:\n    SSL_CTX_free(tls->ssl_ctx);\nerr:\n    strophe_free(conn->ctx, tls);\n    _tls_log_error(conn->ctx);\n    return NULL;\n}\n\nvoid tls_free(tls_t *tls)\n{\n    if (tls->keylogfile)\n        fclose(tls->keylogfile);\n    strophe_free(tls->ctx, tls->channel_binding_data);\n    SSL_free(tls->ssl);\n    X509_free(tls->client_cert);\n    SSL_CTX_free(tls->ssl_ctx);\n    strophe_free(tls->ctx, tls);\n}\n\nxmpp_tlscert_t *tls_peer_cert(xmpp_conn_t *conn)\n{\n    if (conn && conn->tls && conn->tls->ssl) {\n        X509 *cert = STROPHE_SSL_get1_peer_certificate(conn->tls->ssl);\n        if (cert) {\n            xmpp_tlscert_t *tlscert = _x509_to_tlscert(conn->ctx, cert);\n            X509_free(cert);\n            return tlscert;\n        }\n    }\n    return NULL;\n}\n\nint tls_set_credentials(tls_t *tls, const char *cafilename)\n{\n    UNUSED(tls);\n    UNUSED(cafilename);\n    return -1;\n}\n\nint tls_init_channel_binding(tls_t *tls,\n                             const char **binding_prefix,\n                             size_t *binding_prefix_len)\n{\n    const char *label = NULL;\n    size_t labellen = 0;\n    int ssl_version = SSL_version(tls->ssl);\n\n    switch (ssl_version) {\n    case SSL3_VERSION:\n        *binding_prefix = \"tls-unique\";\n        *binding_prefix_len = strlen(\"tls-unique\");\n        tls->channel_binding_size = 36;\n        break;\n    case TLS1_VERSION:\n    case TLS1_1_VERSION:\n    case TLS1_2_VERSION:\n        *binding_prefix = \"tls-unique\";\n        *binding_prefix_len = strlen(\"tls-unique\");\n        tls->channel_binding_size = 12;\n        break;\n#ifdef TLS1_3_VERSION\n    case TLS1_3_VERSION:\n        label = \"EXPORTER-Channel-Binding\";\n        labellen = 24;\n        *binding_prefix = \"tls-exporter\";\n        *binding_prefix_len = strlen(\"tls-exporter\");\n        tls->channel_binding_size = 32;\n        break;\n#endif\n    default:\n        strophe_error(tls->ctx, \"tls\", \"Unsupported TLS/SSL Version: %s\",\n                      SSL_get_version(tls->ssl));\n        return -1;\n    }\n\n    strophe_free_and_null(tls->ctx, tls->channel_binding_data);\n    tls->channel_binding_data =\n        strophe_alloc(tls->ctx, tls->channel_binding_size);\n    if (!tls->channel_binding_data)\n        return -1;\n\n    if (ssl_version <= TLS1_2_VERSION) {\n        size_t len;\n        if (SSL_session_reused(tls->ssl)) {\n            len = SSL_get_peer_finished(tls->ssl, tls->channel_binding_data,\n                                        tls->channel_binding_size);\n        } else {\n            len = SSL_get_finished(tls->ssl, tls->channel_binding_data,\n                                   tls->channel_binding_size);\n        }\n        if (len != tls->channel_binding_size) {\n            strophe_error(tls->ctx, \"tls\",\n                          \"Got channel binding data of wrong size %zu\", len);\n            return -1;\n        }\n    } else {\n        if (SSL_export_keying_material(tls->ssl, tls->channel_binding_data,\n                                       tls->channel_binding_size, label,\n                                       labellen, NULL, 0, 0) != 1) {\n            strophe_error(tls->ctx, \"tls\",\n                          \"Could not get channel binding data\");\n            return -1;\n        }\n    }\n    return 0;\n}\n\nconst void *tls_get_channel_binding_data(tls_t *tls, size_t *size)\n{\n    if (!tls->channel_binding_data || !tls->channel_binding_size) {\n        strophe_error(tls->ctx, \"tls\", \"No channel binding data available\");\n    }\n    *size = tls->channel_binding_size;\n    return tls->channel_binding_data;\n}\n\nint tls_start(tls_t *tls)\n{\n    int error;\n    int ret;\n    long x509_res;\n\n    /* Since we're non-blocking, loop the connect call until it\n       succeeds or fails */\n    while (1) {\n        ret = SSL_connect(tls->ssl);\n        error = ret <= 0 ? SSL_get_error(tls->ssl, ret) : 0;\n\n        if (ret == -1 && tls_is_recoverable(NULL, error)) {\n            /* wait for something to happen on the sock before looping back */\n            _tls_sock_wait(tls, error);\n            continue;\n        }\n\n        /* success or fatal error */\n        break;\n    }\n\n    x509_res = SSL_get_verify_result(tls->ssl);\n    if (x509_res == X509_V_OK) {\n        strophe_debug(tls->ctx, \"tls\", \"Certificate verification passed\");\n    } else {\n        strophe_debug(tls->ctx, \"tls\",\n                      \"Certificate verification FAILED, result=%s(%ld)\",\n                      TLS_ERROR_STR((int)x509_res, cert_errors), x509_res);\n        if (ret > 0)\n            strophe_debug(tls->ctx, \"tls\", \"User decided to connect anyways\");\n    }\n    _tls_dump_cert_info(tls);\n\n    _tls_set_error(tls, error);\n    return ret <= 0 ? 0 : 1;\n}\n\nint tls_stop(tls_t *tls)\n{\n    int retries = 0;\n    int error;\n    int ret;\n\n    /* According to OpenSSL.org, we must not call SSL_shutdown(3)\n       if a previous fatal error has occurred on a connection. */\n    if (tls->lasterror == SSL_ERROR_SYSCALL || tls->lasterror == SSL_ERROR_SSL)\n        return 1;\n\n    while (1) {\n        ++retries;\n        ret = SSL_shutdown(tls->ssl);\n        error = ret < 0 ? SSL_get_error(tls->ssl, ret) : 0;\n        if (ret == 1 || !tls_is_recoverable(NULL, error) ||\n            retries >= TLS_SHUTDOWN_MAX_RETRIES) {\n            break;\n        }\n        _tls_sock_wait(tls, error);\n    }\n    if (error == SSL_ERROR_SYSCALL && errno == 0) {\n        /*\n         * Handle special case when peer closes connection instead of\n         * proper shutdown.\n         */\n        error = 0;\n        ret = 1;\n    }\n    _tls_set_error(tls, error);\n\n    return ret <= 0 ? 0 : 1;\n}\n\nint tls_is_recoverable(struct conn_interface *intf, int error)\n{\n    UNUSED(intf);\n    return (error == SSL_ERROR_NONE || error == SSL_ERROR_WANT_READ ||\n            error == SSL_ERROR_WANT_WRITE || error == SSL_ERROR_WANT_CONNECT ||\n            error == SSL_ERROR_WANT_ACCEPT);\n}\n\nint tls_pending(struct conn_interface *intf)\n{\n    return SSL_pending(intf->conn->tls->ssl);\n}\n\nint tls_read(struct conn_interface *intf, void *buff, size_t len)\n{\n    int ret;\n    tls_t *tls = intf->conn->tls;\n\n    ret = SSL_read(tls->ssl, buff, len);\n    _tls_set_error(tls, ret <= 0 ? SSL_get_error(tls->ssl, ret) : 0);\n\n    return ret;\n}\n\nint tls_write(struct conn_interface *intf, const void *buff, size_t len)\n{\n    int ret;\n    tls_t *tls = intf->conn->tls;\n\n    ret = SSL_write(tls->ssl, buff, len);\n    _tls_set_error(tls, ret <= 0 ? SSL_get_error(tls->ssl, ret) : 0);\n\n    return ret;\n}\n\nint tls_clear_pending_write(struct conn_interface *intf)\n{\n    UNUSED(intf);\n    return 0;\n}\n\nstatic void _tls_sock_wait(tls_t *tls, int error)\n{\n    struct timeval tv;\n    fd_set rfds;\n    fd_set wfds;\n    int nfds;\n    int ret;\n\n    if (error == SSL_ERROR_NONE)\n        return;\n\n    FD_ZERO(&rfds);\n    FD_ZERO(&wfds);\n    if (error == SSL_ERROR_WANT_READ)\n        FD_SET(tls->sock, &rfds);\n    if (error == SSL_ERROR_WANT_WRITE)\n        FD_SET(tls->sock, &wfds);\n    nfds = (error == SSL_ERROR_WANT_READ || error == SSL_ERROR_WANT_WRITE)\n               ? tls->sock + 1\n               : 0;\n    do {\n        tv.tv_sec = TLS_TIMEOUT_SEC;\n        tv.tv_usec = TLS_TIMEOUT_USEC;\n        ret = select(nfds, &rfds, &wfds, NULL, &tv);\n    } while (ret == -1 && errno == EINTR);\n}\n\nstatic const char *_tls_error_str(int error, const char **tbl, size_t tbl_size)\n{\n    return (error >= 0 && (size_t)error < tbl_size) ? tbl[error] : \"UNKNOWN\";\n}\n\nstatic void _tls_set_error(tls_t *tls, int error)\n{\n    if (error != 0 && !tls_is_recoverable(NULL, error)) {\n        strophe_debug(tls->ctx, \"tls\", \"error=%s(%d) errno=%d lasterror=%d\",\n                      TLS_ERROR_STR(error, tls_errors), error, errno,\n                      tls->lasterror);\n        _tls_log_error(tls->ctx);\n    } else if (tls->lasterror && tls->lasterror != error) {\n        strophe_debug_verbose(1, tls->ctx, \"tls\", \"overwrite lasterror=%d\",\n                              tls->lasterror);\n    }\n    tls->lasterror = error;\n}\n\nstatic void _tls_log_error(xmpp_ctx_t *ctx)\n{\n    unsigned long e;\n\n    do {\n        e = ERR_get_error();\n        if (e != 0) {\n            strophe_debug(\n                ctx, \"tls\", \"error:%08X:%s:%s:%s\", e, ERR_lib_error_string(e),\n                STROPHE_ERR_func_error_string(e), ERR_reason_error_string(e));\n        }\n    } while (e != 0);\n}\n\nstatic void _tls_dump_cert_info(tls_t *tls)\n{\n    X509 *cert;\n    char *name;\n\n    cert = STROPHE_SSL_get1_peer_certificate(tls->ssl);\n    if (cert == NULL)\n        strophe_debug(tls->ctx, \"tls\", \"Certificate was not presented by peer\");\n    else {\n        name = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);\n        if (name != NULL) {\n            strophe_debug(tls->ctx, \"tls\", \"Subject=%s\", name);\n            OPENSSL_free(name);\n        }\n        name = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);\n        if (name != NULL) {\n            strophe_debug(tls->ctx, \"tls\", \"Issuer=%s\", name);\n            OPENSSL_free(name);\n        }\n        X509_free(cert);\n    }\n}\n\nstatic X509 *_tls_cert_read_x509(xmpp_conn_t *conn)\n{\n    if (conn->tls && conn->tls->client_cert)\n        return conn->tls->client_cert;\n    BIO *f = BIO_new_file(conn->tls_client_cert, \"r\");\n    if (!f) {\n        strophe_debug(conn->ctx, \"tls\", \"f == NULL\");\n        return NULL;\n    }\n    X509 *c = PEM_read_bio_X509(f, NULL, NULL, NULL);\n    BIO_free(f);\n    if (!c) {\n        _tls_log_error(conn->ctx);\n    }\n    return c;\n}\n\nstatic int _tls_parse_p12(PKCS12 *p12,\n                          const char *pass,\n                          EVP_PKEY **pkey,\n                          X509 **cert,\n                          STACK_OF(X509) * *ca)\n{\n    /* For some reason `PKCS12_parse()` fails without a `EVP_PKEY`\n     * so if the user doesn't want it, use a local one and free it\n     * again directly after parsing.\n     */\n    EVP_PKEY *pkey_;\n    if (!pkey)\n        pkey = &pkey_;\n    int parse_ok = PKCS12_parse(p12, pass, pkey, cert, ca);\n    if (pkey == &pkey_ && pkey_)\n        EVP_PKEY_free(pkey_);\n    return parse_ok;\n}\n\nstatic X509 *\n_tls_cert_read_p12(xmpp_conn_t *conn, EVP_PKEY **pkey, STACK_OF(X509) * *ca)\n{\n    if (conn->tls && conn->tls->client_cert && !pkey && !ca)\n        return conn->tls->client_cert;\n    X509 *cert = NULL;\n    PKCS12 *p12 = NULL;\n    BIO *f = BIO_new_file(conn->tls_client_cert, \"rb\");\n    if (!f) {\n        strophe_debug(conn->ctx, \"tls\", \"f == NULL\");\n        goto error_out;\n    }\n    p12 = d2i_PKCS12_bio(f, NULL);\n    BIO_free(f);\n    if (!p12) {\n        strophe_debug(conn->ctx, \"tls\", \"Could not read p12 file\");\n        goto error_out;\n    }\n\n    /* First try to open file w/o a pass */\n    if (_tls_parse_p12(p12, NULL, pkey, &cert, ca)) {\n        goto success;\n    }\n    cert = NULL;\n\n    unsigned int retries = 0;\n\n    pem_password_cb *cb = PEM_def_callback;\n    void *userdata = NULL;\n    if (conn->password_callback) {\n        cb = _tls_password_callback;\n        userdata = conn;\n    }\n\n    while (retries++ < conn->password_retries) {\n        char pass[PEM_BUFSIZE + 1];\n        int passlen = cb(pass, PEM_BUFSIZE, 0, userdata);\n        if (passlen < 0 || passlen > PEM_BUFSIZE)\n            goto error_out;\n        int parse_ok = _tls_parse_p12(p12, pass, pkey, &cert, ca);\n        if (parse_ok) {\n            goto success;\n        }\n        cert = NULL;\n        tls_clear_password_cache(conn);\n        int err = ERR_peek_last_error();\n        if (ERR_GET_LIB(err) == ERR_LIB_PKCS12 &&\n            ERR_GET_REASON(err) == PKCS12_R_MAC_VERIFY_FAILURE) {\n            strophe_debug(conn->ctx, \"tls\",\n                          \"Entered password is most likely wrong!\");\n            continue;\n        }\n        strophe_debug(conn->ctx, \"tls\", \"Could not parse PKCS#12\");\n        goto error_out;\n    }\nerror_out:\n    _tls_log_error(conn->ctx);\nsuccess:\n    if (p12)\n        PKCS12_free(p12);\n    return cert;\n}\n\nstatic X509 *_tls_cert_read(xmpp_conn_t *conn)\n{\n    if (conn->tls && conn->tls->client_cert)\n        return conn->tls->client_cert;\n    if (conn->tls_client_cert && !conn->tls_client_key) {\n        return _tls_cert_read_p12(conn, NULL, NULL);\n    }\n    return _tls_cert_read_x509(conn);\n}\n\nstatic int _tls_xaddr_nid(void)\n{\n    static int xaddr_nid = NID_undef;\n    if (xaddr_nid == NID_undef) {\n        xaddr_nid = OBJ_sn2nid(\"id-on-xmppAddr\");\n    }\n    if (xaddr_nid == NID_undef) {\n        xaddr_nid = OBJ_create(\"1.3.6.1.5.5.7.8.5\", \"id-on-xmppAddr\",\n                               \"XmppAddr Identifier\");\n    }\n    return xaddr_nid;\n}\n\nstatic GENERAL_NAMES *_tls_conn_get_names(xmpp_conn_t *conn)\n{\n    X509 *client_cert;\n    GENERAL_NAMES *names = NULL;\n    client_cert = _tls_cert_read(conn);\n    if (!client_cert)\n        return NULL;\n    names = _tls_cert_get_names(client_cert);\n    if (!conn->tls || !conn->tls->client_cert)\n        X509_free(client_cert);\n    return names;\n}\n\nstatic GENERAL_NAMES *_tls_cert_get_names(X509 *client_cert)\n{\n    int san = X509_get_ext_by_NID(client_cert, NID_subject_alt_name, 0);\n    X509_EXTENSION *san_ext = X509_get_ext(client_cert, san);\n    if (!san_ext)\n        return NULL;\n    ASN1_OCTET_STRING *data = X509_EXTENSION_get_data(san_ext);\n    if (!data)\n        return NULL;\n    const unsigned char *d = ASN1_STRING_get0_data(data);\n    if (!d)\n        return NULL;\n    return d2i_GENERAL_NAMES(NULL, &d, ASN1_STRING_length(data));\n}\n\n/** Convert GENERAL_NAME* to a string\n *\n *  This checks whether the GENERAL_NAME* that is given has the\n *  correct id-on-xmppAddr set and then optionally converts this\n *  form ASN.1 to a string/char*.\n *\n *  When `res` pointer is set to NULL this method doesn't allocate\n *  the result but only checks whether it is in the correct format.\n *\n *  @param name Pointer to the GENERAL_NAME that shall be converted\n *  @param res Result-pointer (optional, can be NULL)\n *\n *  @return classic Unix style - 0=success, 1=error\n */\nstatic int _tls_xmppaddr_to_string(GENERAL_NAME *name, char **res)\n{\n    ASN1_OBJECT *oid;\n    ASN1_TYPE *val;\n    if (!name || name->type != GEN_OTHERNAME)\n        return 1;\n    if (GENERAL_NAME_get0_otherName(name, &oid, &val) == 0)\n        return 1;\n    if (OBJ_obj2nid(oid) != _tls_xaddr_nid() || !val)\n        return 1;\n    if (!res)\n        return 0;\n    if (ASN1_STRING_to_UTF8((unsigned char **)res, val->value.asn1_string) < 0)\n        return 1;\n    return 0;\n}\n\nstatic int _tls_dnsname_to_string(GENERAL_NAME *name, char **res)\n{\n    ASN1_STRING *str;\n    if (!name || name->type != GEN_DNS)\n        return 1;\n    str = GENERAL_NAME_get0_value(name, NULL);\n    if (str == NULL)\n        return 1;\n    if (!res)\n        return 0;\n    if (ASN1_STRING_to_UTF8((unsigned char **)res, str) < 0)\n        return 1;\n    return 0;\n}\n"
  },
  {
    "path": "src/tls_schannel.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* tls_schannel.c\n** strophe XMPP client library -- TLS abstraction schannel impl.\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  TLS implementation with Win32 SChannel.\n */\n\n#include \"common.h\"\n#include \"tls.h\"\n#include \"sock.h\"\n\n#define SECURITY_WIN32\n#include <security.h>\n#include <schnlsp.h>\n\nstruct _tls {\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    sock_t sock;\n\n    HANDLE hsec32;\n    SecurityFunctionTable *sft;\n    CredHandle hcred;\n    SecPkgInfo *spi;\n    int init;\n\n    CtxtHandle hctxt;\n    SecPkgContext_StreamSizes spcss;\n\n    unsigned char *recvbuffer;\n    unsigned int recvbuffermaxlen;\n    unsigned int recvbufferpos;\n\n    unsigned char *readybuffer;\n    unsigned int readybufferpos;\n    unsigned int readybufferlen;\n\n    unsigned char *sendbuffer;\n    unsigned int sendbuffermaxlen;\n    unsigned int sendbufferlen;\n    unsigned int sendbufferpos;\n\n    SECURITY_STATUS lasterror;\n};\n\nvoid tls_initialize(void)\n{\n    return;\n}\n\nvoid tls_shutdown(void)\n{\n    return;\n}\n\nchar *tls_id_on_xmppaddr(xmpp_conn_t *conn, unsigned int n)\n{\n    UNUSED(n);\n    /* always fail */\n    strophe_error(conn->ctx, \"tls\", \"Client-Authentication not implemented\");\n    return NULL;\n}\n\nunsigned int tls_id_on_xmppaddr_num(xmpp_conn_t *conn)\n{\n    /* always fail */\n    strophe_error(conn->ctx, \"tls\", \"Client-Authentication not implemented\");\n    return 0;\n}\n\ntls_t *tls_new(xmpp_conn_t *conn)\n{\n    xmpp_ctx_t *ctx = conn->ctx;\n    sock_t sock = conn->sock;\n    tls_t *tls;\n    PSecurityFunctionTable (*pInitSecurityInterface)(void);\n    SCHANNEL_CRED scred;\n    int ret;\n    ALG_ID algs[1];\n\n    SecPkgCred_SupportedAlgs spc_sa;\n    SecPkgCred_CipherStrengths spc_cs;\n    SecPkgCred_SupportedProtocols spc_sp;\n\n    OSVERSIONINFO osvi;\n\n    memset(&osvi, 0, sizeof(osvi));\n    osvi.dwOSVersionInfoSize = sizeof(osvi);\n\n    GetVersionEx(&osvi);\n\n    /* no TLS support on win9x/me, despite what anyone says */\n    if (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) {\n        return NULL;\n    }\n\n    tls = strophe_alloc(ctx, sizeof(*tls));\n\n    if (!tls) {\n        return NULL;\n    }\n\n    memset(tls, 0, sizeof(*tls));\n    tls->ctx = ctx;\n    tls->conn = conn;\n    tls->sock = sock;\n\n    if (!(tls->hsec32 = LoadLibrary(\"secur32.dll\"))) {\n        tls_free(tls);\n        return NULL;\n    }\n\n    if (!(pInitSecurityInterface =\n              (void *)GetProcAddress(tls->hsec32, \"InitSecurityInterfaceA\"))) {\n        tls_free(tls);\n        return NULL;\n    }\n\n    tls->sft = pInitSecurityInterface();\n\n    if (!tls->sft) {\n        tls_free(tls);\n        return NULL;\n    }\n\n    ret = tls->sft->QuerySecurityPackageInfo(UNISP_NAME, &(tls->spi));\n\n    if (ret != SEC_E_OK) {\n        tls_free(tls);\n        return NULL;\n    }\n\n    strophe_debug(ctx, \"TLSS\", \"QuerySecurityPackageInfo() success\");\n\n    memset(&scred, 0, sizeof(scred));\n    scred.dwVersion = SCHANNEL_CRED_VERSION;\n    /*scred.grbitEnabledProtocols = SP_PROT_TLS1_CLIENT;*/\n    /* Remote server closes connection with forced RC4.\n       The below lines are commented to leave default system configuration */\n#if 0\n    /* Something down the line doesn't like AES, so force it to RC4 */\n    algs[0] = CALG_RC4;\n    scred.cSupportedAlgs = 1;\n    scred.palgSupportedAlgs = algs;\n#else\n    (void)algs;\n#endif\n\n    ret = tls->sft->AcquireCredentialsHandleA(\n        NULL, UNISP_NAME, SECPKG_CRED_OUTBOUND, NULL, &scred, NULL, NULL,\n        &(tls->hcred), NULL);\n\n    if (ret != SEC_E_OK) {\n        tls_free(tls);\n        return NULL;\n    }\n\n    strophe_debug(ctx, \"TLSS\", \"AcquireCredentialsHandle() success\");\n\n    tls->init = 1;\n\n    /* This bunch of queries should trip up wine until someone fixes\n     * schannel support there */\n    ret = tls->sft->QueryCredentialsAttributes(\n        &(tls->hcred), SECPKG_ATTR_SUPPORTED_ALGS, &spc_sa);\n    if (ret != SEC_E_OK) {\n        tls_free(tls);\n        return NULL;\n    }\n\n    ret = tls->sft->QueryCredentialsAttributes(\n        &(tls->hcred), SECPKG_ATTR_CIPHER_STRENGTHS, &spc_cs);\n    if (ret != SEC_E_OK) {\n        tls_free(tls);\n        return NULL;\n    }\n\n    ret = tls->sft->QueryCredentialsAttributes(\n        &(tls->hcred), SECPKG_ATTR_SUPPORTED_PROTOCOLS, &spc_sp);\n    if (ret != SEC_E_OK) {\n        tls_free(tls);\n        return NULL;\n    }\n\n    return tls;\n}\n\nvoid tls_free(tls_t *tls)\n{\n    if (tls->recvbuffer) {\n        strophe_free(tls->ctx, tls->recvbuffer);\n    }\n\n    if (tls->readybuffer) {\n        strophe_free(tls->ctx, tls->readybuffer);\n    }\n\n    if (tls->sendbuffer) {\n        strophe_free(tls->ctx, tls->sendbuffer);\n    }\n\n    if (tls->init) {\n        tls->sft->FreeCredentialsHandle(&(tls->hcred));\n    }\n\n    tls->sft = NULL;\n\n    if (tls->hsec32) {\n        FreeLibrary(tls->hsec32);\n        tls->hsec32 = NULL;\n    }\n\n    strophe_free(tls->ctx, tls);\n    return;\n}\n\nxmpp_tlscert_t *tls_peer_cert(xmpp_conn_t *conn)\n{\n    /* always fail */\n    strophe_error(conn->ctx, \"tls\", \"tls_peer_cert() not implemented\");\n    return NULL;\n}\n\nint tls_set_credentials(tls_t *tls, const char *cafilename)\n{\n    UNUSED(tls);\n    UNUSED(cafilename);\n    return -1;\n}\n\nint tls_init_channel_binding(tls_t *tls,\n                             const char **binding_prefix,\n                             size_t *binding_prefix_len)\n{\n    UNUSED(tls);\n    UNUSED(binding_prefix);\n    UNUSED(binding_prefix_len);\n    return -1;\n}\n\nconst void *tls_get_channel_binding_data(tls_t *tls, size_t *size)\n{\n    UNUSED(tls);\n    UNUSED(size);\n    return NULL;\n}\n\nint tls_start(tls_t *tls)\n{\n    ULONG ctxtreq = 0, ctxtattr = 0;\n    SecBufferDesc sbdin, sbdout;\n    SecBuffer sbin[2], sbout[1];\n    SECURITY_STATUS ret;\n    int sent;\n    char *name;\n    struct conn_interface *intf;\n\n    /* use the domain there as our name */\n    name = tls->conn->domain;\n    intf = &tls->conn->intf;\n\n    ctxtreq = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT |\n              ISC_REQ_CONFIDENTIALITY | ISC_RET_EXTENDED_ERROR |\n              ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM |\n              ISC_REQ_MANUAL_CRED_VALIDATION | ISC_REQ_INTEGRITY;\n\n    memset(&(sbout[0]), 0, sizeof(sbout[0]));\n    sbout[0].BufferType = SECBUFFER_TOKEN;\n\n    memset(&sbdout, 0, sizeof(sbdout));\n    sbdout.ulVersion = SECBUFFER_VERSION;\n    sbdout.cBuffers = 1;\n    sbdout.pBuffers = sbout;\n\n    memset(&(sbin[0]), 0, sizeof(sbin[0]));\n    sbin[0].BufferType = SECBUFFER_TOKEN;\n    sbin[0].pvBuffer = strophe_alloc(tls->ctx, tls->spi->cbMaxToken);\n    sbin[0].cbBuffer = tls->spi->cbMaxToken;\n\n    memset(&(sbin[1]), 0, sizeof(sbin[1]));\n    sbin[1].BufferType = SECBUFFER_EMPTY;\n\n    memset(&sbdin, 0, sizeof(sbdin));\n    sbdin.ulVersion = SECBUFFER_VERSION;\n    sbdin.cBuffers = 2;\n    sbdin.pBuffers = sbin;\n\n    ret = tls->sft->InitializeSecurityContextA(\n        &(tls->hcred), NULL, name, ctxtreq, 0, 0, NULL, 0, &(tls->hctxt),\n        &sbdout, &ctxtattr, NULL);\n\n    unsigned char *p = sbin[0].pvBuffer;\n    int len = 0;\n\n    while (ret == SEC_I_CONTINUE_NEEDED ||\n           ret == SEC_I_INCOMPLETE_CREDENTIALS ||\n           ret == SEC_E_INCOMPLETE_MESSAGE) {\n        int inbytes = 0;\n\n        if (ret != SEC_E_INCOMPLETE_MESSAGE) {\n            len = 0;\n            p = sbin[0].pvBuffer;\n        }\n\n        if (sbdout.pBuffers[0].cbBuffer) {\n            unsigned char *writebuff = sbdout.pBuffers[0].pvBuffer;\n            unsigned int writelen = sbdout.pBuffers[0].cbBuffer;\n\n            sent = sock_write(intf, writebuff, writelen);\n            if (sent == -1) {\n                tls->lasterror = sock_error(intf);\n            } else {\n                writebuff += sent;\n                writelen -= sent;\n            }\n            tls->sft->FreeContextBuffer(sbdout.pBuffers[0].pvBuffer);\n            sbdout.pBuffers[0].pvBuffer = NULL;\n            sbdout.pBuffers[0].cbBuffer = 0;\n        }\n\n        /* poll for a bit until the remote server stops sending data, ie it\n         * finishes sending the token */\n        inbytes = 1;\n        {\n            fd_set fds;\n            struct timeval tv;\n\n            tv.tv_sec = 2;\n            tv.tv_usec = 0;\n\n            FD_ZERO(&fds);\n            FD_SET(tls->sock, &fds);\n\n            select(tls->sock, &fds, NULL, NULL, &tv);\n        }\n\n        while (inbytes > 0) {\n            fd_set fds;\n            struct timeval tv;\n\n            tv.tv_sec = 0;\n            tv.tv_usec = 1000;\n\n            FD_ZERO(&fds);\n            FD_SET(tls->sock, &fds);\n\n            select(tls->sock, &fds, NULL, NULL, &tv);\n\n            inbytes = sock_read(intf, p, tls->spi->cbMaxToken - len);\n\n            if (inbytes > 0) {\n                len += inbytes;\n                p += inbytes;\n            } else {\n                tls->lasterror = sock_error(intf);\n            }\n        }\n\n        sbin[0].cbBuffer = len;\n\n        ret = tls->sft->InitializeSecurityContextA(\n            &(tls->hcred), &(tls->hctxt), name, ctxtreq, 0, 0, &sbdin, 0,\n            &(tls->hctxt), &sbdout, &ctxtattr, NULL);\n    }\n\n    if (ret == SEC_E_OK) {\n        if (sbdout.pBuffers[0].cbBuffer) {\n            unsigned char *writebuff = sbdout.pBuffers[0].pvBuffer;\n            unsigned int writelen = sbdout.pBuffers[0].cbBuffer;\n            sent = sock_write(intf, writebuff, writelen);\n            if (sent == -1) {\n                tls->lasterror = sock_error(intf);\n            } else {\n                writebuff += sent;\n                writelen -= sent;\n            }\n            tls->sft->FreeContextBuffer(sbdout.pBuffers[0].pvBuffer);\n            sbdout.pBuffers[0].pvBuffer = NULL;\n            sbdout.pBuffers[0].cbBuffer = 0;\n        }\n    }\n\n    strophe_free(tls->ctx, sbin[0].pvBuffer);\n\n    if (ret != SEC_E_OK) {\n        tls->lasterror = ret;\n        strophe_error(tls->ctx, \"TLSS\", \"Schannel error 0x%lx\",\n                      (unsigned long)ret);\n        return 0;\n    }\n\n    tls->sft->QueryContextAttributes(&(tls->hctxt), SECPKG_ATTR_STREAM_SIZES,\n                                     &(tls->spcss));\n\n    tls->recvbuffermaxlen = tls->spcss.cbHeader + tls->spcss.cbMaximumMessage +\n                            tls->spcss.cbTrailer;\n    tls->recvbuffer = strophe_alloc(tls->ctx, tls->recvbuffermaxlen);\n    tls->recvbufferpos = 0;\n\n    tls->sendbuffermaxlen = tls->spcss.cbHeader + tls->spcss.cbMaximumMessage +\n                            tls->spcss.cbTrailer;\n    tls->sendbuffer = strophe_alloc(tls->ctx, tls->sendbuffermaxlen);\n    tls->sendbufferpos = 0;\n    tls->sendbufferlen = 0;\n\n    tls->readybuffer = strophe_alloc(tls->ctx, tls->spcss.cbMaximumMessage);\n    tls->readybufferpos = 0;\n    tls->readybufferlen = 0;\n\n    return 1;\n}\n\nint tls_stop(tls_t *tls)\n{\n    UNUSED(tls);\n    return -1;\n}\n\nint tls_error(struct conn_interface *intf)\n{\n    return intf->conn->tls->lasterror;\n}\n\nint tls_is_recoverable(struct conn_interface *intf, int error)\n{\n    UNUSED(intf);\n    return (error == SEC_E_OK || error == SEC_E_INCOMPLETE_MESSAGE ||\n            error == WSAEWOULDBLOCK || error == WSAEMSGSIZE ||\n            error == WSAEINPROGRESS);\n}\n\nint tls_pending(struct conn_interface *intf)\n{\n    tls_t *tls = intf->conn->tls;\n    // There are 3 cases:\n    // - there is data in ready buffer, so it is by default pending\n    // - there is data in recv buffer. If it is not decrypted yet, means it\n    // was incomplete. This should be processed again only if there is data\n    // on the physical connection\n    // - there is data on the physical connection. This case is treated\n    // outside the tls (in event.c)\n\n    if (tls->readybufferpos < tls->readybufferlen) {\n        return tls->readybufferlen - tls->readybufferpos;\n    }\n\n    return 0;\n}\n\nint tls_read(struct conn_interface *intf, void *buff, size_t len)\n{\n    int bytes;\n    tls_t *tls = intf->conn->tls;\n\n    /* first, if we've got some ready data, put that in the buffer */\n    if (tls->readybufferpos < tls->readybufferlen) {\n        if (len < tls->readybufferlen - tls->readybufferpos) {\n            bytes = len;\n        } else {\n            bytes = tls->readybufferlen - tls->readybufferpos;\n        }\n\n        memcpy(buff, tls->readybuffer + tls->readybufferpos, bytes);\n\n        if (len < tls->readybufferlen - tls->readybufferpos) {\n            tls->readybufferpos += bytes;\n            return bytes;\n        } else {\n            unsigned char *newbuff = buff;\n            int read;\n            tls->readybufferpos += bytes;\n            newbuff += bytes;\n            read = tls_read(tls, newbuff, len - bytes);\n\n            if (read == -1) {\n                if (tls_is_recoverable(intf, tls->lasterror)) {\n                    return bytes;\n                }\n\n                return -1;\n            }\n\n            return bytes + read;\n        }\n    }\n\n    /* next, top up our recv buffer */\n    bytes = sock_read(intf, tls->recvbuffer + tls->recvbufferpos,\n                      tls->recvbuffermaxlen - tls->recvbufferpos);\n\n    if (bytes == 0) {\n        tls->lasterror = WSAECONNRESET;\n        return -1;\n    }\n\n    if (bytes == -1) {\n        if (!tls_is_recoverable(intf, sock_error(intf))) {\n            tls->lasterror = sock_error(intf);\n            return -1;\n        }\n    }\n\n    if (bytes > 0) {\n        tls->recvbufferpos += bytes;\n    }\n\n    /* next, try to decrypt the recv buffer */\n    if (tls->recvbufferpos > 0) {\n        SecBufferDesc sbddec;\n        SecBuffer sbdec[4];\n        int ret;\n\n        memset(&sbddec, 0, sizeof(sbddec));\n        sbddec.ulVersion = SECBUFFER_VERSION;\n        sbddec.cBuffers = 4;\n        sbddec.pBuffers = sbdec;\n\n        memset(&(sbdec[0]), 0, sizeof(sbdec[0]));\n        sbdec[0].BufferType = SECBUFFER_DATA;\n        sbdec[0].pvBuffer = tls->recvbuffer;\n        sbdec[0].cbBuffer = tls->recvbufferpos;\n\n        memset(&(sbdec[1]), 0, sizeof(sbdec[1]));\n        sbdec[1].BufferType = SECBUFFER_EMPTY;\n\n        memset(&(sbdec[2]), 0, sizeof(sbdec[2]));\n        sbdec[2].BufferType = SECBUFFER_EMPTY;\n\n        memset(&(sbdec[3]), 0, sizeof(sbdec[3]));\n        sbdec[3].BufferType = SECBUFFER_EMPTY;\n\n        ret = tls->sft->DecryptMessage(&(tls->hctxt), &sbddec, 0, NULL);\n\n        if (ret == SEC_E_OK) {\n            memcpy(tls->readybuffer, sbdec[1].pvBuffer, sbdec[1].cbBuffer);\n            tls->readybufferpos = 0;\n            tls->readybufferlen = sbdec[1].cbBuffer;\n            /* have we got some data left over?  If so, copy it to the start\n             * of the recv buffer */\n            if (sbdec[3].BufferType == SECBUFFER_EXTRA) {\n                memcpy(tls->recvbuffer, sbdec[3].pvBuffer, sbdec[3].cbBuffer);\n                tls->recvbufferpos = sbdec[3].cbBuffer;\n            } else {\n                tls->recvbufferpos = 0;\n            }\n\n            return tls_read(tls, buff, len);\n        } else if (ret == SEC_E_INCOMPLETE_MESSAGE) {\n            tls->lasterror = SEC_E_INCOMPLETE_MESSAGE;\n            return -1;\n        } else if (ret == SEC_I_RENEGOTIATE) {\n            ret = tls_start(tls);\n            if (!ret) {\n                return -1;\n            }\n\n            /* fake an incomplete message so we're called again */\n            tls->lasterror = SEC_E_INCOMPLETE_MESSAGE;\n            return -1;\n        }\n\n        /* something bad happened, so we bail */\n        tls->lasterror = ret;\n\n        return -1;\n    }\n\n    tls->lasterror = SEC_E_INCOMPLETE_MESSAGE;\n\n    return -1;\n}\n\nint tls_clear_pending_write(struct conn_interface *intf)\n{\n    tls_t *tls = intf->conn->tls;\n    if (tls->sendbufferpos < tls->sendbufferlen) {\n        int bytes;\n\n        bytes = sock_write(intf, tls->sendbuffer + tls->sendbufferpos,\n                           tls->sendbufferlen - tls->sendbufferpos);\n\n        if (bytes == -1) {\n            tls->lasterror = sock_error(intf);\n            return -1;\n        } else if (bytes > 0) {\n            tls->sendbufferpos += bytes;\n        }\n\n        if (tls->sendbufferpos < tls->sendbufferlen) {\n            return 0;\n        }\n    }\n\n    return 1;\n}\n\nint tls_write(struct conn_interface *intf, const void *buff, size_t len)\n{\n    SecBufferDesc sbdenc;\n    SecBuffer sbenc[4];\n    const unsigned char *p = buff;\n    int sent = 0, ret, remain = len;\n    tls_t *tls = intf->conn->tls;\n\n    ret = tls_clear_pending_write(tls);\n    if (ret <= 0) {\n        return ret;\n    }\n\n    tls->sendbufferpos = 0;\n    tls->sendbufferlen = 0;\n\n    memset(&sbdenc, 0, sizeof(sbdenc));\n    sbdenc.ulVersion = SECBUFFER_VERSION;\n    sbdenc.cBuffers = 4;\n    sbdenc.pBuffers = sbenc;\n\n    memset(&(sbenc[0]), 0, sizeof(sbenc[0]));\n    sbenc[0].BufferType = SECBUFFER_STREAM_HEADER;\n\n    memset(&(sbenc[1]), 0, sizeof(sbenc[1]));\n    sbenc[1].BufferType = SECBUFFER_DATA;\n\n    memset(&(sbenc[2]), 0, sizeof(sbenc[2]));\n    sbenc[2].BufferType = SECBUFFER_STREAM_TRAILER;\n\n    memset(&(sbenc[3]), 0, sizeof(sbenc[3]));\n    sbenc[3].BufferType = SECBUFFER_EMPTY;\n\n    sbenc[0].pvBuffer = tls->sendbuffer;\n    sbenc[0].cbBuffer = tls->spcss.cbHeader;\n\n    sbenc[1].pvBuffer = tls->sendbuffer + tls->spcss.cbHeader;\n\n    while (remain > 0) {\n        if (remain > tls->spcss.cbMaximumMessage) {\n            sbenc[1].cbBuffer = tls->spcss.cbMaximumMessage;\n        } else {\n            sbenc[1].cbBuffer = remain;\n        }\n\n        sbenc[2].pvBuffer =\n            (unsigned char *)sbenc[1].pvBuffer + sbenc[1].cbBuffer;\n        sbenc[2].cbBuffer = tls->spcss.cbTrailer;\n\n        memcpy(sbenc[1].pvBuffer, p, sbenc[1].cbBuffer);\n        p += tls->spcss.cbMaximumMessage;\n\n        tls->sendbufferlen =\n            sbenc[0].cbBuffer + sbenc[1].cbBuffer + sbenc[2].cbBuffer;\n\n        ret = tls->sft->EncryptMessage(&(tls->hctxt), 0, &sbdenc, 0);\n\n        if (ret != SEC_E_OK) {\n            tls->lasterror = ret;\n            return -1;\n        }\n\n        tls->sendbufferpos = 0;\n\n        ret = tls_clear_pending_write(tls);\n\n        if (ret == -1 && !tls_is_recoverable(intf, tls_error(tls))) {\n            return -1;\n        }\n\n        if (remain > tls->spcss.cbMaximumMessage) {\n            sent += tls->spcss.cbMaximumMessage;\n            remain -= tls->spcss.cbMaximumMessage;\n        } else {\n            sent += remain;\n            remain = 0;\n        }\n\n        if (ret == 0 ||\n            (ret == -1 && tls_is_recoverable(intf, tls_error(tls)))) {\n            return sent;\n        }\n    }\n\n    return sent;\n}\n"
  },
  {
    "path": "src/util.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* util.c\n** strophe XMPP client library -- various utility functions\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Utility functions.\n */\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n#ifdef _WIN32\n#include <winsock2.h>\n#else\n#include <sys/time.h>\n#include <time.h>\n#endif\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"ostypes.h\"\n#include \"util.h\"\n\n/** implement our own strdup that uses the ctx allocator */\n/** Duplicate a string.\n *  This function replaces the standard strdup library call with a version\n *  that uses the Strophe context object's allocator.\n *\n *  @param ctx a Strophe context object\n *  @param s a string\n *\n *  @return a newly allocated string with the same data as s or NULL on error\n */\nchar *strophe_strdup(const xmpp_ctx_t *ctx, const char *s)\n{\n    return strophe_strndup(ctx, s, SIZE_MAX);\n}\n\n/** Duplicate a string with a maximum length.\n *  This function replaces the standard strndup library call with a version\n *  that uses the Strophe context object's allocator.\n *\n *  @param ctx a Strophe context object\n *  @param s a string\n *  @param len the maximum length of the string to copy\n *\n *  @return a newly allocated string that contains at most `len` symbols\n *             of the original string or NULL on error\n */\nchar *strophe_strndup(const xmpp_ctx_t *ctx, const char *s, size_t len)\n{\n    char *copy;\n    size_t l;\n\n    l = strlen(s);\n    if (l > len)\n        l = len;\n\n    copy = strophe_alloc(ctx, l + 1);\n    if (!copy) {\n        strophe_error(ctx, \"xmpp\", \"failed to allocate required memory\");\n        return NULL;\n    }\n\n    memcpy(copy, s, l);\n    copy[l] = '\\0';\n\n    return copy;\n}\n\n/** strtok_r(3) implementation.\n *  This function has appeared in POSIX.1-2001, but not in C standard.\n *  For example, visual studio older than 2005 doesn't provide strtok_r()\n *  nor strtok_s().\n */\nchar *strophe_strtok_r(char *s, const char *delim, char **saveptr)\n{\n    size_t len;\n\n    s = s ? s : *saveptr;\n    len = strspn(s, delim);\n    s += len;\n    if (*s == '\\0')\n        return NULL;\n\n    len = strcspn(s, delim);\n    *saveptr = s[len] == '\\0' ? &s[len] : &s[len + 1];\n    s[len] = '\\0';\n\n    return s;\n}\n\n/** Return an integer based time stamp.\n *  This function uses gettimeofday or timeGetTime (on Win32 platforms) to\n *  compute an integer based time stamp.  This is used internally by the\n *  event loop and timed handlers.\n *\n *  @return an integer time stamp\n */\nuint64_t time_stamp(void)\n{\n#if defined(_WIN32) || defined(_XBOX_ONE)\n\n#ifndef __GNUC__\n#define EPOCHFILETIME (116444736000000000i64)\n#else\n#define EPOCHFILETIME (116444736000000000LL)\n#endif\n\n    FILETIME ft;\n    LARGE_INTEGER li;\n    __int64 t;\n\n    GetSystemTimeAsFileTime(&ft);\n    li.LowPart = ft.dwLowDateTime;\n    li.HighPart = ft.dwHighDateTime;\n    t = li.QuadPart;              /* In 100-nanosecond intervals */\n    t -= EPOCHFILETIME;           /* Offset to the Epoch time */\n    return (uint64_t)(t / 10000); /* Convert to milliseconds */\n#else\n    struct timeval tv;\n\n    gettimeofday(&tv, NULL);\n\n    return (uint64_t)tv.tv_sec * 1000 + (uint64_t)tv.tv_usec / 1000;\n#endif\n}\n\n/** Get the time elapsed between two time stamps.\n *  This function returns the time elapsed between t1 and t2 by subtracting\n *  t1 from t2.  If t2 happened before t1, the result will be negative.  This\n *  function is used internally by the event loop and timed handlers.\n *\n *  @param t1 first time stamp\n *  @param t2 second time stamp\n *\n *  @return number of milliseconds between the stamps\n */\nuint64_t time_elapsed(uint64_t t1, uint64_t t2)\n{\n    return (uint64_t)(t2 - t1);\n}\n\n/** Disconnect the stream with a memory error.\n *  This is a convenience function used internally by various parts of\n *  the Strophe library for terminating the connection because of a\n *  memory error.\n *\n *  @param conn a Strophe connection object\n */\nvoid disconnect_mem_error(xmpp_conn_t *conn)\n{\n    strophe_error(conn->ctx, \"xmpp\", \"Memory allocation error\");\n    xmpp_disconnect(conn);\n}\n\nint string_to_ul(const char *s, unsigned long *ul)\n{\n    char *endptr;\n    *ul = strtoul(s, &endptr, 10);\n    return *endptr != '\\0';\n}\n\nvoid hex_encode(char *writebuf, void *readbuf, size_t len)\n{\n    size_t i;\n    for (i = 0; i < len; i++) {\n        sprintf(writebuf, \"%02x\", ((unsigned char *)readbuf)[i]);\n        writebuf += 2;\n    }\n}\n"
  },
  {
    "path": "src/util.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* util.h\n** strophe XMPP client library -- various utility functions\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Internally used utility functions.\n */\n\n#ifndef __LIBSTROPHE_UTIL_H__\n#define __LIBSTROPHE_UTIL_H__\n\n#include \"ostypes.h\"\n\n#ifndef ARRAY_SIZE\n#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))\n#endif /* ARRAY_SIZE */\n\n/* TODO evaluate x and y only once */\n#define xmpp_min(x, y) ((x) < (y) ? (x) : (y))\n\n/* string functions */\nchar *strophe_strtok_r(char *s, const char *delim, char **saveptr);\n\n/* timing functions */\nuint64_t time_stamp(void);\nuint64_t time_elapsed(uint64_t t1, uint64_t t2);\n\n/* misc functions */\nint string_to_ul(const char *s, unsigned long *ul);\nvoid hex_encode(char *writebuf, void *readbuf, size_t len);\n\n#endif /* __LIBSTROPHE_UTIL_H__ */\n"
  },
  {
    "path": "src/uuid.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* uuid.c\n * strophe XMPP client library -- UUID generation\n *\n * Copyright (C) 2015 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/** @file\n *  Generation of UUID version 4 according to RFC4122.\n */\n\n#include \"strophe.h\"\n#include \"common.h\"\n\n/** @def XMPP_UUID_LEN\n *  UUID length in string representation excluding '\\0'.\n */\n#define XMPP_UUID_LEN 36\n\n/** Generate UUID version 4 in pre-allocated buffer.\n *\n *  @param ctx a Strophe context object\n *  @param uuid pre-allocated buffer of size (XMPP_UUID_LEN + 1)\n */\nstatic void crypto_uuid_gen(xmpp_ctx_t *ctx, char *uuid)\n{\n    unsigned char buf[16];\n    int i = 0; /* uuid iterator */\n    int j = 0; /* buf iterator */\n\n    static const char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7',\n                               '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n\n    xmpp_rand_bytes(ctx->rand, buf, sizeof(buf));\n    buf[8] &= 0x3f;\n    buf[8] |= 0x80;\n    buf[6] &= 0x0f;\n    buf[6] |= 0x40;\n    while (i < XMPP_UUID_LEN) {\n        if (i == 8 || i == 13 || i == 18 || i == 23)\n            uuid[i++] = '-';\n        else {\n            uuid[i++] = hex[buf[j] >> 4];\n            uuid[i++] = hex[buf[j] & 0x0f];\n            ++j;\n        }\n    }\n    uuid[XMPP_UUID_LEN] = '\\0';\n}\n\n/** Generate UUID version 4.\n *  This function allocates memory for the resulting string and must be freed\n *  with xmpp_free().\n *\n *  @param ctx a Strophe context object\n *\n *  @return ASCIIZ string\n */\nchar *xmpp_uuid_gen(xmpp_ctx_t *ctx)\n{\n    char *uuid;\n\n    uuid = strophe_alloc(ctx, XMPP_UUID_LEN + 1);\n    if (uuid != NULL) {\n        crypto_uuid_gen(ctx, uuid);\n    }\n    return uuid;\n}\n"
  },
  {
    "path": "strophe.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* strophe.h\n** strophe XMPP client library C API\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express or\n**  implied.\n**\n**  This software is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n/** @file\n *  Strophe public C API definitions.\n */\n\n#ifndef __LIBSTROPHE_STROPHE_H__\n#define __LIBSTROPHE_STROPHE_H__\n\n#include <stddef.h> /* size_t */\n#include <stdint.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* namespace defines */\n/** @def XMPP_NS_CLIENT\n *  Namespace definition for 'jabber:client'.\n */\n#define XMPP_NS_CLIENT \"jabber:client\"\n/** @def XMPP_NS_COMPONENT\n *  Namespace definition for 'jabber:component:accept'.\n */\n#define XMPP_NS_COMPONENT \"jabber:component:accept\"\n/** @def XMPP_NS_STREAMS\n *  Namespace definition for 'http://etherx.jabber.org/streams'.\n */\n#define XMPP_NS_STREAMS \"http://etherx.jabber.org/streams\"\n/** @def XMPP_NS_STREAMS_IETF\n *  Namespace definition for 'urn:ietf:params:xml:ns:xmpp-streams'.\n */\n#define XMPP_NS_STREAMS_IETF \"urn:ietf:params:xml:ns:xmpp-streams\"\n/** @def XMPP_NS_STANZAS_IETF\n *  Namespace definition for 'urn:ietf:params:xml:ns:xmpp-stanzas'.\n */\n#define XMPP_NS_STANZAS_IETF \"urn:ietf:params:xml:ns:xmpp-stanzas\"\n/** @def XMPP_NS_TLS\n *  Namespace definition for 'url:ietf:params:xml:ns:xmpp-tls'.\n */\n#define XMPP_NS_TLS \"urn:ietf:params:xml:ns:xmpp-tls\"\n/** @def XMPP_NS_SASL\n *  Namespace definition for 'urn:ietf:params:xml:ns:xmpp-sasl'.\n */\n#define XMPP_NS_SASL \"urn:ietf:params:xml:ns:xmpp-sasl\"\n/** @def XMPP_NS_BIND\n *  Namespace definition for 'urn:ietf:params:xml:ns:xmpp-bind'.\n */\n#define XMPP_NS_BIND \"urn:ietf:params:xml:ns:xmpp-bind\"\n/** @def XMPP_NS_SESSION\n *  Namespace definition for 'urn:ietf:params:xml:ns:xmpp-session'.\n */\n#define XMPP_NS_SESSION \"urn:ietf:params:xml:ns:xmpp-session\"\n/** @def XMPP_NS_AUTH\n *  Namespace definition for 'jabber:iq:auth'.\n */\n#define XMPP_NS_AUTH \"jabber:iq:auth\"\n/** @def XMPP_NS_DISCO_INFO\n *  Namespace definition for 'http://jabber.org/protocol/disco#info'.\n */\n#define XMPP_NS_DISCO_INFO \"http://jabber.org/protocol/disco#info\"\n/** @def XMPP_NS_DISCO_ITEMS\n *  Namespace definition for 'http://jabber.org/protocol/disco#items'.\n */\n#define XMPP_NS_DISCO_ITEMS \"http://jabber.org/protocol/disco#items\"\n/** @def XMPP_NS_ROSTER\n *  Namespace definition for 'jabber:iq:roster'.\n */\n#define XMPP_NS_ROSTER \"jabber:iq:roster\"\n/** @def XMPP_NS_REGISTER\n *  Namespace definition for 'jabber:iq:register'.\n */\n#define XMPP_NS_REGISTER \"jabber:iq:register\"\n/** @def XMPP_NS_SM\n *  Namespace definition for Stream Management.\n */\n#define XMPP_NS_SM \"urn:xmpp:sm:3\"\n/** @def XMPP_NS_COMPRESSION\n *  Namespace definition for Stream Compression.\n */\n#define XMPP_NS_COMPRESSION \"http://jabber.org/protocol/compress\"\n/** @def XMPP_NS_FEATURE_COMPRESSION\n *  Namespace definition for Stream Compression.\n */\n#define XMPP_NS_FEATURE_COMPRESSION \"http://jabber.org/features/compress\"\n\n/* error defines */\n/** @def XMPP_EOK\n *  Success error code.\n */\n#define XMPP_EOK 0\n/** @def XMPP_EMEM\n *  Memory related failure error code.\n *\n *  This is returned on allocation errors and signals that the host may\n *  be out of memory.\n */\n#define XMPP_EMEM -1\n/** @def XMPP_EINVOP\n *  Invalid operation error code.\n *\n *  This error code is returned when the operation was invalid and signals\n *  that the Strophe API is being used incorrectly.\n */\n#define XMPP_EINVOP -2\n/** @def XMPP_EINT\n *  Internal failure error code.\n */\n#define XMPP_EINT -3\n\n/* initialization and shutdown */\nvoid xmpp_initialize(void);\nvoid xmpp_shutdown(void);\n\n/* version */\nint xmpp_version_check(int major, int minor);\n\n/* run-time contexts */\n\n/* user-replaceable memory allocator */\ntypedef struct _xmpp_mem_t xmpp_mem_t;\n\n/* user-replaceable log object */\ntypedef struct _xmpp_log_t xmpp_log_t;\n\n/* opaque run time context containing the above hooks */\ntypedef struct _xmpp_ctx_t xmpp_ctx_t;\n\ntypedef struct _xmpp_tlscert_t xmpp_tlscert_t;\n\nxmpp_ctx_t *xmpp_ctx_new(const xmpp_mem_t *mem, const xmpp_log_t *log);\nvoid xmpp_ctx_free(xmpp_ctx_t *ctx);\n\n/* set the verbosity level of the ctx */\nvoid xmpp_ctx_set_verbosity(xmpp_ctx_t *ctx, int level);\n\n/* free some blocks returned by other APIs, for example the\n   buffer you get from xmpp_stanza_to_text */\nvoid xmpp_free(const xmpp_ctx_t *ctx, void *p);\n\nstruct _xmpp_mem_t {\n    void *(*alloc)(size_t size, void *userdata);\n    void (*free)(void *p, void *userdata);\n    void *(*realloc)(void *p, size_t size, void *userdata);\n    void *userdata;\n};\n\ntypedef enum {\n    XMPP_LEVEL_DEBUG,\n    XMPP_LEVEL_INFO,\n    XMPP_LEVEL_WARN,\n    XMPP_LEVEL_ERROR\n} xmpp_log_level_t;\n\ntypedef enum { XMPP_UNKNOWN, XMPP_CLIENT, XMPP_COMPONENT } xmpp_conn_type_t;\n\ntypedef void (*xmpp_log_handler)(void *userdata,\n                                 xmpp_log_level_t level,\n                                 const char *area,\n                                 const char *msg);\n\nstruct _xmpp_log_t {\n    xmpp_log_handler handler;\n    void *userdata;\n};\n\n/* return a default logger filtering at a given level */\nxmpp_log_t *xmpp_get_default_logger(xmpp_log_level_t level);\n\n/* connection */\n\n/* opaque connection object */\ntypedef struct _xmpp_conn_t xmpp_conn_t;\ntypedef struct _xmpp_stanza_t xmpp_stanza_t;\ntypedef struct _xmpp_sm_t xmpp_sm_state_t;\n\n/* connection flags */\n#define XMPP_CONN_FLAG_DISABLE_TLS (1UL << 0)\n#define XMPP_CONN_FLAG_MANDATORY_TLS (1UL << 1)\n#define XMPP_CONN_FLAG_LEGACY_SSL (1UL << 2)\n#define XMPP_CONN_FLAG_DIRECT_TLS XMPP_CONN_FLAG_LEGACY_SSL\n/** @def XMPP_CONN_FLAG_TRUST_TLS\n *  Trust server's certificate even if it is invalid.\n */\n#define XMPP_CONN_FLAG_TRUST_TLS (1UL << 3)\n/** @def XMPP_CONN_FLAG_LEGACY_AUTH\n *  Enable legacy authentication support.\n */\n#define XMPP_CONN_FLAG_LEGACY_AUTH (1UL << 4)\n/** @def XMPP_CONN_FLAG_DISABLE_SM\n *  Disable Stream-Management XEP-0198.\n */\n#define XMPP_CONN_FLAG_DISABLE_SM (1UL << 5)\n/** @def XMPP_CONN_FLAG_ENABLE_COMPRESSION\n *  Enable Stream-Compression XEP-0138.\n */\n#define XMPP_CONN_FLAG_ENABLE_COMPRESSION (1UL << 6)\n/** @def XMPP_CONN_FLAG_COMPRESSION_DONT_RESET\n *  Don't reset the compressed stream after each stanza.\n *  Only enable this flag if you know what you're doing.\n */\n#define XMPP_CONN_FLAG_COMPRESSION_DONT_RESET (1UL << 7)\n\n/* connect callback */\ntypedef enum {\n    XMPP_CONN_CONNECT,\n    XMPP_CONN_RAW_CONNECT,\n    XMPP_CONN_DISCONNECT,\n    XMPP_CONN_FAIL\n} xmpp_conn_event_t;\n\ntypedef enum {\n    XMPP_SE_BAD_FORMAT,\n    XMPP_SE_BAD_NS_PREFIX,\n    XMPP_SE_CONFLICT,\n    XMPP_SE_CONN_TIMEOUT,\n    XMPP_SE_HOST_GONE,\n    XMPP_SE_HOST_UNKNOWN,\n    XMPP_SE_IMPROPER_ADDR,\n    XMPP_SE_INTERNAL_SERVER_ERROR,\n    XMPP_SE_INVALID_FROM,\n    XMPP_SE_INVALID_ID,\n    XMPP_SE_INVALID_NS,\n    XMPP_SE_INVALID_XML,\n    XMPP_SE_NOT_AUTHORIZED,\n    XMPP_SE_POLICY_VIOLATION,\n    XMPP_SE_REMOTE_CONN_FAILED,\n    XMPP_SE_RESOURCE_CONSTRAINT,\n    XMPP_SE_RESTRICTED_XML,\n    XMPP_SE_SEE_OTHER_HOST,\n    XMPP_SE_SYSTEM_SHUTDOWN,\n    XMPP_SE_UNDEFINED_CONDITION,\n    XMPP_SE_UNSUPPORTED_ENCODING,\n    XMPP_SE_UNSUPPORTED_STANZA_TYPE,\n    XMPP_SE_UNSUPPORTED_VERSION,\n    XMPP_SE_XML_NOT_WELL_FORMED\n} xmpp_error_type_t;\n\n/** Certificate Elements\n *\n *  @ingroup TLS\n */\ntypedef enum {\n    XMPP_CERT_VERSION,                   /**< X.509 Version */\n    XMPP_CERT_SERIALNUMBER,              /**< SerialNumber */\n    XMPP_CERT_SUBJECT,                   /**< Subject */\n    XMPP_CERT_ISSUER,                    /**< Issuer */\n    XMPP_CERT_NOTBEFORE,                 /**< Issued on */\n    XMPP_CERT_NOTAFTER,                  /**< Expires on */\n    XMPP_CERT_KEYALG,                    /**< Public Key Algorithm */\n    XMPP_CERT_SIGALG,                    /**< Certificate Signature Algorithm */\n    XMPP_CERT_FINGERPRINT_SHA1,          /**< Fingerprint SHA-1 */\n    XMPP_CERT_FINGERPRINT_SHA256,        /**< Fingerprint SHA-256 */\n    XMPP_CERT_PUBKEY_FINGERPRINT_SHA256, /**< SHA-256 fingerprint of pubkey */\n    XMPP_CERT_ELEMENT_MAX                /**< Last element of the enum */\n} xmpp_cert_element_t;\n\ntypedef struct {\n    xmpp_error_type_t type;\n    char *text;\n    xmpp_stanza_t *stanza;\n} xmpp_stream_error_t;\n\ntypedef void (*xmpp_conn_handler)(xmpp_conn_t *conn,\n                                  xmpp_conn_event_t event,\n                                  int error,\n                                  xmpp_stream_error_t *stream_error,\n                                  void *userdata);\n\n/** The Handler function which will be called when the TLS stack can't\n *  verify the authenticity of a Certificate that gets presented by\n *  the server we're trying to connect to.\n *\n *  When this function is called and details of the `cert` have to be\n *  kept, please copy them yourself. The `cert` object will be free'd\n *  automatically when this function returns.\n *\n *  NB: `errormsg` is specific per certificate on OpenSSL and the same\n *      for all certificates on GnuTLS.\n *\n *  @param cert a Strophe certificate object\n *  @param errormsg The error that caused this.\n *\n *  @return 0 if the connection attempt should be terminated,\n *          1 if the connection should be established.\n *\n *  @ingroup TLS\n */\ntypedef int (*xmpp_certfail_handler)(const xmpp_tlscert_t *cert,\n                                     const char *const errormsg);\n\n/** The Handler function which will be called when the TLS stack can't\n *  decrypt a password protected key file.\n *\n *  When this callback is called it shall write a NULL-terminated\n *  string of maximum length `pw_max - 1` to `pw`.\n *\n *  This is currently only supported for GnuTLS and OpenSSL.\n *\n *  On 2022-02-02 the following maximum lengths are valid:\n *  ```\n *  include/gnutls/pkcs11.h: #define GNUTLS_PKCS11_MAX_PIN_LEN 256\n *  include/openssl/pem.h: #define PEM_BUFSIZE 1024\n *  ```\n *\n *  We expect the buffer to be NULL-terminated, therefore the usable lengths\n *  are:\n *\n *  * 255 for GnuTLS\n *  * 1023 for OpenSSL\n *\n *  Useful API's inside this callback are e.g.\n *\n *  \\ref xmpp_conn_get_keyfile\n *\n *\n *  @param pw       The buffer where the password shall be stored.\n *  @param pw_max   The maximum length of the password.\n *  @param conn     The Strophe connection object this callback originates from.\n *  @param userdata The userdata pointer as supplied when setting this callback.\n *\n *  @return -1 on error, else the number of bytes written to `pw` w/o\n *           terminating NUL byte\n *\n *  @ingroup TLS\n */\ntypedef int (*xmpp_password_callback)(char *pw,\n                                      size_t pw_max,\n                                      xmpp_conn_t *conn,\n                                      void *userdata);\n\n/** The function which will be called when Strophe creates a new socket.\n *\n *  The `sock` argument is a pointer that is dependent on the architecture\n *  Strophe is compiled for.\n *\n *  For POSIX compatible systems usage shall be:\n *  ```\n *  int soc = *((int*)sock);\n *  ```\n *\n *  On Windows usage shall be:\n *  ```\n *  SOCKET soc = *((SOCKET*)sock);\n *  ```\n *\n *  This function will be called for each socket that is created.\n *\n *  `examples/bot.c` uses a libstrophe supplied callback function that sets\n *  basic keepalive parameters (`xmpp_sockopt_cb_keepalive()`).\n *\n *  `examples/complex.c` implements a custom function that could be useful\n *  for an application.\n *\n *  @param conn     The Strophe connection object this callback originates from.\n *  @param sock     A pointer to the underlying file descriptor.\n *\n *  @return 0 on success, -1 on error\n *\n *  @ingroup Connections\n */\ntypedef int (*xmpp_sockopt_callback)(xmpp_conn_t *conn, void *sock);\n\n/* an example callback that sets basic keepalive parameters */\nint xmpp_sockopt_cb_keepalive(xmpp_conn_t *conn, void *sock);\n\nvoid xmpp_send_error(xmpp_conn_t *conn, xmpp_error_type_t type, char *text);\nxmpp_conn_t *xmpp_conn_new(xmpp_ctx_t *ctx);\nxmpp_conn_t *xmpp_conn_clone(xmpp_conn_t *conn);\nint xmpp_conn_release(xmpp_conn_t *conn);\n\nlong xmpp_conn_get_flags(const xmpp_conn_t *conn);\nint xmpp_conn_set_flags(xmpp_conn_t *conn, long flags);\nconst char *xmpp_conn_get_jid(const xmpp_conn_t *conn);\nconst char *xmpp_conn_get_bound_jid(const xmpp_conn_t *conn);\nvoid xmpp_conn_set_jid(xmpp_conn_t *conn, const char *jid);\nvoid xmpp_conn_set_cafile(xmpp_conn_t *const conn, const char *path);\nvoid xmpp_conn_set_capath(xmpp_conn_t *const conn, const char *path);\nvoid xmpp_conn_set_certfail_handler(xmpp_conn_t *const conn,\n                                    xmpp_certfail_handler hndl);\nxmpp_tlscert_t *xmpp_conn_get_peer_cert(xmpp_conn_t *const conn);\nvoid xmpp_conn_set_password_callback(xmpp_conn_t *conn,\n                                     xmpp_password_callback cb,\n                                     void *userdata);\nvoid xmpp_conn_set_password_retries(xmpp_conn_t *conn, unsigned int retries);\nconst char *xmpp_conn_get_keyfile(const xmpp_conn_t *conn);\nvoid xmpp_conn_set_client_cert(xmpp_conn_t *conn,\n                               const char *cert,\n                               const char *key);\nunsigned int xmpp_conn_cert_xmppaddr_num(xmpp_conn_t *conn);\nchar *xmpp_conn_cert_xmppaddr(xmpp_conn_t *conn, unsigned int n);\nconst char *xmpp_conn_get_pass(const xmpp_conn_t *conn);\nvoid xmpp_conn_set_pass(xmpp_conn_t *conn, const char *pass);\nxmpp_ctx_t *xmpp_conn_get_context(xmpp_conn_t *conn);\nint xmpp_conn_is_secured(xmpp_conn_t *conn);\nvoid xmpp_conn_set_sockopt_callback(xmpp_conn_t *conn,\n                                    xmpp_sockopt_callback callback);\nint xmpp_conn_is_connecting(xmpp_conn_t *conn);\nint xmpp_conn_is_connected(xmpp_conn_t *conn);\nint xmpp_conn_is_disconnected(xmpp_conn_t *conn);\nint xmpp_conn_send_queue_len(const xmpp_conn_t *conn);\n\ntypedef enum {\n    XMPP_QUEUE_OLDEST = -1,\n    XMPP_QUEUE_YOUNGEST = -2,\n} xmpp_queue_element_t;\nchar *xmpp_conn_send_queue_drop_element(xmpp_conn_t *conn,\n                                        xmpp_queue_element_t which);\n\nint xmpp_conn_set_sm_state(xmpp_conn_t *conn, xmpp_sm_state_t *sm_state);\nxmpp_sm_state_t *xmpp_conn_get_sm_state(xmpp_conn_t *conn);\n\n/** The function which will be called when Strophe updates its internal SM\n *  state.\n *\n *  Please note that you have to create a copy of the buffer, since the library\n *  will free the buffer right after return of the callback function.\n *\n *\n *  @param conn            The Strophe connection object this callback\n *                         originates from.\n *  @param ctx             The `ctx` pointer as passed to\n *                         \\ref xmpp_conn_set_sm_callback\n *  @param sm_state        A pointer to a buffer containing the serialized SM\n *                         state.\n *  @param sm_state_len    The length of `sm_state`.\n *\n *  @return 0 on success, -1 on error\n *\n *  @ingroup Connections\n */\ntypedef void (*xmpp_sm_callback)(xmpp_conn_t *conn,\n                                 void *ctx,\n                                 const unsigned char *sm_state,\n                                 size_t sm_state_len);\nvoid xmpp_conn_set_sm_callback(xmpp_conn_t *conn,\n                               xmpp_sm_callback cb,\n                               void *ctx);\nint xmpp_conn_restore_sm_state(xmpp_conn_t *conn,\n                               const unsigned char *sm_state,\n                               size_t sm_state_len);\n\nvoid xmpp_free_sm_state(xmpp_sm_state_t *sm_state);\n\nint xmpp_connect_client(xmpp_conn_t *conn,\n                        const char *altdomain,\n                        unsigned short altport,\n                        xmpp_conn_handler callback,\n                        void *userdata);\n\nint xmpp_connect_component(xmpp_conn_t *conn,\n                           const char *server,\n                           unsigned short port,\n                           xmpp_conn_handler callback,\n                           void *userdata);\n\nint xmpp_connect_raw(xmpp_conn_t *conn,\n                     const char *altdomain,\n                     unsigned short altport,\n                     xmpp_conn_handler callback,\n                     void *userdata);\nint xmpp_conn_open_stream_default(xmpp_conn_t *conn);\nint xmpp_conn_open_stream(xmpp_conn_t *conn,\n                          char **attributes,\n                          size_t attributes_len);\nint xmpp_conn_tls_start(xmpp_conn_t *conn);\n\nvoid xmpp_disconnect(xmpp_conn_t *conn);\n\nvoid xmpp_send(xmpp_conn_t *conn, xmpp_stanza_t *stanza);\n\nvoid xmpp_send_raw_string(xmpp_conn_t *conn, const char *fmt, ...);\nvoid xmpp_send_raw(xmpp_conn_t *conn, const char *data, size_t len);\n\n/* handlers */\n\n/* if the handler returns false it is removed */\ntypedef int (*xmpp_timed_handler)(xmpp_conn_t *conn, void *userdata);\n\nvoid xmpp_timed_handler_add(xmpp_conn_t *conn,\n                            xmpp_timed_handler handler,\n                            unsigned long period,\n                            void *userdata);\nvoid xmpp_timed_handler_delete(xmpp_conn_t *conn, xmpp_timed_handler handler);\n\n/* if the handler returns false it is removed */\ntypedef int (*xmpp_global_timed_handler)(xmpp_ctx_t *ctx, void *userdata);\n\nvoid xmpp_global_timed_handler_add(xmpp_ctx_t *ctx,\n                                   xmpp_global_timed_handler handler,\n                                   unsigned long period,\n                                   void *userdata);\nvoid xmpp_global_timed_handler_delete(xmpp_ctx_t *ctx,\n                                      xmpp_global_timed_handler handler);\n\n/* if the handler returns false it is removed */\ntypedef int (*xmpp_handler)(xmpp_conn_t *conn,\n                            xmpp_stanza_t *stanza,\n                            void *userdata);\n\nvoid xmpp_handler_add(xmpp_conn_t *conn,\n                      xmpp_handler handler,\n                      const char *ns,\n                      const char *name,\n                      const char *type,\n                      void *userdata);\nvoid xmpp_handler_delete(xmpp_conn_t *conn, xmpp_handler handler);\n\nvoid xmpp_id_handler_add(xmpp_conn_t *conn,\n                         xmpp_handler handler,\n                         const char *id,\n                         void *userdata);\nvoid xmpp_id_handler_delete(xmpp_conn_t *conn,\n                            xmpp_handler handler,\n                            const char *id);\n\n/*\nvoid xmpp_register_stanza_handler(conn, stanza, xmlns, type, handler)\n*/\n\n/* stanzas */\n\n/* allocate and initialize a blank stanza */\nxmpp_stanza_t *xmpp_stanza_new(xmpp_ctx_t *ctx);\nxmpp_stanza_t *xmpp_stanza_new_from_string(xmpp_ctx_t *ctx, const char *str);\n\n/* clone a stanza */\nxmpp_stanza_t *xmpp_stanza_clone(xmpp_stanza_t *stanza);\n\n/* copies a stanza and all children */\nxmpp_stanza_t *xmpp_stanza_copy(const xmpp_stanza_t *stanza);\n\n/* free a stanza object and it's contents */\nint xmpp_stanza_release(xmpp_stanza_t *stanza);\n\nxmpp_ctx_t *xmpp_stanza_get_context(const xmpp_stanza_t *stanza);\n\nint xmpp_stanza_is_text(xmpp_stanza_t *stanza);\nint xmpp_stanza_is_tag(xmpp_stanza_t *stanza);\n\n/* marshall a stanza into text for transmission or display */\nint xmpp_stanza_to_text(xmpp_stanza_t *stanza, char **buf, size_t *buflen);\n\nxmpp_stanza_t *xmpp_stanza_get_children(xmpp_stanza_t *stanza);\nxmpp_stanza_t *xmpp_stanza_get_child_by_name(xmpp_stanza_t *stanza,\n                                             const char *name);\nxmpp_stanza_t *xmpp_stanza_get_child_by_ns(xmpp_stanza_t *stanza,\n                                           const char *ns);\nxmpp_stanza_t *xmpp_stanza_get_child_by_name_and_ns(xmpp_stanza_t *stanza,\n                                                    const char *name,\n                                                    const char *ns);\n/* helper macro for names with a namespace */\n#define XMPP_STANZA_NAME_IN_NS(name, ns) name \"[@ns='\" ns \"']\"\nxmpp_stanza_t *xmpp_stanza_get_child_by_path(xmpp_stanza_t *stanza, ...);\nxmpp_stanza_t *xmpp_stanza_get_next(xmpp_stanza_t *stanza);\nint xmpp_stanza_add_child(xmpp_stanza_t *stanza, xmpp_stanza_t *child);\nint xmpp_stanza_add_child_ex(xmpp_stanza_t *stanza,\n                             xmpp_stanza_t *child,\n                             int do_clone);\n\nconst char *xmpp_stanza_get_attribute(xmpp_stanza_t *stanza, const char *name);\nint xmpp_stanza_get_attribute_count(xmpp_stanza_t *stanza);\nint xmpp_stanza_get_attributes(xmpp_stanza_t *stanza,\n                               const char **attr,\n                               int attrlen);\n/* concatenate all child text nodes.  this function\n * returns a string that must be freed by the caller */\nchar *xmpp_stanza_get_text(xmpp_stanza_t *stanza);\nconst char *xmpp_stanza_get_text_ptr(xmpp_stanza_t *stanza);\nconst char *xmpp_stanza_get_name(xmpp_stanza_t *stanza);\n/* set_attribute adds/replaces attributes */\nint xmpp_stanza_set_attribute(xmpp_stanza_t *stanza,\n                              const char *key,\n                              const char *value);\nint xmpp_stanza_set_name(xmpp_stanza_t *stanza, const char *name);\nint xmpp_stanza_set_text(xmpp_stanza_t *stanza, const char *text);\nint xmpp_stanza_set_text_with_size(xmpp_stanza_t *stanza,\n                                   const char *text,\n                                   size_t size);\nint xmpp_stanza_del_attribute(xmpp_stanza_t *stanza, const char *name);\n\n/* common stanza helpers */\nconst char *xmpp_stanza_get_ns(xmpp_stanza_t *stanza);\nconst char *xmpp_stanza_get_type(xmpp_stanza_t *stanza);\nconst char *xmpp_stanza_get_id(xmpp_stanza_t *stanza);\nconst char *xmpp_stanza_get_to(xmpp_stanza_t *stanza);\nconst char *xmpp_stanza_get_from(xmpp_stanza_t *stanza);\nint xmpp_stanza_set_ns(xmpp_stanza_t *stanza, const char *ns);\nint xmpp_stanza_set_id(xmpp_stanza_t *stanza, const char *id);\nint xmpp_stanza_set_type(xmpp_stanza_t *stanza, const char *type);\nint xmpp_stanza_set_to(xmpp_stanza_t *stanza, const char *to);\nint xmpp_stanza_set_from(xmpp_stanza_t *stanza, const char *from);\n\n/* allocate and initialize a stanza in reply to another */\nxmpp_stanza_t *xmpp_stanza_reply(xmpp_stanza_t *stanza);\nxmpp_stanza_t *xmpp_stanza_reply_error(xmpp_stanza_t *stanza,\n                                       const char *error_type,\n                                       const char *condition,\n                                       const char *text);\n\n/* stanza subclasses */\nxmpp_stanza_t *xmpp_message_new(xmpp_ctx_t *ctx,\n                                const char *type,\n                                const char *to,\n                                const char *id);\nchar *xmpp_message_get_body(xmpp_stanza_t *msg);\nint xmpp_message_set_body(xmpp_stanza_t *msg, const char *text);\n\nxmpp_stanza_t *xmpp_iq_new(xmpp_ctx_t *ctx, const char *type, const char *id);\nxmpp_stanza_t *xmpp_presence_new(xmpp_ctx_t *ctx);\nxmpp_stanza_t *\nxmpp_error_new(xmpp_ctx_t *ctx, xmpp_error_type_t type, const char *text);\n\n/* jid */\n\n/* these return new strings that must be xmpp_free()'d */\nchar *xmpp_jid_new(xmpp_ctx_t *ctx,\n                   const char *node,\n                   const char *domain,\n                   const char *resource);\nchar *xmpp_jid_bare(xmpp_ctx_t *ctx, const char *jid);\nchar *xmpp_jid_node(xmpp_ctx_t *ctx, const char *jid);\nchar *xmpp_jid_domain(xmpp_ctx_t *ctx, const char *jid);\nchar *xmpp_jid_resource(xmpp_ctx_t *ctx, const char *jid);\n\n/* event loop */\n\nvoid xmpp_run_once(xmpp_ctx_t *ctx, unsigned long timeout);\nvoid xmpp_run(xmpp_ctx_t *ctx);\nvoid xmpp_stop(xmpp_ctx_t *ctx);\nvoid xmpp_ctx_set_timeout(xmpp_ctx_t *ctx, unsigned long timeout);\n\n/* TLS certificates */\n\nxmpp_ctx_t *xmpp_tlscert_get_ctx(const xmpp_tlscert_t *cert);\nxmpp_conn_t *xmpp_tlscert_get_conn(const xmpp_tlscert_t *cert);\nvoid *xmpp_tlscert_get_userdata(const xmpp_tlscert_t *cert);\nconst char *xmpp_tlscert_get_pem(const xmpp_tlscert_t *cert);\nconst char *xmpp_tlscert_get_dnsname(const xmpp_tlscert_t *cert, size_t n);\nconst char *xmpp_tlscert_get_string(const xmpp_tlscert_t *cert,\n                                    xmpp_cert_element_t elmnt);\nconst char *xmpp_tlscert_get_description(xmpp_cert_element_t elmnt);\nvoid xmpp_tlscert_free(xmpp_tlscert_t *cert);\n\n/* UUID */\n\nchar *xmpp_uuid_gen(xmpp_ctx_t *ctx);\n\n/* SHA1 */\n\n/** @def XMPP_SHA1_DIGEST_SIZE\n *  Size of the SHA1 message digest.\n */\n#define XMPP_SHA1_DIGEST_SIZE 20\n\ntypedef struct _xmpp_sha1_t xmpp_sha1_t;\n\nchar *xmpp_sha1(xmpp_ctx_t *ctx, const unsigned char *data, size_t len);\nvoid xmpp_sha1_digest(const unsigned char *data,\n                      size_t len,\n                      unsigned char *digest);\n\nxmpp_sha1_t *xmpp_sha1_new(xmpp_ctx_t *ctx);\nvoid xmpp_sha1_free(xmpp_sha1_t *sha1);\nvoid xmpp_sha1_update(xmpp_sha1_t *sha1, const unsigned char *data, size_t len);\nvoid xmpp_sha1_final(xmpp_sha1_t *sha1);\nchar *xmpp_sha1_to_string(xmpp_sha1_t *sha1, char *s, size_t slen);\nchar *xmpp_sha1_to_string_alloc(xmpp_sha1_t *sha1);\nvoid xmpp_sha1_to_digest(xmpp_sha1_t *sha1, unsigned char *digest);\n\n/* Base64 */\n\nchar *\nxmpp_base64_encode(xmpp_ctx_t *ctx, const unsigned char *data, size_t len);\nchar *xmpp_base64_decode_str(xmpp_ctx_t *ctx, const char *base64, size_t len);\nvoid xmpp_base64_decode_bin(xmpp_ctx_t *ctx,\n                            const char *base64,\n                            size_t len,\n                            unsigned char **out,\n                            size_t *outlen);\n\n/* RNG */\n\ntypedef struct _xmpp_rand_t xmpp_rand_t;\n\n/** Create new xmpp_rand_t object.\n *\n *  @param ctx A Strophe context object\n *\n *  @ingroup Random\n */\nxmpp_rand_t *xmpp_rand_new(xmpp_ctx_t *ctx);\n\n/** Destroy an xmpp_rand_t object.\n *\n *  @param ctx A Strophe context object\n *  @param rand A xmpp_rand_t object\n *\n *  @ingroup Random\n */\nvoid xmpp_rand_free(xmpp_ctx_t *ctx, xmpp_rand_t *rand);\n\n/** Generate random integer.\n *  Analogue of rand(3).\n *\n *  @ingroup Random\n */\nint xmpp_rand(xmpp_rand_t *rand);\n\n/** Generate random bytes.\n *  Generates len bytes and stores them to the output buffer.\n *\n *  @param rand A xmpp_rand_t object\n *  @param output A buffer where a len random bytes will be placed.\n *  @param len Number of bytes reserved for the output..\n *\n *  @ingroup Random\n */\nvoid xmpp_rand_bytes(xmpp_rand_t *rand, unsigned char *output, size_t len);\n\n/** Generate a nonce that is printable randomized string.\n *  This function doesn't allocate memory and doesn't fail.\n *\n *  @param rand A xmpp_rand_t object\n *  @param output A buffer where a NULL-terminated string will be placed.\n *                The string will contain len-1 printable symbols.\n *  @param len Number of bytes reserved for the output string, including\n *             end of line '\\0'.\n *\n *  @ingroup Random\n */\nvoid xmpp_rand_nonce(xmpp_rand_t *rand, char *output, size_t len);\n\n/*\n * Formerly \"private but exported\" functions made public for now to announce\n * deprecation */\n#include <stdarg.h>\n\n/**\n * XMPP_DEPRECATED(x) macro to show a compiler warning for deprecated API\n * functions\n *\n * @param x The function that can be used as a replacement or 'internal' if\n * there is no replacement\n */\n#if defined(__GNUC__)\n#if (__GNUC__ * 100 + __GNUC_MINOR__ >= 405)\n#define XMPP_DEPRECATED(x) __attribute__((deprecated(\"replaced by \" #x)))\n#elif (__GNUC__ * 100 + __GNUC_MINOR__ >= 300)\n#define XMPP_DEPRECATED(x) __attribute__((deprecated))\n#endif\n#elif defined(_MSC_VER) && _MSC_VER >= 1500\n#define XMPP_DEPRECATED(x) __declspec(deprecated(\"replaced by \" #x))\n#else\n#define XMPP_DEPRECATED(x)\n#endif\n\nXMPP_DEPRECATED(internal) void *xmpp_alloc(const xmpp_ctx_t *ctx, size_t size);\nXMPP_DEPRECATED(internal)\nvoid *xmpp_realloc(const xmpp_ctx_t *ctx, void *p, size_t size);\nXMPP_DEPRECATED(internal)\nchar *xmpp_strdup(const xmpp_ctx_t *ctx, const char *s);\nXMPP_DEPRECATED(internal)\nchar *xmpp_strndup(const xmpp_ctx_t *ctx, const char *s, size_t len);\n\nXMPP_DEPRECATED(internal)\nchar *xmpp_strtok_r(char *s, const char *delim, char **saveptr);\nXMPP_DEPRECATED(internal)\nint xmpp_snprintf(char *str, size_t count, const char *fmt, ...);\nXMPP_DEPRECATED(internal)\nint xmpp_vsnprintf(char *str, size_t count, const char *fmt, va_list arg);\n\nXMPP_DEPRECATED(internal)\nvoid xmpp_log(const xmpp_ctx_t *ctx,\n              xmpp_log_level_t level,\n              const char *area,\n              const char *fmt,\n              va_list ap);\nXMPP_DEPRECATED(internal)\nvoid xmpp_error(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...);\nXMPP_DEPRECATED(internal)\nvoid xmpp_warn(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...);\nXMPP_DEPRECATED(internal)\nvoid xmpp_info(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...);\nXMPP_DEPRECATED(internal)\nvoid xmpp_debug(const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...);\nXMPP_DEPRECATED(internal)\nvoid xmpp_debug_verbose(\n    int level, const xmpp_ctx_t *ctx, const char *area, const char *fmt, ...);\n\nXMPP_DEPRECATED(xmpp_conn_set_sockopt_callback)\nvoid xmpp_conn_set_keepalive(xmpp_conn_t *conn, int timeout, int interval);\nXMPP_DEPRECATED(xmpp_conn_set_flags)\nvoid xmpp_conn_disable_tls(xmpp_conn_t *conn);\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __LIBSTROPHE_STROPHE_H__ */\n"
  },
  {
    "path": "testbuild.sh",
    "content": "#!/bin/sh\n\nlogfile=\"../../testbuild.log\"\nerrfile=\"../../testerr.log\"\n\nerr_out() {\n  tail $logfile\n  exit 1\n}\n\n./bootstrap.sh\n./configure >> $logfile 2>> $errfile || err_out\nmake -j$(( `nproc` * 2 + 1 )) >> $logfile 2>> $errfile || err_out\nmake check >> $logfile 2>> $errfile || err_out\n"
  },
  {
    "path": "tests/cert.pem",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDIDCCAqagAwIBAgIIddFxfQ2VcRIwCgYIKoZIzj0EAwQwSzFJMEcGA1UEAwxA\ndmVyeS5sb25nLnVzZXJuYW1lQHNvLnRoZS5hc24xLmxlbmd0aC5pcy5hLnZhbGlk\nLmFzY2lpLmNoYXJhY3RlcjAgFw0yMzA4MDkxMzI3MDBaGA8yMTI0MDgwOTEzMjcw\nMFowSzFJMEcGA1UEAwxAdmVyeS5sb25nLnVzZXJuYW1lQHNvLnRoZS5hc24xLmxl\nbmd0aC5pcy5hLnZhbGlkLmFzY2lpLmNoYXJhY3RlcjB2MBAGByqGSM49AgEGBSuB\nBAAiA2IABHfN9a5xAEPYWz+0O6Jfe95WGUeuq6Eca5po4UGcJgs78L6d4KT+FR/a\nyDSi/BmS0ZAksXbshkSjQA6XmAwWkNInJF/buAwh/hFVAOXwx3eKtguPskxg1xYj\n0WZ3WrY9oKOCAVMwggFPMAkGA1UdEwQCMAAwHQYDVR0OBBYEFNeonZqrLTGCm3Vk\n+X3TtMfDQVf4MGQGA1UdIwRdMFuhT6RNMEsxSTBHBgNVBAMMQHZlcnkubG9uZy51\nc2VybmFtZUBzby50aGUuYXNuMS5sZW5ndGguaXMuYS52YWxpZC5hc2NpaS5jaGFy\nYWN0ZXKCCHXRcX0NlXESMAsGA1UdDwQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcD\nAjCBmgYDVR0RBIGSMIGPoE4GCCsGAQUFBwgFoEIMQHZlcnkubG9uZy51c2VybmFt\nZUBzby50aGUuYXNuMS5sZW5ndGguaXMuYS52YWxpZC5hc2NpaS5jaGFyYWN0ZXKB\nDnlldEBub3RoZXIuc2Fugg53d3cuc3Ryb3BoZS5pbaAdBggrBgEFBQcIBaARDA9z\nZWNvbmRAeG1wcC5qaWQwCgYIKoZIzj0EAwQDaAAwZQIxAJTzJY/q/zFws0FPPfVI\nVXc+kaGdxwzM1FKlVMwxl+PzXAoeL0Z7FtGSkaCWyaokaAIwLaYxuQhgisetYxbU\nqTyv0MdS2uUy6NNcVNztWCMS350TuuVm3f9wmwOjfaeoHft3\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "tests/check_parser.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* check_parser.h\n** strophe XMPP client library -- parser tests\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express or\n**  implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"parser.h\"\n\n#include \"test.h\"\n\n#define fail_unless(expr)                                               \\\n    do {                                                                \\\n        int result = (expr);                                            \\\n        if (!result) {                                                  \\\n            printf(\"%s:%d: Assertion failed: %s\\n\", __FILE__, __LINE__, \\\n                   #expr);                                              \\\n            exit(1);                                                    \\\n        }                                                               \\\n    } while (0)\n\nstatic void create_destroy(void)\n{\n    xmpp_ctx_t *ctx;\n    parser_t *parser;\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n    parser = parser_new(ctx, NULL, NULL, NULL, NULL);\n    fail_unless(parser != NULL);\n    parser_free(parser);\n    xmpp_ctx_free(ctx);\n}\n\nint cbtest_got_start = 0;\nvoid cbtest_handle_start(char *name, char **attrs, void *userdata)\n{\n    (void)attrs;\n    (void)userdata;\n\n    if (strcmp(name, \"stream\") == 0)\n        cbtest_got_start = 1;\n}\n\nint cbtest_got_end = 0;\nvoid cbtest_handle_end(char *name, void *userdata)\n{\n    (void)userdata;\n\n    if (strcmp(name, \"stream\") == 0)\n        cbtest_got_end = 1;\n}\n\nint cbtest_got_stanza = 0;\nvoid cbtest_handle_stanza(xmpp_stanza_t *stanza, void *userdata)\n{\n    (void)userdata;\n\n    if (strcmp(xmpp_stanza_get_name(stanza), \"message\") == 0)\n        cbtest_got_stanza = 1;\n}\n\nstatic void callbacks(void)\n{\n    xmpp_ctx_t *ctx;\n    parser_t *parser;\n    int ret;\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n    parser = parser_new(ctx, cbtest_handle_start, cbtest_handle_end,\n                        cbtest_handle_stanza, NULL);\n\n    ret = parser_feed(parser, \"<stream>\", 8);\n    fail_unless(ret != 0);\n    ret = parser_feed(parser, \"<message/>\", 10);\n    fail_unless(ret != 0);\n    ret = parser_feed(parser, \"</stream>\", 9);\n    fail_unless(ret != 0);\n\n    fail_unless(cbtest_got_start == 1);\n    fail_unless(cbtest_got_end == 1);\n    fail_unless(cbtest_got_stanza == 1);\n\n    parser_free(parser);\n    xmpp_ctx_free(ctx);\n}\n\nint main()\n{\n    printf(\"XML parser tests.\\n\");\n\n    printf(\"create-destroy: \");\n    create_destroy();\n    printf(\"ok\\n\");\n\n    printf(\"callbacks: \");\n    callbacks();\n    printf(\"ok\\n\");\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/key.pem",
    "content": "-----BEGIN EC PRIVATE KEY-----\nMIGkAgEBBDBZ90AXrC5n1ZxFGq4WpqMgvH7qw2YddaUzzPFtf9qDRDrRe3xW6nTr\nIywpxdh26GWgBwYFK4EEACKhZANiAAR3zfWucQBD2Fs/tDuiX3veVhlHrquhHGua\naOFBnCYLO/C+neCk/hUf2sg0ovwZktGQJLF27IZEo0AOl5gMFpDSJyRf27gMIf4R\nVQDl8Md3irYLj7JMYNcWI9Fmd1q2PaA=\n-----END EC PRIVATE KEY-----\n"
  },
  {
    "path": "tests/key_encrypted.pem",
    "content": "-----BEGIN EC PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-256-CBC,D1537075EE9323A68A08B79257D87D53\n\nfaIortcMN9tCcmwidAJlFDOS68OJlAH1Bzjh2sqhZDhFJEU/w3bOihTDk1cV0yg1\nJHSxolcX7aYLaBfhSdbnUDaeNhyvfF97O6lMHXbiSdkWBMKrOjSwpW5BcemQgbpI\ngjCi7KYWb2Z3CqcELR9624u4vRgytJQliqLW1jjnGMELcuq7HaoB2wP0XmXp9/BV\nQMQU504S6V8JbogFZeNGCOq+EW5C8tEBCz82y1PRUr0=\n-----END EC PRIVATE KEY-----\n"
  },
  {
    "path": "tests/res_query_dump.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* res_query_dump.c\n * Simple program to dump res_query(3) response\n *\n * Copyright (C) 2014 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/* Linux and OSX:\n *   gcc -o res_query_dump tests/res_query_dump.c -lresolv\n * *BSD:\n *   gcc -o res_query_dump tests/res_query_dump.c\n * QNX:\n *   gcc -o res_query_dump tests/res_query_dump.c -lsocket\n * Solaris:\n *   gcc -o res_query_dump tests/res_query_dump.c -lresolv -lsocket -lnsl\n */\n\n#include <netinet/in.h>\n#include <arpa/nameser.h>\n#include <resolv.h>\n\n#include <ctype.h>\n#include <errno.h>\n#include <stdio.h>\n#include <string.h>\n\n#ifndef T_SRV\n#define T_SRV 33\n#endif /* T_SRV */\n#ifndef C_IN\n#define C_IN 1\n#endif /* C_IN */\n\n#define STEP 10\n\nint main(int argc, char **argv)\n{\n    unsigned char buf[65536];\n    char fulldomain[2048];\n    char *service = \"xmpp-client\";\n    char *proto = \"tcp\";\n    char *domain = NULL;\n    int len;\n    int i;\n    int j;\n\n    if (argc < 2) {\n        fprintf(stderr, \"%s: argument missed\\n\", argc > 0 ? argv[0] : \"$0\");\n        fprintf(stderr, \"Usage: %s <domain>\\n\", argc > 0 ? argv[0] : \"$0\");\n        return 1;\n    }\n\n    domain = argv[1];\n    snprintf(fulldomain, sizeof(fulldomain), \"_%s._%s.%s\", service, proto,\n             domain);\n    errno = 0;\n    len = res_query(fulldomain, C_IN, T_SRV, buf, sizeof(buf));\n\n    if (len < 0) {\n        fprintf(stderr, \"res_query(): Error occurred (errno=%d)\\n\", errno);\n    }\n    if (len == 0) {\n        fprintf(stderr, \"res_query(): Empty result\\n\");\n    }\n    if (len > 0) {\n        printf(\"/* res_query(\\\"%s\\\", C_IN, T_SRV, ...) */\\n\", fulldomain);\n        printf(\"static const unsigned char data[] = {\\n\");\n        for (i = 0; i < len; i += STEP) {\n            printf(\"   \");\n            for (j = i; j < len && j < i + STEP; ++j) {\n                printf(\" 0x%02x,\", buf[j]);\n            }\n            for (j = len; j < i + STEP; ++j) {\n                printf(\"      \");\n            }\n            printf(\"    // \");\n            for (j = i; j < len && j < i + STEP; ++j) {\n                printf(\"%c\", isprint(buf[j]) ? buf[j] : '.');\n            }\n            printf(\"\\n\");\n        }\n        printf(\"};\\n\");\n    }\n\n    return len <= 0;\n}\n"
  },
  {
    "path": "tests/test.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test.c\n * strophe XMPP client library -- common routines for tests\n *\n * Copyright (C) 2014 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n#include <assert.h>\n#include <string.h>\n\n#include \"test.h\"\n\nstatic uint8_t char_to_bin(char c)\n{\n    return c <= '9'   ? (uint8_t)(c - '0')\n           : c <= 'Z' ? (uint8_t)(c - 'A' + 10)\n                      : (uint8_t)(c - 'a' + 10);\n}\n\nvoid test_hex_to_bin(const char *hex, uint8_t *bin, size_t *bin_len)\n{\n    size_t len = strlen(hex);\n    size_t i;\n\n    assert(len % 2 == 0);\n\n    for (i = 0; i < len / 2; ++i) {\n        bin[i] = char_to_bin(hex[i * 2]) * 16 + char_to_bin(hex[i * 2 + 1]);\n    }\n    *bin_len = len / 2;\n}\n\nconst char *test_bin_to_hex(const uint8_t *bin, size_t len)\n{\n    static char buf[2048];\n    size_t i;\n\n    static const char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7',\n                               '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n\n    assert(ARRAY_SIZE(buf) > len * 2);\n\n    for (i = 0; i < len; ++i) {\n        buf[i * 2] = hex[(bin[i] >> 4) & 0x0f];\n        buf[i * 2 + 1] = hex[bin[i] & 0x0f];\n    }\n    buf[len * 2] = '\\0';\n\n    return buf;\n}\n"
  },
  {
    "path": "tests/test.h",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test.h\n** libstrophe XMPP client library -- common routines for tests\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#ifndef __LIBSTROPHE_TEST_H__\n#define __LIBSTROPHE_TEST_H__\n\n#include <stddef.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include \"ostypes.h\"\n\n#define TEST_MAIN                                               \\\n    int main(int argc, char **argv)                             \\\n    {                                                           \\\n        int num_failed;                                         \\\n        Suite *s = parser_suite();                              \\\n        SRunner *sr = srunner_create(s);                        \\\n        srunner_run_all(sr, CK_NORMAL);                         \\\n        num_failed = srunner_ntests_failed(sr);                 \\\n        srunner_free(sr);                                       \\\n        return (num_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; \\\n    }\n\n#ifndef ARRAY_SIZE\n#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))\n#endif\n\n#define COMPARE(should, is)                                             \\\n    do {                                                                \\\n        const char *__should = should;                                  \\\n        const char *__is = is;                                          \\\n        if ((__should == NULL) && (__is == NULL)) {                     \\\n            /* noop */                                                  \\\n        } else if (!__should || !__is || strcmp(__should, __is) != 0) { \\\n            printf(\"Error:    %s\\n\"                                     \\\n                   \"Expected: %s\\n\"                                     \\\n                   \"Got:      %s\\n\",                                    \\\n                   #should \" != \" #is, __should, __is);                 \\\n            exit(1);                                                    \\\n        }                                                               \\\n    } while (0)\n\n#define COMPARE_BUF(should, should_len, is, is_len)                      \\\n    do {                                                                 \\\n        const uint8_t *__should = (uint8_t *)(should);                   \\\n        const uint8_t *__is = (uint8_t *)(is);                           \\\n        size_t __should_len = should_len;                                \\\n        size_t __is_len = is_len;                                        \\\n        if (__should_len != __is_len ||                                  \\\n            memcmp(__should, __is, __should_len) != 0) {                 \\\n            printf(\"Error:    %s\\n\", #should \" != \" #is);                \\\n            printf(\"Expected: 0x%s\\n\",                                   \\\n                   test_bin_to_hex(__should, __should_len));             \\\n            printf(\"Got:      0x%s\\n\", test_bin_to_hex(__is, __is_len)); \\\n            exit(1);                                                     \\\n        }                                                                \\\n    } while (0)\n\n#define ENSURE_EQ(should, is)                           \\\n    do {                                                \\\n        int __should = should;                          \\\n        int __is = is;                                  \\\n        if (__should != __is) {                         \\\n            printf(\"Error:    %s\\n\"                     \\\n                   \"Expected: %d\\n\"                     \\\n                   \"Got:      %d\\n\",                    \\\n                   #should \" != \" #is, __is, __should); \\\n            exit(1);                                    \\\n        }                                               \\\n    } while (0)\n\nvoid test_hex_to_bin(const char *hex, uint8_t *bin, size_t *bin_len);\nconst char *test_bin_to_hex(const uint8_t *bin, size_t len);\n\n#endif /* __LIBSTROPHE_TEST_H__ */\n"
  },
  {
    "path": "tests/test_base64.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_base64.c\n** libstrophe XMPP client library -- test routines for the base64 codec\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n\n#include \"test.h\"\n\nstatic const unsigned char test_2_raw[] = {0x14, 0xfb, 0x9c, 0x03,\n                                           0xd9, 0x7e, 0x00};\nstatic const unsigned char test_4_raw[] = {0xd6, 0x2f, 0x27, 0x49, 0x7e, 0xdd,\n                                           0xf3, 0xd5, 0x41, 0xbc, 0x1b, 0xe9,\n                                           0xdf, 0xe9, 0xb3, 0x08, 0x00};\n\nstatic const struct {\n    char *raw;\n    char *base64;\n} tests[] = {\n    {\n        .raw = \"How now brown cow?\",\n        .base64 = \"SG93IG5vdyBicm93biBjb3c/\",\n    },\n    {\n        .raw = (char *)test_2_raw,\n        .base64 = \"FPucA9l+\",\n    },\n    {\n        .raw = \"From rest and sleep, which but thy pictures be, \"\n               \"Much pleasure; then from thee much more must flow, \"\n               \"And soonest our best men with thee do go, \"\n               \"Rest of their bones, and soul's delivery.\",\n        .base64 = \"RnJvbSByZXN0IGFuZCBzbGVlcCwgd2hpY2ggYnV0IHRoeSBwaWN0dXJl\"\n                  \"cyBiZSwgTXVjaCBwbGVhc3VyZTsgdGhlbiBmcm9tIHRoZWUgbXVjaCBt\"\n                  \"b3JlIG11c3QgZmxvdywgQW5kIHNvb25lc3Qgb3VyIGJlc3QgbWVuIHdp\"\n                  \"dGggdGhlZSBkbyBnbywgUmVzdCBvZiB0aGVpciBib25lcywgYW5kIHNv\"\n                  \"dWwncyBkZWxpdmVyeS4=\",\n    },\n    {\n        .raw = (char *)test_4_raw,\n        .base64 = \"1i8nSX7d89VBvBvp3+mzCA==\",\n    },\n    {\n        .raw = \"realm=\\\"chesspark.com\\\",nonce=\\\"b243c0d663257a9149999cef2f83\"\n               \"a22116559e93\\\",qop=\\\"auth\\\",charset=utf-8,algorithm=md5-sess\",\n        .base64 = \"cmVhbG09ImNoZXNzcGFyay5jb20iLG5vbmNlPSJiMjQzYzBkNjYzMjU3\"\n                  \"YTkxNDk5OTljZWYyZjgzYTIyMTE2NTU5ZTkzIixxb3A9ImF1dGgiLGNo\"\n                  \"YXJzZXQ9dXRmLTgsYWxnb3JpdGhtPW1kNS1zZXNz\",\n    },\n\n    /* RFC4648 test vectors */\n    {\n        .raw = \"\",\n        .base64 = \"\",\n    },\n    {\n        .raw = \"f\",\n        .base64 = \"Zg==\",\n    },\n    {\n        .raw = \"fo\",\n        .base64 = \"Zm8=\",\n    },\n    {\n        .raw = \"foo\",\n        .base64 = \"Zm9v\",\n    },\n    {\n        .raw = \"foob\",\n        .base64 = \"Zm9vYg==\",\n    },\n    {\n        .raw = \"fooba\",\n        .base64 = \"Zm9vYmE=\",\n    },\n    {\n        .raw = \"foobar\",\n        .base64 = \"Zm9vYmFy\",\n    },\n};\n\nstatic const unsigned char bin_data[] = {\n    0xda, 0xa8, 0x81, 0x80, 0x00, 0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00,\n    0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63, 0x6c, 0x69, 0x65, 0x6e,\n    0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x67, 0x6d, 0x61, 0x69, 0x6c,\n    0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x21, 0x00, 0x01, 0xc0, 0x0c, 0x00,\n    0x21, 0x00, 0x01, 0x00, 0x00, 0x02, 0x43, 0x00, 0x1e, 0x00, 0x14, 0x00,\n    0x00, 0x14, 0x66, 0x04, 0x61, 0x6c, 0x74, 0x31, 0x04, 0x78, 0x6d, 0x70,\n    0x70, 0x01, 0x6c, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63,\n    0x6f, 0x6d, 0x00, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x02,\n    0x43, 0x00, 0x1e, 0x00, 0x14, 0x00, 0x00, 0x14, 0x66, 0x04, 0x61, 0x6c,\n    0x74, 0x34, 0x04, 0x78, 0x6d, 0x70, 0x70, 0x01, 0x6c, 0x06, 0x67, 0x6f,\n    0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0xc0, 0x0c, 0x00,\n    0x21, 0x00, 0x01, 0x00, 0x00, 0x02, 0x43, 0x00, 0x1e, 0x00, 0x14, 0x00,\n    0x00, 0x14, 0x66, 0x04, 0x61, 0x6c, 0x74, 0x32, 0x04, 0x78, 0x6d, 0x70,\n    0x70, 0x01, 0x6c, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63,\n    0x6f, 0x6d, 0x00, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x02,\n    0x43, 0x00, 0x19, 0x00, 0x05, 0x00, 0x00, 0x14, 0x66, 0x04, 0x78, 0x6d,\n    0x70, 0x70, 0x01, 0x6c, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,\n    0x63, 0x6f, 0x6d, 0x00, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00,\n    0x02, 0x43, 0x00, 0x1e, 0x00, 0x14, 0x00, 0x00, 0x14, 0x66, 0x04, 0x61,\n    0x6c, 0x74, 0x33, 0x04, 0x78, 0x6d, 0x70, 0x70, 0x01, 0x6c, 0x06, 0x67,\n    0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00,\n};\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    unsigned char *udec;\n    char *dec;\n    char *enc;\n    size_t len, i;\n\n    printf(\"BASE64 tests.\\n\");\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n    if (ctx == NULL) {\n        fprintf(stderr, \"failed to create context\\n\");\n        return 1;\n    }\n\n    for (i = 0; i < ARRAY_SIZE(tests); ++i) {\n        printf(\"Test #%d: \", (int)i + 1);\n        enc = xmpp_base64_encode(ctx, (unsigned char *)tests[i].raw,\n                                 strlen(tests[i].raw));\n        assert(enc != NULL);\n        COMPARE(tests[i].base64, enc);\n        xmpp_free(ctx, enc);\n\n        dec = xmpp_base64_decode_str(ctx, tests[i].base64,\n                                     strlen(tests[i].base64));\n        assert(dec != NULL);\n        COMPARE_BUF(tests[i].raw, strlen(tests[i].raw), dec, strlen(dec));\n        xmpp_free(ctx, dec);\n        printf(\"ok\\n\");\n    }\n\n    printf(\"Test with binary data: \");\n    enc = xmpp_base64_encode(ctx, bin_data, sizeof(bin_data));\n    assert(enc != NULL);\n    xmpp_base64_decode_bin(ctx, enc, strlen(enc), &udec, &len);\n    assert(udec != NULL);\n    assert(len != 0);\n    assert(len == sizeof(bin_data));\n    COMPARE_BUF(bin_data, sizeof(bin_data), udec, len);\n    xmpp_free(ctx, udec);\n    xmpp_free(ctx, enc);\n    printf(\"ok\\n\");\n\n    xmpp_ctx_free(ctx);\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_ctx.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_ctx.c\n** libstrophe XMPP client library -- test routines for the library run-time\n*context\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n\nstatic int log_called = 0;\nstatic int mem_alloc_called = 0;\nstatic int mem_free_called = 0;\nstatic int mem_realloc_called = 0;\n\nvoid *my_alloc(size_t size, void *userdata)\n{\n    (void)userdata;\n\n    mem_alloc_called++;\n    return malloc(size);\n}\n\nvoid my_free(void *p, void *userdata)\n{\n    (void)userdata;\n\n    mem_free_called++;\n    return free(p);\n}\n\nvoid *my_realloc(void *p, size_t size, void *userdata)\n{\n    (void)userdata;\n\n    mem_realloc_called++;\n    return realloc(p, size);\n}\n\nvoid my_logger(void *userdata,\n               xmpp_log_level_t level,\n               const char *area,\n               const char *msg)\n{\n    if (strcmp((char *)userdata, \"asdf\") == 0 && level == XMPP_LEVEL_DEBUG &&\n        strcmp(area, \"test\") == 0 && strcmp(msg, \"hello\") == 0)\n        log_called++;\n}\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    xmpp_mem_t mymem;\n    xmpp_log_t mylog;\n    char my_str[5] = \"asdf\";\n    void *testptr1, *testptr2;\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n    if (ctx == NULL)\n        return 1;\n\n    /* destroy context */\n    xmpp_ctx_free(ctx);\n\n    /* setup our memory handler */\n    mymem.alloc = my_alloc;\n    mymem.free = my_free;\n    mymem.realloc = my_realloc;\n\n    /* setup our logger */\n    mylog.handler = my_logger;\n    mylog.userdata = my_str;\n\n    ctx = xmpp_ctx_new(&mymem, &mylog);\n    strophe_debug(ctx, \"test\", \"hello\");\n\n    testptr1 = strophe_alloc(ctx, 1024);\n    if (testptr1 == NULL) {\n        xmpp_ctx_free(ctx);\n        return 1;\n    }\n\n    testptr2 = strophe_realloc(ctx, testptr1, 2048);\n    if (testptr2 == NULL) {\n        strophe_free(ctx, testptr1);\n        xmpp_ctx_free(ctx);\n        return 1;\n    }\n\n    strophe_free(ctx, testptr2);\n\n    xmpp_ctx_free(ctx);\n\n    /* check for test failure */\n    if (!(log_called && mem_alloc_called && mem_realloc_called &&\n          mem_free_called))\n        return 1;\n    if (mem_alloc_called != mem_free_called)\n        return 1;\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_fuzz_parser.c",
    "content": "#include <stdlib.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"parser.h\"\n\nvoid xmpp_initialize(void);\n\nvoid cbtest_handle_start(char *name, char **attrs, void *userdata)\n{\n    (void)name;\n    (void)attrs;\n    (void)userdata;\n}\n\nvoid cbtest_handle_end(char *name, void *userdata)\n{\n    (void)name;\n    (void)userdata;\n}\n\nvoid cbtest_handle_stanza(xmpp_stanza_t *stanza, void *userdata)\n{\n    (void)stanza;\n    (void)userdata;\n}\n\nint LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)\n{\n    xmpp_ctx_t *ctx;\n    parser_t *parser;\n\n    char *dup = malloc(Size);\n    memcpy(dup, Data, Size);\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n    parser = parser_new(ctx, cbtest_handle_start, cbtest_handle_end,\n                        cbtest_handle_stanza, NULL);\n\n    parser_feed(parser, dup, Size);\n\n    free(dup);\n    parser_free(parser);\n    xmpp_ctx_free(ctx);\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_fuzz_resolver.c",
    "content": "#include <stdlib.h>\n#include <stdint.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"resolver.h\"\n\nvoid xmpp_initialize(void);\n\nvoid cbtest_handle_start(char *name, char **attrs, void *userdata)\n{\n    (void)name;\n    (void)attrs;\n    (void)userdata;\n}\n\nvoid cbtest_handle_end(char *name, void *userdata)\n{\n    (void)name;\n    (void)userdata;\n}\n\nvoid cbtest_handle_stanza(xmpp_stanza_t *stanza, void *userdata)\n{\n    (void)stanza;\n    (void)userdata;\n}\n\n/* res_query(\"_xmpp-client._tcp.jabber.org\", C_IN, T_SRV, ...) */\nstatic const unsigned char data2[] = {\n    0xf2, 0x98, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,\n    0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63, 0x6c, 0x69, 0x65, 0x6e,\n    0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x06, 0x6a, 0x61, 0x62, 0x62, 0x65,\n    0x72, 0x03, 0x6f, 0x72, 0x67, 0x00, 0x00, 0x21, 0x00, 0x01, 0xc0, 0x0c,\n    0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x03, 0x83, 0x00, 0x1a, 0x00, 0x1e,\n    0x00, 0x1e, 0x14, 0x66, 0x07, 0x68, 0x65, 0x72, 0x6d, 0x65, 0x73, 0x32,\n    0x06, 0x6a, 0x61, 0x62, 0x62, 0x65, 0x72, 0x03, 0x6f, 0x72, 0x67, 0x00,\n    0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x03, 0x83, 0x00, 0x1c,\n    0x00, 0x1f, 0x00, 0x1e, 0x14, 0x66, 0x09, 0x68, 0x65, 0x72, 0x6d, 0x65,\n    0x73, 0x32, 0x76, 0x36, 0x06, 0x6a, 0x61, 0x62, 0x62, 0x65, 0x72, 0x03,\n    0x6f, 0x72, 0x67, 0x00,\n};\n\nint LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size)\n{\n    xmpp_ctx_t *ctx;\n    resolver_srv_rr_t *srv_rr_list;\n\n    unsigned char *dup = malloc(Size + 64);\n    memcpy(dup, data2, 64);\n    memcpy(&dup[64], Data, Size);\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n    resolver_srv_lookup_buf(ctx, dup, 64 + Size, &srv_rr_list);\n    if (srv_rr_list != NULL)\n        resolver_srv_free(ctx, srv_rr_list);\n\n    free(dup);\n    xmpp_ctx_free(ctx);\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_hash.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_hash.c\n** libstrophe XMPP client library -- self-test for the hash-table implementation\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <stdlib.h>\n#include <string.h>\n#include <time.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"hash.h\"\n#include \"test.h\"\n\n#define TABLESIZE 100\n#define TESTSIZE 500\n\n/* static test data */\nconst char *keys[] = {\"foo\", \"bar\", \"baz\", \"quux\", \"xyzzy\"};\nconst char *values[] = {\"wuzzle\", \"mug\", \"canonical\", \"rosebud\", \"lottery\"};\nconst int nkeys = ARRAY_SIZE(keys);\n\nint main(int argc, char **argv)\n{\n    xmpp_ctx_t *ctx;\n    hash_t *table, *clone;\n    hash_iterator_t *iter;\n    unsigned int seed;\n    const char *key;\n    char *result;\n    int err = 0;\n    int i;\n\n    /* initialize random numbers */\n    if (argc > 2) {\n        /* use a seed from the command line */\n        seed = (unsigned int)atoi(argv[1]);\n    } else {\n        seed = (unsigned int)clock();\n    }\n    /* using random seed 'seed' */\n    srand(seed);\n\n    /* allocate a default context */\n    ctx = xmpp_ctx_new(NULL, NULL);\n    if (ctx == NULL) {\n        /* ctx allocation failed! */\n        return -1;\n    }\n\n    /* allocate a hash table */\n    table = hash_new(ctx, TABLESIZE, strophe_free);\n    if (table == NULL) {\n        /* table allocation failed! */\n        return 1;\n    }\n\n    /* test insertion */\n    for (i = 0; i < nkeys; i++) {\n        err = hash_add(table, keys[i], strophe_strdup(ctx, values[i]));\n        if (err)\n            return err;\n    }\n\n    /* test key count */\n    if (hash_num_keys(table) != nkeys) {\n        /* wrong number of keys in table! */\n        return 1;\n    }\n\n    /* test replacing old values */\n    for (i = 0; i < nkeys; i++) {\n        err = hash_add(table, keys[0], strophe_strdup(ctx, values[i]));\n        if (err)\n            return err;\n        if (hash_num_keys(table) != nkeys)\n            return 1;\n        result = hash_get(table, keys[0]);\n        if (result == NULL)\n            return 1;\n        if (strcmp(result, values[i]) != 0)\n            return 1;\n    }\n    /* restore value for the 1st key */\n    hash_add(table, keys[0], strophe_strdup(ctx, values[0]));\n\n    /* test cloning */\n    clone = hash_clone(table);\n\n    /* test lookup */\n    for (i = 0; i < nkeys; i++) {\n        result = hash_get(clone, keys[i]);\n        if (result == NULL) {\n            /* lookup failed! */\n            return 1;\n        }\n        if (strcmp(values[i], result)) {\n            /* lookup returned incorrect value! */\n            return 1;\n        }\n    }\n\n    /* test key iterator */\n    iter = hash_iter_new(clone);\n    if (iter == NULL) {\n        /* iterator allocation failed! */\n        return 1;\n    }\n    for (i = 0; i < nkeys; i++) {\n        key = hash_iter_next(iter);\n        printf(\"key: '%s'\\n\", key);\n    }\n    key = hash_iter_next(iter);\n    if (key != NULL) {\n        /* extra keys returned! */\n        return 1;\n    }\n    key = hash_iter_next(iter);\n    if (key != NULL) {\n        /* extra keys returned! */\n        return 1;\n    }\n    hash_iter_release(iter);\n\n    /* release the hash table */\n    hash_release(table);\n\n    /* test drops */\n    hash_drop(clone, keys[2]);\n    if (hash_get(clone, keys[2]) != NULL)\n        return 1;\n    hash_drop(clone, keys[1]);\n    hash_drop(clone, keys[4]);\n    if (hash_get(clone, keys[4]) != NULL)\n        return 1;\n    if (hash_get(clone, keys[1]) != NULL)\n        return 1;\n    /* keys 0,3 should still be available */\n    if (hash_get(clone, keys[0]) == NULL)\n        return 1;\n    if (hash_get(clone, keys[3]) == NULL)\n        return 1;\n\n    /* release our clone */\n    hash_release(clone);\n\n    /* release our library context */\n    xmpp_ctx_free(ctx);\n\n    return err;\n}\n"
  },
  {
    "path": "tests/test_jid.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_jid.c\n** libstrophe XMPP client library -- test routines for the jid utils\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n\n#include \"test.h\"\n\nstatic const char *_s(const char *s)\n{\n    return s == NULL ? \"<NULL>\" : s;\n}\n\nstatic int test_jid(xmpp_ctx_t *ctx)\n{\n    char *bare;\n    char *node;\n    char *domain;\n    char *resource;\n    size_t n;\n    struct {\n        const char *jid;\n        const char *bare;\n        const char *node;\n        const char *domain;\n        const char *resource;\n    } testcases[] = {\n        {\"foo@bar.com\", \"foo@bar.com\", \"foo\", \"bar.com\", NULL},\n        {\n            \"anyone@example.com/hullo\",\n            \"anyone@example.com\",\n            \"anyone\",\n            \"example.com\",\n            \"hullo\",\n        },\n        {\n            \"a.example.com/b@example.net\",\n            \"a.example.com\",\n            NULL,\n            \"a.example.com\",\n            \"b@example.net\",\n        },\n        {\n            \"manic.porter@xyz.net/frob\",\n            \"manic.porter@xyz.net\",\n            \"manic.porter\",\n            \"xyz.net\",\n            \"frob\",\n        },\n        {\n            \"domain.tld\",\n            \"domain.tld\",\n            NULL,\n            \"domain.tld\",\n            NULL,\n        },\n    };\n\n    for (n = 0; n < sizeof(testcases) / sizeof(testcases[0]); ++n) {\n        bare = xmpp_jid_bare(ctx, testcases[n].jid);\n        node = xmpp_jid_node(ctx, testcases[n].jid);\n        domain = xmpp_jid_domain(ctx, testcases[n].jid);\n        resource = xmpp_jid_resource(ctx, testcases[n].jid);\n        printf(\"jid '%s' parsed to %s, %s, %s\\n\", testcases[n].jid, _s(node),\n               _s(domain), _s(resource));\n        COMPARE(testcases[n].bare, bare);\n        COMPARE(testcases[n].node, node);\n        COMPARE(testcases[n].domain, domain);\n        COMPARE(testcases[n].resource, resource);\n        if (bare)\n            strophe_free(ctx, bare);\n        if (node)\n            strophe_free(ctx, node);\n        if (domain)\n            strophe_free(ctx, domain);\n        if (resource)\n            strophe_free(ctx, resource);\n    }\n\n    printf(\"test_jid() finished successfully\\n\");\n\n    return 0;\n}\n\nint test_jid_new(xmpp_ctx_t *ctx)\n{\n    char *jid;\n\n    jid = xmpp_jid_new(ctx, \"node\", \"domain\", \"resource\");\n    printf(\"new jid: '%s'\\n\", jid);\n    if (strcmp(jid, \"node@domain/resource\"))\n        return 1;\n    strophe_free(ctx, jid);\n\n    jid = xmpp_jid_new(ctx, \"foo\", \"bar.com\", NULL);\n    printf(\"new jid: '%s'\\n\", jid);\n    if (strcmp(jid, \"foo@bar.com\"))\n        return 1;\n    strophe_free(ctx, jid);\n\n    const char *invalid_chars = \"\\\"&'/:<>@\";\n    char localpart[] = \"localpart\";\n    do {\n        localpart[1] = *invalid_chars;\n        jid = xmpp_jid_new(ctx, localpart, \"bar.com\", NULL);\n        if (jid != NULL) {\n            printf(\"Shouldn't have created JID with localpart=\\\"%s\\\"\\n\",\n                   localpart);\n            return 1;\n        }\n        invalid_chars++;\n    } while (*invalid_chars != '\\0');\n\n    return 0;\n}\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    int ret;\n\n    printf(\"allocating context... \");\n    ctx = xmpp_ctx_new(NULL, NULL);\n    if (ctx == NULL)\n        printf(\"failed to create context\\n\");\n    if (ctx == NULL)\n        return -1;\n    printf(\"ok.\\n\");\n\n    printf(\"testing jid routines...\\n\");\n    ret = test_jid(ctx);\n    if (ret)\n        printf(\"testing jid routines... failed!\\n\");\n    if (ret)\n        return ret;\n    printf(\"testing jid routines... ok.\\n\");\n\n    printf(\"testing jid new routines...\\n\");\n    ret = test_jid_new(ctx);\n    if (ret)\n        printf(\"testing jid new routines... failed!\\n\");\n    if (ret)\n        return ret;\n    printf(\"testing jid new routines... ok.\\n\");\n\n    printf(\"freeing context... \");\n    xmpp_ctx_free(ctx);\n    printf(\"ok.\\n\");\n\n    return ret;\n}\n"
  },
  {
    "path": "tests/test_md5.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_md5.c\n * strophe XMPP client library -- test vectors for MD5\n *\n * Copyright (C) 2015 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/* gcc -o test_md5 -I./src tests/test_md5.c tests/test.c src/md5.c */\n\n#include <stdio.h>\n#include <string.h>\n\n#include \"test.h\"\n#include \"md5.h\"\n\n/*\n * Test vectors for MD5 (RFC1321).\n */\nstatic const struct {\n    const char *data;\n    const char *md5;\n} tests[] = {\n    {\n        .data = \"\",\n        .md5 = \"d41d8cd98f00b204e9800998ecf8427e\",\n    },\n    {\n        .data = \"a\",\n        .md5 = \"0cc175b9c0f1b6a831c399e269772661\",\n    },\n    {\n        .data = \"abc\",\n        .md5 = \"900150983cd24fb0d6963f7d28e17f72\",\n    },\n    {\n        .data = \"message digest\",\n        .md5 = \"f96b697d7cb7938d525a2f31aaf161d0\",\n    },\n    {\n        .data = \"abcdefghijklmnopqrstuvwxyz\",\n        .md5 = \"c3fcd3d76192e4007dfb496cca67e13b\",\n    },\n    {\n        .data = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcde\"\n                \"fghijklmnopqrstuvwxyz0123456789\",\n        .md5 = \"d174ab98d277d9f5a5611c2c9f419d9f\",\n    },\n    {\n        .data = \"1234567890123456789012345678901\"\n                \"2345678901234567890123456789012\"\n                \"345678901234567890\",\n        .md5 = \"57edf4a22be3c955ac49da2e2107b67a\",\n    },\n};\n\nint main()\n{\n    struct MD5Context ctx;\n    unsigned char digest[16];\n    size_t i;\n\n    printf(\"MD5 tests.\\n\");\n\n    for (i = 0; i < ARRAY_SIZE(tests); ++i) {\n        printf(\"Test #%zu: \", i + 1);\n        MD5Init(&ctx);\n        MD5Update(&ctx, (unsigned char *)tests[i].data, strlen(tests[i].data));\n        MD5Final(digest, &ctx);\n        COMPARE(tests[i].md5, test_bin_to_hex(digest, sizeof(digest)));\n        printf(\"ok\\n\");\n    }\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_rand.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* check_rand.c\n * strophe XMPP client library -- test vectors for Hash_DRBG\n *\n * Copyright (C) 2014 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/* gcc -o test_rand -I./src tests/test_rand.c tests/test.c src/sha1.c */\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"test.h\"\n\n/* include rand.c to access private structures and functions */\n#include \"rand.c\"\n\n/* stubs to build test without whole libstrophe */\nvoid *strophe_alloc(const xmpp_ctx_t *ctx, size_t size)\n{\n    (void)ctx;\n    (void)size;\n    return NULL;\n}\n\nvoid strophe_free(const xmpp_ctx_t *ctx, void *p)\n{\n    (void)ctx;\n    (void)p;\n}\n\n#ifndef HAVE_SNPRINTF\nint strophe_snprintf(char *str, size_t count, const char *fmt, ...)\n{\n    (void)str;\n    (void)count;\n    (void)fmt;\n    return 0;\n}\n#endif /* HAVE_SNPRINTF */\n\nuint64_t time_stamp(void)\n{\n    return 0;\n}\n\n#ifndef USE_GETRANDOM\n\nstatic struct {\n    const char *entropy_input;\n    const char *nonce;\n    size_t returned_bytes;\n    /* after instantiate */\n    const char *V1;\n    const char *C1;\n    /* after first generate */\n    const char *V2;\n    const char *C2;\n    /* after second generate */\n    const char *V3;\n    const char *C3;\n    const char *output;\n} test_vectors[] = {\n    {\n        .entropy_input = \"136cf1c174e5a09f66b962d994396525\",\n        .nonce = \"fff1c6645f19231f\",\n        .returned_bytes = 80,\n        .V1 = \"a884a83fa40bcf730e7395dd5800ea7101b48\"\n              \"77aaa29da9b7bc0bd2bd052b9b4022f83bae3\"\n              \"8064134a233835845fdd1442bf3a0221bdc8\",\n        .C1 = \"4977fb1268c1f6286b5b3969d416fb8ca7e4e\"\n              \"aab7fd2edefc239202baa033f8b44e9145148\"\n              \"ad24ce83d597176a0bacc84c99246f15e088\",\n        .V2 = \"f1fca3520ccdc59b79cecf472c17e5fda9997\"\n              \"22629fcc88b3df9dd577a55f93f47189892b1\"\n              \"8e1c5f39dfc077ae256588eecec7bbd0323c\",\n        .C2 = \"4977fb1268c1f6286b5b3969d416fb8ca7e4e\"\n              \"aab7fd2edefc239202baa033f8b44e9145148\"\n              \"ad24ce83d597176a0bacc84c99246f15e088\",\n        .V3 = \"3b749e64758fbbc3e52a08b1002ee18a517e5\"\n              \"cd1a9cfb67b0032fd83245938ca8c01add770\"\n              \"68515bde248c75adea10bbaaf0bc18e66a2c\",\n        .C3 = \"4977fb1268c1f6286b5b3969d416fb8ca7e4e\"\n              \"aab7fd2edefc239202baa033f8b44e9145148\"\n              \"ad24ce83d597176a0bacc84c99246f15e088\",\n        .output = \"0e28130fa5ca11edd3293ca26fdb8ae1810611f7\"\n                  \"8715082ed3841e7486f16677b28e33ffe0b93d98\"\n                  \"ba57ba358c1343ab2a26b4eb7940f5bc63938464\"\n                  \"1ee80a25140331076268bd1ce702ad534dda0ed8\",\n    },\n\n    {\n        .entropy_input = \"dfed69b08902fcfb795d5d35dbe23f6b\",\n        .nonce = \"37258e820432e392\",\n        .returned_bytes = 80,\n        .V1 = \"2708022f0f6d13cd8bc139ceb86ee237ee124\"\n              \"e17029ac4f053d41526285599d4eac5029972\"\n              \"7d83a0df0d5fa9824d5f14d7e7e9c8bdb165\",\n        .C1 = \"fdb1a827c30e436c997261da6dc31ae7c27ee\"\n              \"28e5c29b2ee0ca57b44ab78b7b0d1e8b459ba\"\n              \"7285f5d93abf218d16d834a803c2330321cd\",\n        .V2 = \"24b9aa56d27b573a25339ba92631fd1fb0913\"\n              \"0a55ec477de6079906ad3ce5185bcadb7b047\"\n              \"627060f80afb8529c18b46567e6b79dffb01\",\n        .C2 = \"fdb1a827c30e436c997261da6dc31ae7c27ee\"\n              \"28e5c29b2ee0ca57b44ab78b7b0d1e8b459ba\"\n              \"7285f5d93abf218d16d834a803c2330321cd\",\n        .V3 = \"226b527e95899aa6bea5fd8393f5180773101\"\n              \"333baee2acc6d1f0baf7f4709368e966c945c\"\n              \"d4a0d86093183375443379b09c08e4381fa8\",\n        .C3 = \"fdb1a827c30e436c997261da6dc31ae7c27ee\"\n              \"28e5c29b2ee0ca57b44ab78b7b0d1e8b459ba\"\n              \"7285f5d93abf218d16d834a803c2330321cd\",\n        .output = \"adcb8e2cbbc5957d538a20db18b5e7fe350a90a2\"\n                  \"01359fab9e0f154c53aa146bc6af1fcc7ff8f330\"\n                  \"b8d9f3d7b038488ba627e6fa21d0147377b13404\"\n                  \"22b22634b412dac69ac82c35b5fb411a4e42a133\",\n    },\n};\n\nint main()\n{\n    size_t i;\n    uint8_t entropy_input[1024];\n    size_t entropy_input_len;\n    uint8_t nonce[1024];\n    size_t nonce_len;\n    uint8_t output[1024];\n    Hash_DRBG_CTX ctx;\n\n    printf(\"Hash_DRBG tests.\\n\");\n    for (i = 0; i < ARRAY_SIZE(test_vectors); ++i) {\n        printf(\"Test #%d: \", (int)i + 1);\n        test_hex_to_bin(test_vectors[i].entropy_input, entropy_input,\n                        &entropy_input_len);\n        test_hex_to_bin(test_vectors[i].nonce, nonce, &nonce_len);\n\n        Hash_DRBG_Instantiate(&ctx, entropy_input, entropy_input_len, nonce,\n                              nonce_len);\n        COMPARE(test_vectors[i].V1, test_bin_to_hex(ctx.V, sizeof(ctx.V)));\n        COMPARE(test_vectors[i].C1, test_bin_to_hex(ctx.C, sizeof(ctx.C)));\n        assert(ctx.reseed_counter == 1);\n\n        Hash_DRBG_Generate(&ctx, output, test_vectors[i].returned_bytes);\n        COMPARE(test_vectors[i].V2, test_bin_to_hex(ctx.V, sizeof(ctx.V)));\n        COMPARE(test_vectors[i].C2, test_bin_to_hex(ctx.C, sizeof(ctx.C)));\n        assert(ctx.reseed_counter == 2);\n\n        Hash_DRBG_Generate(&ctx, output, test_vectors[i].returned_bytes);\n        COMPARE(test_vectors[i].V3, test_bin_to_hex(ctx.V, sizeof(ctx.V)));\n        COMPARE(test_vectors[i].C3, test_bin_to_hex(ctx.C, sizeof(ctx.C)));\n        COMPARE(test_vectors[i].output,\n                test_bin_to_hex(output, test_vectors[i].returned_bytes));\n        assert(ctx.reseed_counter == 3);\n        printf(\"ok\\n\");\n    }\n\n    return 0;\n}\n\n#else\n\nint main()\n{\n    uint8_t output[1024];\n    xmpp_rand_t *rand = xmpp_rand_new(NULL);\n\n    assert(rand != NULL);\n    /* this would assert if it failed */\n    xmpp_rand_bytes(rand, output, sizeof(output));\n\n    return 0;\n}\n\n#endif\n"
  },
  {
    "path": "tests/test_resolver.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_resolver.c\n * strophe XMPP client library -- tests for resolver\n *\n * Copyright (C) 2015 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n#include <assert.h>\n#include <stdio.h>\n\n#include \"strophe.h\"\n#include \"resolver.h\"\n#include \"test.h\"\n\n/* res_query(\"_xmpp-client._tcp.jabber.kiev.ua\", C_IN, T_SRV, ...) */\nstatic const unsigned char data1[] = {\n    0x95, 0xf3, 0x81, 0x80, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,\n    0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63, 0x6c, 0x69, 0x65, 0x6e,\n    0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x06, 0x6a, 0x61, 0x62, 0x62, 0x65,\n    0x72, 0x04, 0x6b, 0x69, 0x65, 0x76, 0x02, 0x75, 0x61, 0x00, 0x00, 0x21,\n    0x00, 0x01, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x00, 0x3b,\n    0x00, 0x16, 0x00, 0x01, 0x00, 0x00, 0x14, 0x66, 0x06, 0x6a, 0x61, 0x62,\n    0x62, 0x65, 0x72, 0x04, 0x6b, 0x69, 0x65, 0x76, 0x02, 0x75, 0x61, 0x00,\n};\n/* res_query(\"_xmpp-client._tcp.jabber.org\", C_IN, T_SRV, ...) */\nstatic const unsigned char data2[] = {\n    0xf2, 0x98, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00,\n    0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63, 0x6c, 0x69, 0x65, 0x6e,\n    0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x06, 0x6a, 0x61, 0x62, 0x62, 0x65,\n    0x72, 0x03, 0x6f, 0x72, 0x67, 0x00, 0x00, 0x21, 0x00, 0x01, 0xc0, 0x0c,\n    0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x03, 0x83, 0x00, 0x1a, 0x00, 0x1e,\n    0x00, 0x1e, 0x14, 0x66, 0x07, 0x68, 0x65, 0x72, 0x6d, 0x65, 0x73, 0x32,\n    0x06, 0x6a, 0x61, 0x62, 0x62, 0x65, 0x72, 0x03, 0x6f, 0x72, 0x67, 0x00,\n    0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x03, 0x83, 0x00, 0x1c,\n    0x00, 0x1f, 0x00, 0x1e, 0x14, 0x66, 0x09, 0x68, 0x65, 0x72, 0x6d, 0x65,\n    0x73, 0x32, 0x76, 0x36, 0x06, 0x6a, 0x61, 0x62, 0x62, 0x65, 0x72, 0x03,\n    0x6f, 0x72, 0x67, 0x00,\n};\n/* res_query(\"_xmpp-client._tcp.gmail.com\", C_IN, T_SRV, ...) */\nstatic const unsigned char data3[] = {\n    0xda, 0xa8, 0x81, 0x80, 0x00, 0x01, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00,\n    0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63, 0x6c, 0x69, 0x65, 0x6e,\n    0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x67, 0x6d, 0x61, 0x69, 0x6c,\n    0x03, 0x63, 0x6f, 0x6d, 0x00, 0x00, 0x21, 0x00, 0x01, 0xc0, 0x0c, 0x00,\n    0x21, 0x00, 0x01, 0x00, 0x00, 0x02, 0x43, 0x00, 0x1e, 0x00, 0x14, 0x00,\n    0x00, 0x14, 0x66, 0x04, 0x61, 0x6c, 0x74, 0x31, 0x04, 0x78, 0x6d, 0x70,\n    0x70, 0x01, 0x6c, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63,\n    0x6f, 0x6d, 0x00, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x02,\n    0x43, 0x00, 0x1e, 0x00, 0x14, 0x00, 0x00, 0x14, 0x66, 0x04, 0x61, 0x6c,\n    0x74, 0x34, 0x04, 0x78, 0x6d, 0x70, 0x70, 0x01, 0x6c, 0x06, 0x67, 0x6f,\n    0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00, 0xc0, 0x0c, 0x00,\n    0x21, 0x00, 0x01, 0x00, 0x00, 0x02, 0x43, 0x00, 0x1e, 0x00, 0x14, 0x00,\n    0x00, 0x14, 0x66, 0x04, 0x61, 0x6c, 0x74, 0x32, 0x04, 0x78, 0x6d, 0x70,\n    0x70, 0x01, 0x6c, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63,\n    0x6f, 0x6d, 0x00, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x02,\n    0x43, 0x00, 0x19, 0x00, 0x05, 0x00, 0x00, 0x14, 0x66, 0x04, 0x78, 0x6d,\n    0x70, 0x70, 0x01, 0x6c, 0x06, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03,\n    0x63, 0x6f, 0x6d, 0x00, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00,\n    0x02, 0x43, 0x00, 0x1e, 0x00, 0x14, 0x00, 0x00, 0x14, 0x66, 0x04, 0x61,\n    0x6c, 0x74, 0x33, 0x04, 0x78, 0x6d, 0x70, 0x70, 0x01, 0x6c, 0x06, 0x67,\n    0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x03, 0x63, 0x6f, 0x6d, 0x00,\n};\n/* res_query(\"_xmpp-client._tcp.jabber.calyxinstitute.org\", C_IN, T_SRV, ...) */\nstatic const unsigned char data4[] = {\n    0x8d, 0x58, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, // .X........\n    0x00, 0x00, 0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63, // ..._xmpp-c\n    0x6c, 0x69, 0x65, 0x6e, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, // lient._tcp\n    0x06, 0x6a, 0x61, 0x62, 0x62, 0x65, 0x72, 0x0e, 0x63, 0x61, // .jabber.ca\n    0x6c, 0x79, 0x78, 0x69, 0x6e, 0x73, 0x74, 0x69, 0x74, 0x75, // lyxinstitu\n    0x74, 0x65, 0x03, 0x6f, 0x72, 0x67, 0x00, 0x00, 0x21, 0x00, // te.org..!.\n    0x01, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x03, // ....!.....\n    0x83, 0x00, 0x1e, 0x00, 0x04, 0x00, 0x00, 0x14, 0x66, 0x10, // ........f.\n    0x69, 0x6a, 0x65, 0x65, 0x79, 0x6e, 0x72, 0x63, 0x36, 0x78, // ijeeynrc6x\n    0x32, 0x75, 0x79, 0x35, 0x6f, 0x62, 0x05, 0x6f, 0x6e, 0x69, // 2uy5ob.oni\n    0x6f, 0x6e, 0x00, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, // on....!...\n    0x00, 0x03, 0x83, 0x00, 0x21, 0x00, 0x05, 0x00, 0x01, 0x14, // ....!.....\n    0x66, 0x06, 0x6a, 0x61, 0x62, 0x62, 0x65, 0x72, 0x0e, 0x63, // f.jabber.c\n    0x61, 0x6c, 0x79, 0x78, 0x69, 0x6e, 0x73, 0x74, 0x69, 0x74, // alyxinstit\n    0x75, 0x74, 0x65, 0x03, 0x6f, 0x72, 0x67, 0x00,             // ute.org.\n};\n/* res_query(\"_xmpp-client._tcp.jabber.org\", C_IN, T_SRV, ...) with pointers */\nstatic const unsigned char data5[] = {\n    0x00, 0x00, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, // ..........\n    0x00, 0x00, 0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63, // ..._xmpp-c\n    0x6c, 0x69, 0x65, 0x6e, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, // lient._tcp\n    0x06, 0x6a, 0x61, 0x62, 0x62, 0x65, 0x72, 0x03, 0x6f, 0x72, // .jabber.or\n    0x67, 0x00, 0x00, 0x21, 0x00, 0x01, 0xc0, 0x0c, 0x00, 0x21, // g..!.....!\n    0x00, 0x01, 0x00, 0x00, 0x01, 0x9e, 0x00, 0x12, 0x00, 0x1f, // ..........\n    0x00, 0x1e, 0x14, 0x66, 0x09, 0x68, 0x65, 0x72, 0x6d, 0x65, // ...f.herme\n    0x73, 0x32, 0x76, 0x36, 0xc0, 0x1e, 0xc0, 0x0c, 0x00, 0x21, // s2v6.....!\n    0x00, 0x01, 0x00, 0x00, 0x01, 0x9e, 0x00, 0x10, 0x00, 0x1e, // ..........\n    0x00, 0x1e, 0x14, 0x66, 0x07, 0x68, 0x65, 0x72, 0x6d, 0x65, // ...f.herme\n    0x73, 0x32, 0xc0, 0x1e,                                     // s2..\n};\n/* hacked data2 with two empty-string targets. */\nstatic const unsigned char data6[] = {\n    0xf2, 0x98, 0x81, 0x80, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00,\n    0x00, 0x0c, 0x5f, 0x78, 0x6d, 0x70, 0x70, 0x2d, 0x63, 0x6c, 0x69,\n    0x65, 0x6e, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x06, 0x6a, 0x61,\n    0x62, 0x62, 0x65, 0x72, 0x03, 0x6f, 0x72, 0x67, 0x00, 0x00, 0x21,\n    0x00, 0x01, 0xc0, 0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x03,\n    0x83, 0x00, 0x07, 0x00, 0x1e, 0x00, 0x1e, 0x14, 0x66, 0x00, 0xc0,\n    0x0c, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x03, 0x83, 0x00, 0x08,\n    0x00, 0x1f, 0x00, 0x1e, 0x14, 0x66, 0xc0, 0x40,\n};\n\nstatic const struct {\n    const unsigned char *data;\n    size_t len;\n    char *target;\n    unsigned short port;\n    int target_nr;\n} tests[] = {\n    {\n        .data = data1,\n        .len = sizeof(data1),\n        .target = \"jabber.kiev.ua\",\n        .port = 5222,\n        .target_nr = 1,\n    },\n    {\n        .data = data2,\n        .len = sizeof(data2),\n        .target = \"hermes2.jabber.org\",\n        .port = 5222,\n        .target_nr = 2,\n    },\n    {\n        .data = data3,\n        .len = sizeof(data3),\n        .target = \"xmpp.l.google.com\",\n        .port = 5222,\n        .target_nr = 5,\n    },\n    {\n        .data = data4,\n        .len = sizeof(data4),\n        .target = \"ijeeynrc6x2uy5ob.onion\",\n        .port = 5222,\n        .target_nr = 2,\n    },\n    {\n        .data = data5,\n        .len = sizeof(data5),\n        .target = \"hermes2.jabber.org\",\n        .port = 5222,\n        .target_nr = 2,\n    },\n    {\n        .data = data6,\n        .len = sizeof(data6),\n        .target = \"\",\n        .port = 5222,\n        .target_nr = 2,\n    },\n};\n\nstatic int srv_rr_list_len(resolver_srv_rr_t *list)\n{\n    int nr;\n\n    for (nr = 0; list != NULL; ++nr, list = list->next)\n        ;\n\n    return nr;\n}\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    xmpp_rand_t *rand;\n    resolver_srv_rr_t *srv_rr_list;\n    char *domain, *rnd_b64;\n    unsigned char *buf;\n    unsigned short port;\n    size_t i, slen;\n    int ret;\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n    assert(ctx != NULL);\n\n    printf(\"resolver_srv_lookup_buf() tests.\\n\");\n    for (i = 0; i < ARRAY_SIZE(tests); ++i) {\n        printf(\"Test #%zu: \", i + 1);\n        ret = resolver_srv_lookup_buf(ctx, tests[i].data, tests[i].len,\n                                      &srv_rr_list);\n        assert(ret == XMPP_DOMAIN_FOUND);\n        assert(srv_rr_list != NULL);\n        if (tests[i].target_nr != srv_rr_list_len(srv_rr_list)) {\n            printf(\"fail! got %d targets, but should be %d\\n\",\n                   srv_rr_list_len(srv_rr_list), tests[i].target_nr);\n            return 1;\n        }\n        /* check only 1st result */\n        domain = srv_rr_list->target;\n        port = srv_rr_list->port;\n        COMPARE(tests[i].target, domain);\n        if (tests[i].port != port) {\n            printf(\"fail! got port=%u, but should be %u\\n\", (unsigned)port,\n                   (unsigned)tests[i].port);\n            return 1;\n        }\n        printf(\"ok\\n\");\n        resolver_srv_free(ctx, srv_rr_list);\n    }\n\n    /*\n     * The next test case must not crash and is supposed to be checked\n     * under valgrind.\n     */\n    printf(\"Test of a broken message: \");\n    rand = xmpp_rand_new(ctx);\n    assert(rand != NULL);\n    assert(sizeof(data2) > 64);\n    buf = strophe_alloc(ctx, sizeof(data2));\n    assert(buf != NULL);\n    memcpy(buf, data2, 64);\n    xmpp_rand_bytes(rand, &buf[64], sizeof(data2) - 64);\n    ret = resolver_srv_lookup_buf(ctx, buf, sizeof(data2), &srv_rr_list);\n    if (ret == XMPP_DOMAIN_FOUND && srv_rr_list != NULL)\n        resolver_srv_free(ctx, srv_rr_list);\n    xmpp_rand_free(ctx, rand);\n    printf(\"ok\\n\");\n\n    printf(\"Broken message was:\\n\");\n    rnd_b64 = xmpp_base64_encode(ctx, buf, sizeof(data2));\n    slen = strlen(rnd_b64);\n    for (i = 0; i < slen; i += 64) {\n        printf(\"%.64s\\n\", &rnd_b64[i]);\n    }\n\n    strophe_free(ctx, buf);\n    strophe_free(ctx, rnd_b64);\n    xmpp_ctx_free(ctx);\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_sasl.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_sasl.c\n** libstrophe XMPP client library -- test routines for the SASL implementation\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"sasl.h\"\n\nstatic const unsigned char jid[] = \"foo@bar.com\";\nstatic const char password[] = \"secret\";\nstatic const char response_plain[] = \"AGZvb0BiYXIuY29tAHNlY3JldA==\";\n\nstatic const char challenge_md5[] =\n    \"cmVhbG09InNvbWVyZWFsbSIsbm9uY2U9Ik9BNk1HOXRFUUdtMmhoIixxb3A9ImF1dGgi\"\n    \"LGNoYXJzZXQ9dXRmLTgsYWxnb3JpdGhtPW1kNS1zZXNzCg==\";\nstatic const char response_md5[] =\n    \"dXNlcm5hbWU9InNvbWVub2RlIixyZWFsbT0ic29tZXJlYWxtIixub25jZT0i\"\n    \"T0E2TUc5dEVRR20yaGgiLGNub25jZT0iMDBERUFEQkVFRjAwIixuYz0wMDAw\"\n    \"MDAwMSxxb3A9YXV0aCxkaWdlc3QtdXJpPSJ4bXBwL3NvbWVyZWFsbSIscmVz\"\n    \"cG9uc2U9NGVhNmU4N2JjMDkzMzUwNzQzZGIyOGQ3MDIwOGNhZmIsY2hhcnNl\"\n    \"dD11dGYtOA==\";\n\nint test_plain(xmpp_ctx_t *ctx)\n{\n    char *result;\n\n    result = sasl_plain(ctx, jid, password);\n    if (result == NULL) {\n        /* SASL PLAIN internal failure! */\n        return 1;\n    }\n    if (strncmp(response_plain, result, strlen(response_plain))) {\n        /* SASL PLAIN returned incorrect string! */\n        return 2;\n    }\n    strophe_free(ctx, result);\n\n    return 0;\n}\n\nint test_digest_md5(xmpp_ctx_t *ctx)\n{\n    char *result;\n\n    result =\n        sasl_digest_md5(ctx, challenge_md5, \"somenode@somerealm\", \"secret\");\n    printf(\"response:\\n%s\\n\", result);\n    if (strcmp(response_md5, result)) {\n        /* generated incorrect response to challenge */\n        return 1;\n    }\n\n    return 0;\n}\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    int ret;\n\n    printf(\"allocating context... \");\n    ctx = xmpp_ctx_new(NULL, NULL);\n    if (ctx == NULL)\n        printf(\"failed to create context\\n\");\n    if (ctx == NULL)\n        return -1;\n    printf(\"ok.\\n\");\n\n    printf(\"testing SASL PLAIN... \");\n    ret = test_plain(ctx);\n    if (ret)\n        printf(\"failed!\\n\");\n    if (ret)\n        return ret;\n    printf(\"ok.\\n\");\n\n    printf(\"testing SASL DIGEST-MD5... \");\n    ret = test_digest_md5(ctx);\n    if (ret)\n        printf(\"failed!\\n\");\n    if (ret)\n        return ret;\n    printf(\"ok.\\n\");\n\n    printf(\"freeing context... \");\n    xmpp_ctx_free(ctx);\n    printf(\"ok.\\n\");\n\n    return ret;\n}\n"
  },
  {
    "path": "tests/test_scram.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_scram.c\n * strophe XMPP client library -- test vectors for SCRAM-SHA1\n *\n * Copyright (C) 2014 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/* gcc -o test_scram -I./src tests/test_scram.c tests/test.c src/sha1.c */\n\n#include <assert.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n#include \"test.h\"\n\n/* include scram.c to access static functions */\n#include \"scram.c\"\n\n/*\n * Test vectors for derivation function (RFC6070).\n */\nstatic const struct {\n    char *P; /* text */\n    char *S; /* salt */\n    size_t P_len;\n    size_t S_len;\n    uint32_t c; /* i */\n    char *DK;   /* resulting digest */\n} df_vectors[] = {\n    {\n        .P = \"password\",\n        .S = \"salt\",\n        .P_len = 8,\n        .S_len = 4,\n        .c = 1,\n        .DK = \"0c60c80f961f0e71f3a9b524af6012062fe037a6\",\n    },\n    {\n        .P = \"password\",\n        .S = \"salt\",\n        .P_len = 8,\n        .S_len = 4,\n        .c = 2,\n        .DK = \"ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957\",\n    },\n    {\n        .P = \"password\",\n        .S = \"salt\",\n        .P_len = 8,\n        .S_len = 4,\n        .c = 4096,\n        .DK = \"4b007901b765489abead49d926f721d065a429c1\",\n    },\n};\n\nstatic void test_df(const struct hash_alg *alg)\n{\n    size_t i;\n    const char *s;\n    uint8_t dk[SCRAM_DIGEST_SIZE];\n\n    printf(\"Derivation function SCRAM_Hi tests for %s.\\n\", alg->scram_name);\n    for (i = 0; i < ARRAY_SIZE(df_vectors); ++i) {\n        printf(\"Test #%d: \", (int)i + 1);\n        SCRAM_Hi(alg, (uint8_t *)df_vectors[i].P, df_vectors[i].P_len,\n                 (uint8_t *)df_vectors[i].S, df_vectors[i].S_len,\n                 df_vectors[i].c, dk);\n        s = test_bin_to_hex(dk, alg->digest_size);\n        COMPARE(df_vectors[i].DK, s);\n        printf(\"ok\\n\");\n    }\n}\n\n/* RFC6120 */\nstatic const struct {\n    char *password;\n    char *initial;\n    char *challenge;\n    char *response;\n    char *salt;\n    uint32_t i;\n    char *sign;\n} scram_vectors[] = {\n    {\n        .password = \"r0m30myr0m30\",\n        .initial = \"n,,n=juliet,r=oMsTAAwAAAAMAAAANP0TAAAAAABPU0AA\",\n        .challenge = \"r=oMsTAAwAAAAMAAAANP0TAAAAAABPU0AAe124695b-69a9-4de6-9c30\"\n                     \"-b51b3808c59e,s=NjhkYTM0MDgtNGY0Zi00NjdmLTkxMmUtNDlmNTNmN\"\n                     \"DNkMDMz,i=4096\",\n        .response = \"c=biws,r=oMsTAAwAAAAMAAAANP0TAAAAAABPU0AAe124695b-69a9-4de\"\n                    \"6-9c30-b51b3808c59e\",\n        .salt = \"36386461333430382d346634662d34363766\"\n                \"2d393132652d343966353366343364303333\",\n        .i = 4096,\n        .sign = \"500e7bb4cfd2be90130641f6157b345835ef258c\",\n    },\n};\n\nstatic void test_scram(const struct hash_alg *alg)\n{\n    uint8_t key[SCRAM_DIGEST_SIZE];\n    uint8_t sign[SCRAM_DIGEST_SIZE];\n    uint8_t salt[256];\n    size_t salt_len;\n    char auth[512];\n    const char *s;\n    size_t i;\n    size_t j;\n\n    printf(\"SCRAM_ClientKey and SCRAM_ClientSignature tests for %s.\\n\",\n           alg->scram_name);\n    for (i = 0; i < ARRAY_SIZE(scram_vectors); ++i) {\n        printf(\"Test #%d: \", (int)i + 1);\n        snprintf(auth, sizeof(auth), \"%s,%s,%s\", scram_vectors[i].initial + 3,\n                 scram_vectors[i].challenge, scram_vectors[i].response);\n        test_hex_to_bin(scram_vectors[i].salt, salt, &salt_len);\n\n        SCRAM_ClientKey(alg, (uint8_t *)scram_vectors[i].password,\n                        strlen(scram_vectors[i].password), salt, salt_len,\n                        scram_vectors[i].i, key);\n        SCRAM_ClientSignature(alg, key, (uint8_t *)auth, strlen(auth), sign);\n        for (j = 0; j < alg->digest_size; j++) {\n            sign[j] ^= key[j];\n        }\n        s = test_bin_to_hex(sign, alg->digest_size);\n        COMPARE(scram_vectors[i].sign, s);\n        printf(\"ok\\n\");\n    }\n}\n\n/*\n * Test vectors for HMAC (RFC2202, RFC4231).\n */\nstatic const uint8_t hmac_key1[] = {0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,\n                                    0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,\n                                    0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b};\nstatic const uint8_t hmac_data1[] = {0x48, 0x69, 0x20, 0x54,\n                                     0x68, 0x65, 0x72, 0x65};\nstatic const struct {\n    const uint8_t *key;\n    size_t key_len;\n    const uint8_t *data;\n    size_t data_len;\n    const uint8_t sha1[SHA1_DIGEST_SIZE];\n    const uint8_t sha256[SHA256_DIGEST_SIZE];\n    const uint8_t sha512[SHA512_DIGEST_SIZE];\n} hmac_vectors[] = {\n    {\n        .key = hmac_key1,\n        .key_len = sizeof(hmac_key1),\n        .data = hmac_data1,\n        .data_len = sizeof(hmac_data1),\n        .sha1 = {0xb6, 0x17, 0x31, 0x86, 0x55, 0x05, 0x72, 0x64, 0xe2, 0x8b,\n                 0xc0, 0xb6, 0xfb, 0x37, 0x8c, 0x8e, 0xf1, 0x46, 0xbe, 0x00},\n        .sha256 = {0xb0, 0x34, 0x4c, 0x61, 0xd8, 0xdb, 0x38, 0x53,\n                   0x5c, 0xa8, 0xaf, 0xce, 0xaf, 0x0b, 0xf1, 0x2b,\n                   0x88, 0x1d, 0xc2, 0x00, 0xc9, 0x83, 0x3d, 0xa7,\n                   0x26, 0xe9, 0x37, 0x6c, 0x2e, 0x32, 0xcf, 0xf7},\n        .sha512 = {0x87, 0xaa, 0x7c, 0xde, 0xa5, 0xef, 0x61, 0x9d, 0x4f, 0xf0,\n                   0xb4, 0x24, 0x1a, 0x1d, 0x6c, 0xb0, 0x23, 0x79, 0xf4, 0xe2,\n                   0xce, 0x4e, 0xc2, 0x78, 0x7a, 0xd0, 0xb3, 0x05, 0x45, 0xe1,\n                   0x7c, 0xde, 0xda, 0xa8, 0x33, 0xb7, 0xd6, 0xb8, 0xa7, 0x02,\n                   0x03, 0x8b, 0x27, 0x4e, 0xae, 0xa3, 0xf4, 0xe4, 0xbe, 0x9d,\n                   0x91, 0x4e, 0xeb, 0x61, 0xf1, 0x70, 0x2e, 0x69, 0x6c, 0x20,\n                   0x3a, 0x12, 0x68, 0x54},\n    },\n};\n\nstatic void test_hmac(const struct hash_alg *alg)\n{\n    size_t i;\n    uint8_t digest[SCRAM_DIGEST_SIZE];\n\n    printf(\"HMAC tests for %s.\\n\", alg->scram_name);\n    for (i = 0; i < ARRAY_SIZE(hmac_vectors); ++i) {\n        printf(\"Test #%d: \", (int)i + 1);\n        memset(digest, 0, sizeof(digest));\n        crypto_HMAC(alg, hmac_vectors[i].key, hmac_vectors[i].key_len,\n                    hmac_vectors[i].data, hmac_vectors[i].data_len, digest);\n        switch (alg->digest_size) {\n        case SHA1_DIGEST_SIZE:\n            COMPARE_BUF(hmac_vectors[i].sha1, alg->digest_size, digest,\n                        alg->digest_size);\n            break;\n        case SHA256_DIGEST_SIZE:\n            COMPARE_BUF(hmac_vectors[i].sha256, alg->digest_size, digest,\n                        alg->digest_size);\n            break;\n        case SHA512_DIGEST_SIZE:\n            COMPARE_BUF(hmac_vectors[i].sha512, alg->digest_size, digest,\n                        alg->digest_size);\n            break;\n        default:\n            printf(\"Unknown digest size: %zu\\n\", alg->digest_size);\n            exit(1);\n        }\n        printf(\"ok\\n\");\n    }\n}\n\nint main()\n{\n    test_df(&scram_sha1);\n    test_scram(&scram_sha1);\n    test_hmac(&scram_sha1);\n    test_hmac(&scram_sha256);\n    test_hmac(&scram_sha512);\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_send_queue.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_send_queue.c\n** libstrophe XMPP client library -- test routines for the send queue\n**\n** Copyright (C) 2021 Steffen Jaeckel\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n\n#include \"test.h\"\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    xmpp_log_t *log;\n    xmpp_conn_state_t state;\n    xmpp_sm_state_t *sm_state;\n    char *ret;\n\n    unsigned int n;\n\n    xmpp_initialize();\n    log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    ctx = xmpp_ctx_new(NULL, log);\n    conn = xmpp_conn_new(ctx);\n    sm_state = strophe_alloc(ctx, sizeof(*sm_state));\n    memset(sm_state, 0, sizeof(*sm_state));\n    sm_state->ctx = ctx;\n\n    xmpp_conn_set_sm_state(conn, sm_state);\n\n    ENSURE_EQ(0, xmpp_conn_send_queue_len(conn));\n\n    state = conn->state;\n    conn->state = XMPP_STATE_CONNECTED;\n\n    xmpp_send_raw(conn, \"foo\", 3);\n    ENSURE_EQ(1, xmpp_conn_send_queue_len(conn));\n\n    xmpp_send_raw(conn, \"bar\", 3);\n    ENSURE_EQ(2, xmpp_conn_send_queue_len(conn));\n\n    xmpp_send_raw(conn, \"baz\", 3);\n    ENSURE_EQ(3, xmpp_conn_send_queue_len(conn));\n\n    xmpp_send_raw(conn, \"baan\", 4);\n    ENSURE_EQ(4, xmpp_conn_send_queue_len(conn));\n\n    conn->send_queue_head->wip = 1;\n    ENSURE_EQ(3, xmpp_conn_send_queue_len(conn));\n\n    ret = xmpp_conn_send_queue_drop_element(conn, XMPP_QUEUE_OLDEST);\n    COMPARE(\"bar\", ret);\n    xmpp_free(ctx, ret);\n    ENSURE_EQ(2, xmpp_conn_send_queue_len(conn));\n\n    conn->send_queue_head->wip = 0;\n    ENSURE_EQ(3, xmpp_conn_send_queue_len(conn));\n\n    ret = xmpp_conn_send_queue_drop_element(conn, XMPP_QUEUE_OLDEST);\n    COMPARE(\"foo\", ret);\n    xmpp_free(ctx, ret);\n    ENSURE_EQ(2, xmpp_conn_send_queue_len(conn));\n\n    ret = xmpp_conn_send_queue_drop_element(conn, XMPP_QUEUE_YOUNGEST);\n    COMPARE(\"baan\", ret);\n    xmpp_free(ctx, ret);\n    ENSURE_EQ(1, xmpp_conn_send_queue_len(conn));\n\n    ret = xmpp_conn_send_queue_drop_element(conn, XMPP_QUEUE_YOUNGEST);\n    COMPARE(\"baz\", ret);\n    xmpp_free(ctx, ret);\n    ENSURE_EQ(0, xmpp_conn_send_queue_len(conn));\n\n    conn->state = state;\n\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_serialize_sm.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_serialize_sm.c\n** libstrophe XMPP client library -- test routines for the send queue\n**\n** Copyright (C) 2024 Stephen Paul Weber\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n\n#include \"test.h\"\n\nvoid callback(xmpp_conn_t *conn,\n              void *ctx,\n              const unsigned char *sm_state,\n              size_t sm_state_len)\n{\n    int *callback_count = ctx;\n    (*callback_count)++;\n    COMPARE_BUF(\"\\x1a\\x00\\x00\\x00\\x00\", 5, sm_state, 5);\n    COMPARE_BUF(\"\\x1a\\x00\\x00\\x00\\x00\", 5, sm_state + 10, 5);\n    COMPARE_BUF(\"\\x7a\\x00\\x00\\x00\\x04SMID\", 9, sm_state + 15, 9);\n    if (*callback_count == 1) {\n        COMPARE_BUF(\"\\x1a\\x00\\x00\\x00\\x00\", 5, sm_state + 5, 5);\n        COMPARE_BUF(\"\\x9a\\x00\\x00\\x00\\x02\", 5, sm_state + 24, 5);\n        COMPARE_BUF(\"\\x7a\\x00\\x00\\x00\\x03\"\n                    \"foo\",\n                    8, sm_state + 29, 8);\n        COMPARE_BUF(\"\\x7a\\x00\\x00\\x00\\x1a<r xmlns='urn:xmpp:sm:3'/>\", 31,\n                    sm_state + 37, 31);\n        COMPARE_BUF(\"\\xba\\x00\\x00\\x00\\x00\", 5, sm_state + 68, 5);\n        ENSURE_EQ(sm_state_len, 73);\n\n        xmpp_conn_t *newconn = xmpp_conn_new(conn->ctx);\n        xmpp_conn_restore_sm_state(newconn, sm_state, sm_state_len);\n        ENSURE_EQ(newconn->sm_state->sm_sent_nr, 0);\n        ENSURE_EQ(newconn->sm_state->sm_handled_nr, 0);\n        COMPARE(newconn->sm_state->id, \"SMID\");\n        ENSURE_EQ(newconn->send_queue_len, 2);\n        ENSURE_EQ(newconn->send_queue_user_len, 2);\n        ENSURE_EQ((size_t)(newconn->sm_state->sm_queue.head), 0);\n        xmpp_conn_release(newconn);\n    }\n    if (*callback_count == 2) {\n        COMPARE_BUF(\"\\x1a\\x00\\x00\\x00\\x01\", 5, sm_state + 5, 5);\n        COMPARE_BUF(\"\\x9a\\x00\\x00\\x00\\x01\", 5, sm_state + 24, 5);\n        COMPARE_BUF(\"\\x7a\\x00\\x00\\x00\\x1a<r xmlns='urn:xmpp:sm:3'/>\", 31,\n                    sm_state + 29, 31);\n        COMPARE_BUF(\"\\xba\\x00\\x00\\x00\\x01\", 5, sm_state + 60, 5);\n        COMPARE_BUF(\"\\x1a\\x00\\x00\\x00\\x00\", 5, sm_state + 65, 5);\n        COMPARE_BUF(\"\\x7a\\x00\\x00\\x00\\x03\"\n                    \"foo\",\n                    8, sm_state + 70, 8);\n        ENSURE_EQ(sm_state_len, 78);\n\n        xmpp_conn_t *newconn = xmpp_conn_new(conn->ctx);\n        xmpp_conn_restore_sm_state(newconn, sm_state, sm_state_len);\n        ENSURE_EQ(newconn->sm_state->sm_sent_nr, 1);\n        ENSURE_EQ(newconn->sm_state->sm_handled_nr, 0);\n        COMPARE(newconn->sm_state->id, \"SMID\");\n        ENSURE_EQ(newconn->send_queue_len, 1);\n        ENSURE_EQ(newconn->send_queue_user_len, 1);\n        ENSURE_EQ(newconn->sm_state->sm_queue.head->sm_h, 0);\n        xmpp_conn_release(newconn);\n    }\n    if (*callback_count == 3) {\n        COMPARE_BUF(\"\\x1a\\x00\\x00\\x00\\x01\", 5, sm_state + 5, 5);\n        COMPARE_BUF(\"\\x9a\\x00\\x00\\x00\\x00\", 5, sm_state + 24, 5);\n        COMPARE_BUF(\"\\xba\\x00\\x00\\x00\\x01\", 5, sm_state + 29, 5);\n        COMPARE_BUF(\"\\x1a\\x00\\x00\\x00\\x00\", 5, sm_state + 34, 5);\n        COMPARE_BUF(\"\\x7a\\x00\\x00\\x00\\x03\"\n                    \"foo\",\n                    8, sm_state + 39, 8);\n        ENSURE_EQ(sm_state_len, 47);\n\n        xmpp_conn_t *newconn = xmpp_conn_new(conn->ctx);\n        xmpp_conn_restore_sm_state(newconn, sm_state, sm_state_len);\n        ENSURE_EQ(newconn->sm_state->sm_sent_nr, 1);\n        ENSURE_EQ(newconn->sm_state->sm_handled_nr, 0);\n        COMPARE(newconn->sm_state->id, \"SMID\");\n        ENSURE_EQ(newconn->send_queue_len, 0);\n        ENSURE_EQ(newconn->send_queue_user_len, 0);\n        ENSURE_EQ(newconn->sm_state->sm_queue.head->sm_h, 0);\n        xmpp_conn_release(newconn);\n    }\n}\n\nint fake_read(struct conn_interface *intf, void *buff, size_t len)\n{\n    return 0;\n}\n\nint fake_write(struct conn_interface *intf, const void *buff, size_t len)\n{\n    return len;\n}\n\nint fake_flush(struct conn_interface *intf)\n{\n    return 0;\n}\n\nint fake_error_is_recoverable(struct conn_interface *intf, int err)\n{\n    return 0;\n}\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    xmpp_log_t *log;\n    xmpp_conn_state_t state;\n    xmpp_sm_state_t *sm_state;\n    char *ret;\n    unsigned int n;\n    int callback_count = 0;\n\n    xmpp_initialize();\n    log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    ctx = xmpp_ctx_new(NULL, log);\n    conn = xmpp_conn_new(ctx);\n    sm_state = strophe_alloc(ctx, sizeof(*sm_state));\n    memset(sm_state, 0, sizeof(*sm_state));\n    sm_state->ctx = ctx;\n    sm_state->sm_support = sm_state->sm_enabled = sm_state->can_resume = 1;\n    sm_state->id = strophe_strdup(ctx, \"SMID\");\n\n    xmpp_conn_set_sm_state(conn, sm_state);\n    xmpp_conn_set_sm_callback(conn, callback, &callback_count);\n\n    ENSURE_EQ(xmpp_conn_send_queue_len(conn), 0);\n\n    struct conn_interface intf = {fake_read,  fake_write,\n                                  fake_flush, fake_flush,\n                                  fake_flush, fake_error_is_recoverable,\n                                  conn};\n    conn->intf = intf;\n    state = conn->state;\n    conn->state = XMPP_STATE_CONNECTED;\n    conn->sock = 123;\n\n    xmpp_send_raw(conn, \"foo\", 3);\n    ENSURE_EQ(xmpp_conn_send_queue_len(conn), 1);\n    ENSURE_EQ(callback_count, 1);\n\n    xmpp_run_once(ctx, 0);\n    ENSURE_EQ(callback_count, 3);\n\n    conn->state = state;\n\n    xmpp_conn_release(conn);\n    xmpp_ctx_free(ctx);\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_sha1.c",
    "content": "/* Tests for Steve Reid's public domain SHA-1 implementation */\n/* This file is in the public domain */\n\n/* gcc -o test_sha1 -I./src tests/test_sha1.c src/sha1.c */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"sha1.h\"\n#include \"test.h\"\n\n/* Test Vectors (from FIPS PUB 180-1) */\nstatic char *test_data[] = {\n    \"abc\", \"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\",\n    \"A million repetitions of 'a'\",\n    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};\nstatic char *test_results[] = {\"A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D\",\n                               \"84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1\",\n                               \"34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F\",\n                               \"AD5B3FDB CB526778 C2839D2F 151EA753 995E26A0\"};\n\nstatic void digest_to_hex(const uint8_t *digest, char *output)\n{\n    int i, j;\n    char *c = output;\n\n    for (i = 0; i < SHA1_DIGEST_SIZE / 4; i++) {\n        for (j = 0; j < 4; j++) {\n            sprintf(c, \"%02X\", digest[i * 4 + j]);\n            c += 2;\n        }\n        sprintf(c, \" \");\n        c += 1;\n    }\n    *(c - 1) = '\\0';\n}\n\nint main()\n{\n    size_t k;\n    SHA1_CTX context;\n    uint8_t digest[20];\n    char output[80];\n    char *copy;\n\n    fprintf(stdout, \"verifying SHA-1 implementation... \");\n\n    for (k = 0; k < ARRAY_SIZE(test_data); k++) {\n        if (k == 2) {\n            /* this case will be checked below */\n            continue;\n        }\n        copy = strdup(test_data[k]);\n        crypto_SHA1_Init(&context);\n        crypto_SHA1_Update(&context, (uint8_t *)test_data[k],\n                           strlen(test_data[k]));\n        crypto_SHA1_Final(&context, digest);\n        digest_to_hex(digest, output);\n\n        if (strcmp(output, test_results[k])) {\n            fprintf(stdout, \"FAIL\\n\");\n            fprintf(stderr, \"* hash of \\\"%s\\\" incorrect:\\n\", test_data[k]);\n            fprintf(stderr, \"\\t%s returned\\n\", output);\n            fprintf(stderr, \"\\t%s is correct\\n\", test_results[k]);\n            return (1);\n        }\n        if (strcmp(copy, test_data[k])) {\n            fprintf(stdout, \"FAIL\\n\");\n            fprintf(stdout, \"* original string was changed by SHA1\\n\");\n            return (1);\n        }\n        free(copy);\n    }\n    /* million 'a' vector we feed separately */\n    crypto_SHA1_Init(&context);\n    for (k = 0; k < 1000000; k++)\n        crypto_SHA1_Update(&context, (uint8_t *)\"a\", 1);\n    crypto_SHA1_Final(&context, digest);\n    digest_to_hex(digest, output);\n    if (strcmp(output, test_results[2])) {\n        fprintf(stdout, \"FAIL\\n\");\n        fprintf(stderr, \"* hash of \\\"%s\\\" incorrect:\\n\", test_data[2]);\n        fprintf(stderr, \"\\t%s returned\\n\", output);\n        fprintf(stderr, \"\\t%s is correct\\n\", test_results[2]);\n        return (1);\n    }\n\n    /* success */\n    fprintf(stdout, \"ok\\n\");\n    return (0);\n}\n"
  },
  {
    "path": "tests/test_sha256.c",
    "content": "/* Tests for SHA-256 from LibTomCrypt */\n/* This file is in the public domain */\n\n/* gcc -o test_sha256 -I./src tests/test_sha256.c tests/test.c src/sha256.c */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"sha256.h\"\n#include \"test.h\"\n\nint main()\n{\n    static const struct {\n        const char *msg;\n        unsigned char hash[SHA256_DIGEST_SIZE];\n    } tests[] = {\n        {\"abc\",\n         {0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40,\n          0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17,\n          0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad}},\n        {\"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq\",\n         {0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26,\n          0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff,\n          0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1}},\n    };\n\n    int i;\n    unsigned char tmp[SHA256_DIGEST_SIZE];\n    sha256_context md;\n\n    for (i = 0; i < (int)(sizeof(tests) / sizeof(tests[0])); i++) {\n        sha256_init(&md);\n        sha256_process(&md, (unsigned char *)tests[i].msg,\n                       (unsigned long)strlen(tests[i].msg));\n        sha256_done(&md, tmp);\n        COMPARE_BUF(tmp, sizeof(tmp), tests[i].hash, sizeof(tests[i].hash));\n    }\n\n    /* success */\n    fprintf(stdout, \"ok\\n\");\n    return (0);\n}\n"
  },
  {
    "path": "tests/test_sha512.c",
    "content": "/* Tests for SHA-512 from LibTomCrypt */\n/* This file is in the public domain */\n\n/* gcc -o test_sha512 -I./src tests/test_sha512.c tests/test.c src/sha512.c */\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"sha512.h\"\n#include \"test.h\"\n\nstatic const uint8_t hash_1m_a[SHA512_DIGEST_SIZE] = {\n    0xe7, 0x18, 0x48, 0x3d, 0x0c, 0xe7, 0x69, 0x64, 0x4e, 0x2e, 0x42,\n    0xc7, 0xbc, 0x15, 0xb4, 0x63, 0x8e, 0x1f, 0x98, 0xb1, 0x3b, 0x20,\n    0x44, 0x28, 0x56, 0x32, 0xa8, 0x03, 0xaf, 0xa9, 0x73, 0xeb, 0xde,\n    0x0f, 0xf2, 0x44, 0x87, 0x7e, 0xa6, 0x0a, 0x4c, 0xb0, 0x43, 0x2c,\n    0xe5, 0x77, 0xc3, 0x1b, 0xeb, 0x00, 0x9c, 0x5c, 0x2c, 0x49, 0xaa,\n    0x2e, 0x4e, 0xad, 0xb2, 0x17, 0xad, 0x8c, 0xc0, 0x9b};\n\nint main()\n{\n    static const struct {\n        const char *msg;\n        uint8_t hash[SHA512_DIGEST_SIZE];\n    } tests[] = {\n        {\"abc\",\n         {0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73,\n          0x49, 0xae, 0x20, 0x41, 0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9,\n          0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a, 0x21,\n          0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23,\n          0xa3, 0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8,\n          0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f}},\n        {\"abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklm\"\n         \"nopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu\",\n         {0x8e, 0x95, 0x9b, 0x75, 0xda, 0xe3, 0x13, 0xda, 0x8c, 0xf4, 0xf7,\n          0x28, 0x14, 0xfc, 0x14, 0x3f, 0x8f, 0x77, 0x79, 0xc6, 0xeb, 0x9f,\n          0x7f, 0xa1, 0x72, 0x99, 0xae, 0xad, 0xb6, 0x88, 0x90, 0x18, 0x50,\n          0x1d, 0x28, 0x9e, 0x49, 0x00, 0xf7, 0xe4, 0x33, 0x1b, 0x99, 0xde,\n          0xc4, 0xb5, 0x43, 0x3a, 0xc7, 0xd3, 0x29, 0xee, 0xb6, 0xdd, 0x26,\n          0x54, 0x5e, 0x96, 0xe5, 0x5b, 0x87, 0x4b, 0xe9, 0x09}},\n    };\n\n    size_t i;\n    uint8_t tmp[SHA512_DIGEST_SIZE];\n    sha512_context md;\n\n    for (i = 0; i < ARRAY_SIZE(tests); i++) {\n        sha512_init(&md);\n        sha512_process(&md, (uint8_t *)tests[i].msg, strlen(tests[i].msg));\n        sha512_done(&md, tmp);\n        COMPARE_BUF(tests[i].hash, sizeof(tests[i].hash), tmp, sizeof(tmp));\n    }\n\n    /* special case: one million repetitions of the character 'a' */\n    sha512_init(&md);\n    for (i = 0; i < 1000000U; ++i)\n        sha512_process(&md, (uint8_t *)\"a\", 1);\n    sha512_done(&md, tmp);\n    COMPARE_BUF(hash_1m_a, sizeof(hash_1m_a), tmp, sizeof(tmp));\n\n    /* success */\n    fprintf(stdout, \"ok\\n\");\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_snprintf.c",
    "content": "/*\n * Copyright Patrick Powell 1995\n * This code is based on code written by Patrick Powell (papowell@astart.com)\n * It may be used for any purpose as long as this notice remains intact\n * on all source code distributions\n */\n\n#include <stdio.h>\n#include <string.h>\n#include <limits.h>\n\n#undef HAVE_VSNPRINTF\n#undef HAVE_SNPRINTF\n#include \"snprintf.c\"\n\n#ifndef LONG_STRING\n#define LONG_STRING 1024\n#endif\n\nint main(void)\n{\n    char buf1[LONG_STRING];\n    char buf2[LONG_STRING];\n    char *fp_fmt[] = {\"%-1.5f\",  \"%1.5f\",  \"%123.9f\", \"%10.5f\", \"% 10.5f\",\n                      \"%+22.9f\", \"%+4.9f\", \"%01.3f\",  \"%4f\",    \"%3.1f\",\n                      \"%3.2f\",   \"%.0f\",   \"%.1f\",    NULL};\n    double fp_nums[] = {-1.5,  134.21, 91340.2, 341.1234, 0203.9, 0.96,\n                        0.996, 0.9996, 1.996,   4.136,    0};\n    char *int_fmt[] = {\"%-1.5d\", \"%1.5d\",   \"%123.9d\",  \"%5.5d\",\n                       \"%10.5d\", \"% 10.5d\", \"%+22.33d\", \"%01.3d\",\n                       \"%4d\",    \"0x%x\",    \"0x%04x\",   NULL};\n    int int_nums[] = {-1,         134,     91340,   341, 0203,\n                      0x76543210, INT_MIN, INT_MAX, 0};\n    char *long_fmt[] = {\"%-1.5ld\", \"%1.5ld\",   \"%123.9ld\",  \"%5.5ld\",\n                        \"%10.5ld\", \"% 10.5ld\", \"%+22.33ld\", \"%01.3ld\",\n                        \"%4ld\",    \"0x%lx\",    \"0x%04lx\",   NULL};\n    long long_nums[] = {-1L,      134L,     91340L,\n                        341L,     0203L,    0xFEDCBA9876543210L,\n                        LONG_MIN, LONG_MAX, 0L};\n    int x, y;\n    int fail = 0;\n    int num = 0;\n\n    printf(\"Testing xmpp_snprintf format codes against system sprintf...\\n\");\n\n    for (x = 0; fp_fmt[x] != NULL; x++)\n        for (y = 0; fp_nums[y] != 0; y++) {\n            strophe_snprintf(buf1, sizeof(buf1), fp_fmt[x], fp_nums[y]);\n            sprintf(buf2, fp_fmt[x], fp_nums[y]);\n            if (strcmp(buf1, buf2)) {\n                printf(\"xmpp_snprintf doesn't match Format: \"\n                       \"%s\\n\\txmpp_snprintf = %s\\n\\tsprintf  = %s\\n\",\n                       fp_fmt[x], buf1, buf2);\n                fail++;\n            }\n            num++;\n        }\n\n    for (x = 0; int_fmt[x] != NULL; x++)\n        for (y = 0; int_nums[y] != 0; y++) {\n            strophe_snprintf(buf1, sizeof(buf1), int_fmt[x], int_nums[y]);\n            sprintf(buf2, int_fmt[x], int_nums[y]);\n            if (strcmp(buf1, buf2)) {\n                printf(\"xmpp_snprintf doesn't match Format: \"\n                       \"%s\\n\\txmpp_snprintf = %s\\n\\tsprintf  = %s\\n\",\n                       int_fmt[x], buf1, buf2);\n                fail++;\n            }\n            num++;\n        }\n\n    for (x = 0; long_fmt[x] != NULL; x++)\n        for (y = 0; long_nums[y] != 0; y++) {\n            strophe_snprintf(buf1, sizeof(buf1), long_fmt[x], long_nums[y]);\n            sprintf(buf2, long_fmt[x], long_nums[y]);\n            if (strcmp(buf1, buf2)) {\n                printf(\"xmpp_snprintf doesn't match Format: \"\n                       \"%s\\n\\txmpp_snprintf = %s\\n\\tsprintf  = %s\\n\",\n                       long_fmt[x], buf1, buf2);\n                fail++;\n            }\n            num++;\n        }\n    printf(\"%d tests failed out of %d.\\n\", fail, num);\n    return fail != 0 ? 1 : 0;\n}\n"
  },
  {
    "path": "tests/test_sock.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_sock.c\n** libstrophe XMPP client library -- test routines for the socket abstraction\n**\n** Copyright (C) 2005-2009 Collecta, Inc.\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n** This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <stdio.h>\n#include <string.h>\n\n#ifndef _WIN32\n#include <sys/select.h>\n#endif\n\n#include \"sock.h\"\n\nint wait_for_connect(sock_t sock)\n{\n    fd_set wfds, efds;\n    int ret;\n\n    FD_ZERO(&wfds);\n    FD_SET(sock, &wfds);\n    FD_ZERO(&efds);\n    FD_SET(sock, &efds);\n\n    ret = select(sock + 1, NULL, &wfds, &efds, NULL);\n    if (ret <= 0)\n        return -1;\n\n    if (FD_ISSET(sock, &efds))\n        return 0;\n    if (FD_ISSET(sock, &wfds))\n        return 1;\n\n    return -1;\n}\n\nint main()\n{\n    sock_t sock;\n    int err;\n\n    sock_initialize();\n\n    sock = sock_connect(\"www.google.com\", 80);\n\n    if (sock < 0) {\n        sock_shutdown();\n        return 1;\n    }\n\n    err = wait_for_connect(sock);\n    if (err < 0) {\n        sock_close(sock);\n        sock_shutdown();\n        return 1;\n    }\n\n    sock_close(sock);\n\n    sock_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_stanza.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_stanza.c\n * libstrophe XMPP client library -- test routines for stanza functions\n *\n * Copyright (C) 2020 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n/* gcc -o test_stanza -I./src tests/test_stanza.c -lstrophe */\n\n#include <strophe.h>\n\n#include <assert.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"test.h\"\n\n#define MAGICPTR ((void *)0xfeedbeef)\nstatic unsigned long used_blocks = 0;\n\nstatic void *stanza_alloc(size_t size, void *userdata)\n{\n    assert(userdata == MAGICPTR);\n\n    ++used_blocks;\n    return malloc(size);\n}\n\nstatic void stanza_free(void *ptr, void *userdata)\n{\n    assert(userdata == MAGICPTR);\n\n    if (ptr != NULL) {\n        assert(used_blocks > 0);\n        --used_blocks;\n    }\n    free(ptr);\n}\n\nstatic void *stanza_realloc(void *ptr, size_t size, void *userdata)\n{\n    assert(userdata == MAGICPTR);\n\n    if (ptr != NULL && size == 0) {\n        /* equivalent to free(ptr) */\n        assert(used_blocks > 0);\n        --used_blocks;\n    } else if (ptr == NULL) {\n        /* equivalent to malloc(size) */\n        ++used_blocks;\n    }\n    return realloc(ptr, size);\n}\n\nstatic const xmpp_mem_t stanza_mem = {\n    .alloc = &stanza_alloc,\n    .free = &stanza_free,\n    .realloc = &stanza_realloc,\n    .userdata = MAGICPTR,\n};\n\nstatic void test_stanza_add_child(xmpp_ctx_t *ctx)\n{\n    xmpp_stanza_t *stanza;\n    xmpp_stanza_t *child;\n    unsigned long baseline = used_blocks;\n\n    /* xmpp_stanza_add_child */\n\n    stanza = xmpp_stanza_new(ctx);\n    child = xmpp_stanza_new(ctx);\n    assert(stanza != NULL);\n    assert(child != NULL);\n    xmpp_stanza_add_child(stanza, child);\n    xmpp_stanza_release(stanza);\n    assert(used_blocks > baseline);\n    xmpp_stanza_release(child);\n    assert(used_blocks == baseline);\n\n    /* xmpp_stanza_add_child_ex */\n\n    stanza = xmpp_stanza_new(ctx);\n    child = xmpp_stanza_new(ctx);\n    assert(stanza != NULL);\n    assert(child != NULL);\n    xmpp_stanza_add_child_ex(stanza, child, 0);\n    xmpp_stanza_release(stanza);\n    assert(used_blocks == baseline);\n}\n\nstatic void test_stanza_from_string(xmpp_ctx_t *ctx)\n{\n    xmpp_stanza_t *stanza;\n    char *buf;\n    size_t buflen;\n    int ret;\n\n    const char *str =\n        \"<signcrypt xmlns=\\\"urn:xmpp:openpgp:0\\\"><to \"\n        \"jid=\\\"user@domain.com\\\"/><time \"\n        \"stamp=\\\"2020-06-03T21:26:24+0200\\\"/><rpad/><payload><body \"\n        \"xmlns=\\\"jabber:client\\\">Hello World!</body></payload></signcrypt>\";\n\n    stanza = xmpp_stanza_new_from_string(ctx, str);\n    assert(stanza != NULL);\n    ret = xmpp_stanza_to_text(stanza, &buf, &buflen);\n    assert(ret == XMPP_EOK);\n    COMPARE(str, buf);\n    xmpp_free(ctx, buf);\n    xmpp_stanza_release(stanza);\n\n    /* create a string with two stanzas to make sure we don't\n     * leak any memory when we convert them to a xmpp_stanza_t\n     */\n    buf = malloc(strlen(str) * 2 + 1);\n    assert(buf != NULL);\n    memcpy(buf, str, strlen(str) + 1);\n    memcpy(&buf[strlen(str)], str, strlen(str) + 1);\n    stanza = xmpp_stanza_new_from_string(ctx, buf);\n    assert(stanza != NULL);\n    free(buf);\n    ret = xmpp_stanza_to_text(stanza, &buf, &buflen);\n    assert(ret == XMPP_EOK);\n    COMPARE(str, buf);\n    xmpp_free(ctx, buf);\n    xmpp_stanza_release(stanza);\n\n    /* Error path. */\n    stanza = xmpp_stanza_new_from_string(ctx, \"<uu><uu>tt\");\n    assert(stanza == NULL);\n}\n\nstatic void test_stanza_error(xmpp_ctx_t *ctx)\n{\n    xmpp_stanza_t *stanza;\n    xmpp_stanza_t *error;\n    xmpp_stanza_t *item;\n    xmpp_stanza_t *mood;\n    char *buf;\n    size_t buflen;\n    const char *attr[10];\n    int attrlen = ARRAY_SIZE(attr);\n    int ret;\n\n    static const char *str =\n        \"<iq from='romeo@montague.lit/home' to='juliet@capulet.lit/chamber' \"\n        \"type='get' id='e2e1'><ping xmlns='urn:xmpp:ping'/></iq>\";\n    static const char *str_error =\n        \"<error type=\\\"cancel\\\"><service-unavailable \"\n        \"xmlns=\\\"urn:ietf:params:xml:ns:xmpp-stanzas\\\"/></error>\";\n    // clang-format off\n    static const char *str_mood =\n        \"<iq from='juliet@capulet.lit/balcony' id='publish1' type='set'>\"\n          \"<pubsub xmlns='http://jabber.org/protocol/pubsub'>\"\n            \"<publish node='http://jabber.org/protocol/mood'>\"\n              \"<item>\"\n                \"<mood xmlns='http://jabber.org/protocol/mood'>\"\n                  \"<annoyed/>\"\n                  \"<text>curse my nurse!</text>\"\n                \"</mood>\"\n              \"</item>\"\n            \"</publish>\"\n          \"</pubsub>\"\n        \"</iq>\";\n    // clang-format on\n\n    stanza = xmpp_stanza_new_from_string(ctx, str);\n    assert(stanza != NULL);\n    error =\n        xmpp_stanza_reply_error(stanza, \"cancel\", \"service-unavailable\", NULL);\n    assert(error != NULL);\n    mood = xmpp_stanza_new_from_string(ctx, str_mood);\n    assert(mood != NULL);\n\n    COMPARE(\"romeo@montague.lit/home\", xmpp_stanza_get_to(error));\n    COMPARE(\"juliet@capulet.lit/chamber\", xmpp_stanza_get_from(error));\n    COMPARE(\"e2e1\", xmpp_stanza_get_id(error));\n    COMPARE(\"error\", xmpp_stanza_get_type(error));\n\n    /* FAIL - no list given */\n    item = xmpp_stanza_get_child_by_path(mood, NULL);\n    assert(item == NULL);\n\n    /* FAIL - first entry doesn't match */\n    item = xmpp_stanza_get_child_by_path(mood, \"foo\", NULL);\n    assert(item == NULL);\n\n    /* FAIL - 'iq' has no namespace */\n    item = xmpp_stanza_get_child_by_path(\n        mood, XMPP_STANZA_NAME_IN_NS(\"iq\", \"foobar\"),\n        XMPP_STANZA_NAME_IN_NS(\"pubsub\", \"http://jabber.org/protocol/pubsub\"),\n        \"publish\", \"item\", \"mood\", NULL);\n    assert(item == NULL);\n\n    /* FAIL - 'pubsub' is in another namespace */\n    item = xmpp_stanza_get_child_by_path(\n        mood, \"iq\",\n        XMPP_STANZA_NAME_IN_NS(\"pubsub\", \"http://jabber.org/protocol/foobar\"),\n        \"publish\", \"item\", \"mood\", NULL);\n    assert(item == NULL);\n\n    item = xmpp_stanza_get_child_by_path(mood, \"iq\", \"pubsub\", \"publish\",\n                                         \"item\", \"mood\", NULL);\n    assert(item != NULL);\n    assert(xmpp_stanza_get_children(item) != NULL);\n    COMPARE(\"annoyed\", xmpp_stanza_get_name(xmpp_stanza_get_children(item)));\n\n    item = xmpp_stanza_get_child_by_path(\n        mood, \"iq\",\n        XMPP_STANZA_NAME_IN_NS(\"pubsub\", \"http://jabber.org/protocol/pubsub\"),\n        \"publish\", \"item\",\n        XMPP_STANZA_NAME_IN_NS(\"mood\", \"http://jabber.org/protocol/mood\"),\n        NULL);\n    assert(item != NULL);\n    assert(xmpp_stanza_get_children(item) != NULL);\n    COMPARE(\"annoyed\", xmpp_stanza_get_name(xmpp_stanza_get_children(item)));\n\n    ret = xmpp_stanza_get_attributes(error, attr, attrlen);\n    /* attr contains both attribute name and value. */\n    assert(ret == 8);\n\n    item = xmpp_stanza_get_child_by_name(error, \"error\");\n    assert(item != NULL);\n\n    ret = xmpp_stanza_to_text(item, &buf, &buflen);\n    assert(ret == XMPP_EOK);\n    COMPARE(str_error, buf);\n\n    xmpp_free(ctx, buf);\n    xmpp_stanza_release(mood);\n    xmpp_stanza_release(stanza);\n    xmpp_stanza_release(error);\n}\n\nstatic void test_stanza_bookmark(xmpp_ctx_t *ctx)\n{\n    // clang-format off\n   static const char *str =\n         \"<item xmlns=\\\"http://jabber.org/protocol/pubsub\\\" id=\\\"\\\">\"\n            \"<conference autojoin=\\\"\\\" name=\\\"Symbol(lit-nothing)\\\" xmlns=\\\"urn:xmpp:bookmarks:1\\\" />\"\n         \"</item>\";\n    // clang-format on\n\n    xmpp_stanza_t *stanza = xmpp_stanza_new_from_string(ctx, str);\n    assert(stanza != NULL);\n    const char *id = xmpp_stanza_get_id(stanza);\n    assert(id != NULL);\n    assert(strcmp(id, \"\") == 0);\n    xmpp_stanza_t *child = xmpp_stanza_get_children(stanza);\n    COMPARE(\"conference\", xmpp_stanza_get_name(child));\n    const char *autojoin = xmpp_stanza_get_attribute(child, \"autojoin\");\n    assert(autojoin != NULL);\n    assert(strcmp(autojoin, \"\") == 0);\n    xmpp_stanza_release(stanza);\n}\n\nstatic void test_stanza_copy(xmpp_ctx_t *ctx)\n{\n    // clang-format off\n   static const char *str =\n         \"<item xmlns=\\\"http://jabber.org/protocol/pubsub\\\" id=\\\"\\\">\"\n            \"<conference autojoin=\\\"\\\" name=\\\"Symbol(lit-nothing)\\\" xmlns=\\\"urn:xmpp:bookmarks:1\\\" />\"\n         \"</item>\";\n    // clang-format on\n\n    xmpp_stanza_t *stanza = xmpp_stanza_new_from_string(ctx, str);\n    assert(stanza != NULL);\n    const char *id = xmpp_stanza_get_id(stanza);\n    assert(id != NULL);\n    assert(strcmp(id, \"\") == 0);\n    xmpp_stanza_t *child = xmpp_stanza_get_children(stanza);\n    COMPARE(\"conference\", xmpp_stanza_get_name(child));\n    xmpp_stanza_t *copy = xmpp_stanza_copy(child);\n    xmpp_stanza_release(stanza);\n    COMPARE(\"conference\", xmpp_stanza_get_name(copy));\n    xmpp_stanza_release(copy);\n}\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n\n    xmpp_initialize();\n    ctx = xmpp_ctx_new(&stanza_mem, NULL);\n    assert(ctx != NULL);\n\n    test_stanza_bookmark(ctx);\n    test_stanza_copy(ctx);\n    test_stanza_add_child(ctx);\n    test_stanza_from_string(ctx);\n    test_stanza_error(ctx);\n\n    xmpp_ctx_free(ctx);\n    xmpp_shutdown();\n\n    /* All allocated blocks must be freed. */\n    assert(used_blocks == 0);\n}\n"
  },
  {
    "path": "tests/test_string.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_string.c\n * strophe XMPP client library -- tests for re-implemented string functions\n *\n * Copyright (C) 2016 Dmitry Podgorny <pasis.ua@gmail.com>\n *\n *  This software is provided AS-IS with no warranty, either express\n *  or implied.\n *\n *  This program is dual licensed under the MIT or GPLv3 licenses.\n */\n\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"strophe.h\"\n#include \"common.h\"\n#include \"util.h\"\n\n#include \"test.h\" /* ARRAY_SIZE */\n\n/* strtok_s() has appeared in visual studio 2005.\n   Use own implementation for older versions. */\n#ifdef _MSC_VER\n#if (_MSC_VER >= 1400)\n#define strtok_r strtok_s\n#else\n#define strtok_r xmpp_strtok_r\n#endif\n#endif /* _MSC_VER */\n\nstatic int test_strtok_r(void)\n{\n    const char *test = \"-abc-=-def--\";\n    char *s1, *s2, *sub1, *sub2;\n    char *sp1, *sp2;\n\n    s1 = strdup(test);\n    s2 = strdup(test);\n    assert(strcmp(s1, s2) == 0);\n\n    sub1 = strtok_r(s1, \"-\", &sp1);\n    sub2 = strophe_strtok_r(s2, \"-\", &sp2);\n    if (strcmp(sub1, sub2) != 0) {\n        printf(\"1st token is '%s', must be '%s'\\n\", sub2, sub1);\n        return -1;\n    }\n    sub1 = strtok_r(NULL, \"-=\", &sp1);\n    sub2 = strophe_strtok_r(NULL, \"-=\", &sp2);\n    if (strcmp(sub1, sub2) != 0) {\n        printf(\"2nd token is '%s', must be '%s'\\n\", sub2, sub1);\n        return -1;\n    }\n    sub1 = strtok_r(NULL, \"-\", &sp1);\n    sub2 = strophe_strtok_r(NULL, \"-\", &sp2);\n    if (sub1 != sub2) {\n        printf(\"3rd call returns %p instead of NULL\\n\", sub2);\n        return -1;\n    }\n\n    free(s1);\n    free(s2);\n\n    return 0;\n}\n\nstatic int test_strdup_one(xmpp_ctx_t *ctx, const char *s)\n{\n    char *s1, *s2;\n    int rc = 0;\n\n    s1 = strdup(s);\n    s2 = strophe_strdup(ctx, s);\n\n    if (!s1 || !s2 || strcmp(s1, s2) != 0) {\n        rc = -1;\n        printf(\"strdup: '%s', xmpp_strdup: '%s'\\n\", s1 ? s1 : \"<NULL>\",\n               s2 ? s2 : \"<NULL>\");\n    }\n\n    free(s1);\n    if (s2)\n        strophe_free(ctx, s2);\n\n    return rc;\n}\n\nstatic int test_strdup(void)\n{\n    xmpp_ctx_t *ctx;\n    size_t i;\n    int rc = 0;\n\n    static const char *tests[] = {\"\", \"\\0\", \"test\", \"s p a c e\", \"\\n\\r\"};\n\n    ctx = xmpp_ctx_new(NULL, NULL);\n    assert(ctx != NULL);\n    for (i = 0; i < ARRAY_SIZE(tests); ++i) {\n        rc = test_strdup_one(ctx, tests[i]);\n        if (rc != 0)\n            break;\n    }\n    xmpp_ctx_free(ctx);\n\n    return rc;\n}\n\nint main()\n{\n    int rc;\n\n    printf(\"xmpp_strtok_r() tests... \");\n    rc = test_strtok_r();\n    if (rc != 0)\n        return 1;\n    printf(\"ok\\n\");\n\n    printf(\"xmpp_strdup() tests... \");\n    rc = test_strdup();\n    if (rc != 0)\n        return 1;\n    printf(\"ok\\n\");\n\n    return 0;\n}\n"
  },
  {
    "path": "tests/test_xmppaddr.c",
    "content": "/* SPDX-License-Identifier: MIT OR GPL-3.0-only */\n/* test_xmppaddr.c\n** libstrophe XMPP client library -- test routines for the xmppaddr\n** certificate API's\n**\n** Copyright (C) 2021 Steffen Jaeckel\n**\n**  This software is provided AS-IS with no warranty, either express\n**  or implied.\n**\n**  This program is dual licensed under the MIT or GPLv3 licenses.\n*/\n\n#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n#include <sys/param.h>\n\n#include \"strophe.h\"\n\n#include \"test.h\"\n\nstatic int\npassword_callback(char *pw, size_t pw_max, xmpp_conn_t *conn, void *userdata)\n{\n    (void)pw_max;\n    (void)userdata;\n    (void)conn;\n    memcpy(pw, \"abc123\", 7);\n    return 6;\n}\n\nint main()\n{\n    xmpp_ctx_t *ctx;\n    xmpp_conn_t *conn;\n    xmpp_log_t *log;\n    struct {\n        int needs_callback;\n        char *pem, *key;\n    } client_cert[] = {\n        {0, \"tests/cert.pem\", \"tests/key.pem\"},\n        {1, \"tests/cert.pem\", \"tests/key_encrypted.pem\"},\n        {0, NULL, \"tests/cert.emptypass.pfx\"},\n        {0, NULL, \"tests/cert.nopass.pfx\"},\n        {1, NULL, \"tests/cert.pfx\"},\n        {0, \"tests/cert.emptypass.pfx\", NULL},\n        {0, \"tests/cert.nopass.pfx\", NULL},\n        {1, \"tests/cert.pfx\", NULL},\n    };\n\n    const char *srcdir;\n    char *certbuf, *keybuf;\n    char xmppaddr_num[] = \"0\";\n    unsigned int m, n;\n\n    xmpp_initialize();\n    log = xmpp_get_default_logger(XMPP_LEVEL_DEBUG);\n    ctx = xmpp_ctx_new(NULL, log);\n\n    srcdir = getenv(\"srcdir\");\n\n    certbuf = malloc(MAXPATHLEN);\n    keybuf = malloc(MAXPATHLEN);\n\n    for (m = 0; m < sizeof(client_cert) / sizeof(client_cert[0]); ++m) {\n        char *certfile = certbuf, *keyfile = keybuf;\n        conn = xmpp_conn_new(ctx);\n\n        if (client_cert[m].pem)\n            snprintf(certfile, MAXPATHLEN, \"%s/%s\", srcdir, client_cert[m].pem);\n        else\n            certfile = NULL;\n\n        if (client_cert[m].key)\n            snprintf(keyfile, MAXPATHLEN, \"%s/%s\", srcdir, client_cert[m].key);\n        else\n            keyfile = NULL;\n\n        if (client_cert[m].needs_callback)\n            xmpp_conn_set_password_callback(conn, password_callback, NULL);\n\n        xmpp_conn_set_client_cert(conn, certfile, keyfile);\n\n        xmppaddr_num[0] = '0' + xmpp_conn_cert_xmppaddr_num(conn);\n\n        COMPARE(\"2\", xmppaddr_num);\n\n        for (n = 0; n < 3; ++n) {\n            char *r = xmpp_conn_cert_xmppaddr(conn, n);\n            switch (n) {\n            case 0:\n                COMPARE(\n                    \"very.long.username@so.the.asn1.length.is.a.valid.ascii.\"\n                    \"character\",\n                    r);\n                break;\n            case 1:\n                COMPARE(\"second@xmpp.jid\", r);\n                break;\n            default:\n                if (r != NULL) {\n                    printf(\"\\nThere shall only be two id-on-xmppAddr SANs!\\n\"\n                           \"Found another one: %s\\n\",\n                           r);\n                    exit(1);\n                }\n                break;\n            }\n            free(r);\n        }\n        xmpp_conn_release(conn);\n    }\n    free(certbuf);\n    free(keybuf);\n\n    xmpp_ctx_free(ctx);\n    xmpp_shutdown();\n\n    return 0;\n}\n"
  },
  {
    "path": "travis/before_script.sh",
    "content": "#!/bin/sh\n\nset -e\n\n[ \"x$XSSL_COMMITISH\" != \"x\" ]\n\nif [ \"x$LIBRESSL\" = \"xtrue\" ]; then\n    REPO_URL=\"https://github.com/libressl-portable/portable.git\"\n    AUTOGEN_CMD=\"./autogen.sh\"\n    CONFIG_CMD=\"./configure --prefix=$HOME/xssl --disable-asm\"\n    MAKE_TARGET=\"install\"\nelse\n    REPO_URL=\"https://github.com/openssl/openssl.git\"\n    AUTOGEN_CMD=\"true\"\n    CONFIG_CMD=\"./Configure --prefix=$HOME/xssl --libdir=lib\"\n    MAKE_TARGET=\"install_sw\"\nfi\n\ncd \"$HOME\"\ngit clone --no-checkout \"$REPO_URL\" xssl-git\ncd xssl-git\ngit checkout \"$XSSL_COMMITISH\"\n$AUTOGEN_CMD\n$CONFIG_CMD\nmake -j\"$(nproc)\"\nmake $MAKE_TARGET\n"
  }
]