[
  {
    "path": ".gitignore",
    "content": "/target\n/docs\n/.vscode\n/prof\n/tests\n/src/scratch.rs\n/benches\nREF.md\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"faf\"\nversion = \"0.6.0\"\nauthors = [\"James Bates <errantmind@protonmail.com>\"]\nedition = \"2021\"\n\n[features]\ndefault = []\n\n[dependencies]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://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 Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\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,\nour General Public Licenses are 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.\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  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\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 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 work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\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 AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "README.md",
    "content": "# FaF\n\nFaF (Fast as Fuck) is a Linux webserver written in Rust.\n\nFaF..\n\n- has one goal: to demonstrate the upper bound of single-node performance while remaining usable in a production setting (for high speed delivery of small to moderate payloads, like web pages or files, bounded by the constant `RES_BUFF_SIZE`)\n- was designed to be easily understood while providing cutting edge performance. Each facet of FaF has been meticulously benchmarked and all design decisions were deliberate.\n- is open to community contributions that further improve its speed or eliminate redundancy\n- is open to issues that clearly demonstrate a security vulnerability.\n- has no Rust dependencies and can be converted into a `#![no_std]` project. See `Code Tour` below for more info. A side-benefit of this is a very small attack surface.\n\n## Requirements and How-To\n\nFaF requires:\n\n- linux x86_64\n- nightly Rust\n\nFaF recommends:\n\n- to compile using a version of llvm (clang and ldd) that match your Rust's LLVM version. You can get this using `rustc -V -v`\n- to be run as root; it is not required though. FaF uses root to set process priority as well as a setting or two related to the socket options\n\nTo use FaF for your own purposes, provide a callback which modifies the response buffer. The response buffer will have a length as defined in the FaF project, so it is easy to ensure you do not write past this length. If you need more buffer, increase the value of the constant `RES_BUFF_SIZE` in this project. From the callback, return the number of bytes you wrote to the buffer. The callback will be called once per HTTP request. See the [FaF Example Project](https://github.com/errantmind/faf-example) for more information.\n\n## Design Principles\n\n1. Speed. Optimize for serving small to moderate payloads to a large number of concurrent connections. Speed will be balanced against over-specialization, like rewriting the entire project in hand-optimized assembly. Speed optimizations are constrained to unsafe Rust, unless the results of some alternative approach are overwhelmingly convincing.\n2. Elegance as Simplicity. Consistency in the architecture, project structure, idioms, and style. Some of these idioms and styling are particular to my taste. Will use a 'right tool for the right job' approach when choosing data structures and algorithms.\n3. Memory Safety. This being third is generally at odds with the Rust community, but if you have read all the text above you will understand. Memory safety is prioritized in-so-far as it has no decernable effect on performance. It should also be implemented in such a way that doesn't add excessive complexity / indirection in the project.\n\n(in that order)\n\n## Code Tour\n\nJust look at `epoll.rs`, everything is either there or referenced there and, even then, it is only ~200 lines of code.\n\nAside: a `no_std` version of this project compiles to a total of only ~400 lines of assembly TEXT, and 7KB binary, although it takes a few modifications to get there: the only real dependency on std is threading, so if we eliminate it and change to a `1 process per core` model instead of `1 thread per core` we get a very minimal setup. The performance is ~1% worse. If you are interested in this, let's discuss.\n\n## Contributions\n\nContributions are welcome, but please discuss before submitting a pull request. If a discussion leads to a pull request, please reference the \\#issue in the pull request. Unsolicited pull requests will not be reviewed nor merged.\n\n## License\n\nAll code is licensed under AGPL 3.0 unless an individual source file specifies otherwise.\n"
  },
  {
    "path": "rustfmt.toml",
    "content": "use_small_heuristics = \"Max\"\ntab_spaces = 3\nmax_width = 140\nreorder_imports = true\n"
  },
  {
    "path": "src/const_config.rs",
    "content": "/*\nFaF is a cutting edge, high performance web server\nCopyright (C) 2021  James Bates\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\n#[macro_export(local_inner_macros)]\nmacro_rules! const_concat_bytes {\n    () => {\n        \"\"\n    };\n    ($a:expr) => {\n        $a\n    };\n    ($a:expr, $b:expr) => {{\n        let bytes: &'static [u8] = unsafe {\n            &$crate::util::concat::<\n                [u8; $a.len()],\n                [u8; $b.len()],\n                [u8; $a.len() + $b.len()],\n            >($a, $b)\n        };\n\n        unsafe { $crate::util::transmute(bytes) }\n    }};\n    ($a:expr, $($rest:expr),*) => {{\n        pub const TAIL: &[u8] = const_concat_bytes!($($rest),*);\n        const_concat_bytes!($a, TAIL)\n    }};\n    ($a:expr, $($rest:expr),*,) => {\n        const_concat_bytes!($a, $($rest),*)\n    };\n}\n\n/// faf spawns one thread per core, meaning each thread can handle 1024 connections\npub const MAX_CONN: usize = 1024;\n\n/// the buffer size of the request buffer. Currently set to 4096 bytes\npub const REQ_BUFF_SIZE: usize = 4096;\n\n/// the buffer size of both the response buffers. Currently set to 4096 bytes\npub const RES_BUFF_SIZE: usize = 4096;\n\n/// our syscall to wait for epoll events will block indefinitely when this value is used\npub const EPOLL_TIMEOUT_BLOCKING: isize = -1;\n\n/// our syscall to wait for epoll events will return immediately when this value is used\npub const EPOLL_TIMEOUT_IMMEDIATE_RETURN: isize = 0;\n\n/// 4096 bytes / 12 byte epoll_event size = ~340.\npub const MAX_EPOLL_EVENTS_RETURNED: usize = 340;\n"
  },
  {
    "path": "src/const_http.rs",
    "content": "/*\nFaF is a cutting edge, high performance web server\nCopyright (C) 2021  James Bates\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\n#![allow(dead_code)]\n\nuse crate::util::const_len;\n\npub const GET: &[u8] = b\"GET\";\npub const GET_LEN: usize = const_len(GET);\npub const HEAD: &[u8] = b\"HEAD\";\npub const HEAD_LEN: usize = const_len(HEAD);\npub const POST: &[u8] = b\"POST\";\npub const POST_LEN: usize = const_len(POST);\npub const PUT: &[u8] = b\"PUT\";\npub const PUT_LEN: usize = const_len(PUT);\npub const DELETE: &[u8] = b\"DELETE\";\npub const DELETE_LEN: usize = const_len(DELETE);\npub const CONNECT: &[u8] = b\"CONNECT\";\npub const CONNECT_LEN: usize = const_len(CONNECT);\npub const OPTIONS: &[u8] = b\"OPTIONS\";\npub const OPTIONS_LEN: usize = const_len(OPTIONS);\npub const TRACE: &[u8] = b\"TRACE\";\npub const TRACE_LEN: usize = const_len(TRACE);\npub const PATCH: &[u8] = b\"PATCH\";\npub const PATCH_LEN: usize = const_len(PATCH);\n\npub const CRLF: &[u8] = b\"\\r\\n\";\npub const CRLF_LEN: usize = 2;\npub const CRLFCRLF: &[u8] = b\"\\r\\n\\r\\n\";\npub const CRLFCRLF_LEN: usize = 4;\n\npub const SERVER: &[u8] = b\"Server: F\";\npub const DATE_LEN: usize = 35;\n\npub const HTTP_200_OK: &[u8] = b\"HTTP/1.1 200 OK\";\npub const HTTP_200_OK_LEN: usize = const_len(HTTP_200_OK);\n\npub const HTTP_404_NOTFOUND: &[u8] = b\"HTTP/1.1 404 Not Found\\r\\nContent-Length: 0\\r\\n\\r\\n\";\npub const HTTP_404_NOTFOUND_LEN: usize = const_len(HTTP_404_NOTFOUND);\n\npub const HTTP_405_NOTALLOWED: &[u8] = b\"HTTP/1.1 405 Method Not Allowed\\r\\nContent-Length: 0\\r\\n\\r\\n\";\npub const HTTP_405_NOTALLOWED_LEN: usize = const_len(HTTP_405_NOTALLOWED);\n\npub const HTTP_500_NOTFOUND: &[u8] = b\"HTTP/1.1 500 Internal Server Error\\r\\nContent-Length: 0\\r\\n\\r\\n\";\npub const HTTP_500_NOTFOUND_LEN: usize = const_len(HTTP_500_NOTFOUND);\n\npub const EXAMPLE_HTTP_RESPONSE: &[u8] = b\"HTTP/1.1 200 OK\\r\\nContent-Length: 15\\r\\nContent-Type: text/plain\\r\\nServer: F\\r\\nDate: Wed, 24 Feb 2021 12:00:00 GMT\\r\\n\\r\\nHello, World!\";\npub const EXAMPLE_HTTP_RESPONSE_LEN: usize = const_len(EXAMPLE_HTTP_RESPONSE);\n"
  },
  {
    "path": "src/const_sys.rs",
    "content": "// This particular file is LICENSED AS GPLv2 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html)\n\n#![allow(dead_code)]\n\n// Manually transformed from /usr/include/x86_64-linux-gnu/asm/unistd_64.h\n\npub const SYS_READ: u32 = 0;\npub const SYS_WRITE: u32 = 1;\npub const SYS_OPEN: u32 = 2;\npub const SYS_CLOSE: u32 = 3;\npub const SYS_STAT: u32 = 4;\npub const SYS_FSTAT: u32 = 5;\npub const SYS_LSTAT: u32 = 6;\npub const SYS_POLL: u32 = 7;\npub const SYS_LSEEK: u32 = 8;\npub const SYS_MMAP: u32 = 9;\npub const SYS_MPROTECT: u32 = 10;\npub const SYS_MUNMAP: u32 = 11;\npub const SYS_BRK: u32 = 12;\npub const SYS_RT_SIGACTION: u32 = 13;\npub const SYS_RT_SIGPROCMASK: u32 = 14;\npub const SYS_RT_SIGRETURN: u32 = 15;\npub const SYS_IOCTL: u32 = 16;\npub const SYS_PREAD64: u32 = 17;\npub const SYS_PWRITE64: u32 = 18;\npub const SYS_READV: u32 = 19;\npub const SYS_WRITEV: u32 = 20;\npub const SYS_ACCESS: u32 = 21;\npub const SYS_PIPE: u32 = 22;\npub const SYS_SELECT: u32 = 23;\npub const SYS_SCHED_YIELD: u32 = 24;\npub const SYS_MREMAP: u32 = 25;\npub const SYS_MSYNC: u32 = 26;\npub const SYS_MINCORE: u32 = 27;\npub const SYS_MADVISE: u32 = 28;\npub const SYS_SHMGET: u32 = 29;\npub const SYS_SHMAT: u32 = 30;\npub const SYS_SHMCTL: u32 = 31;\npub const SYS_DUP: u32 = 32;\npub const SYS_DUP2: u32 = 33;\npub const SYS_PAUSE: u32 = 34;\npub const SYS_NANOSLEEP: u32 = 35;\npub const SYS_GETITIMER: u32 = 36;\npub const SYS_ALARM: u32 = 37;\npub const SYS_SETITIMER: u32 = 38;\npub const SYS_GETPID: u32 = 39;\npub const SYS_SENDFILE: u32 = 40;\npub const SYS_SOCKET: u32 = 41;\npub const SYS_CONNECT: u32 = 42;\npub const SYS_ACCEPT: u32 = 43;\npub const SYS_SENDTO: u32 = 44;\npub const SYS_RECVFROM: u32 = 45;\npub const SYS_SENDMSG: u32 = 46;\npub const SYS_RECVMSG: u32 = 47;\npub const SYS_SHUTDOWN: u32 = 48;\npub const SYS_BIND: u32 = 49;\npub const SYS_LISTEN: u32 = 50;\npub const SYS_GETSOCKNAME: u32 = 51;\npub const SYS_GETPEERNAME: u32 = 52;\npub const SYS_SOCKETPAIR: u32 = 53;\npub const SYS_SETSOCKOPT: u32 = 54;\npub const SYS_GETSOCKOPT: u32 = 55;\npub const SYS_CLONE: u32 = 56;\npub const SYS_FORK: u32 = 57;\npub const SYS_VFORK: u32 = 58;\npub const SYS_EXECVE: u32 = 59;\npub const SYS_EXIT: u32 = 60;\npub const SYS_WAIT4: u32 = 61;\npub const SYS_KILL: u32 = 62;\npub const SYS_UNAME: u32 = 63;\npub const SYS_SEMGET: u32 = 64;\npub const SYS_SEMOP: u32 = 65;\npub const SYS_SEMCTL: u32 = 66;\npub const SYS_SHMDT: u32 = 67;\npub const SYS_MSGGET: u32 = 68;\npub const SYS_MSGSND: u32 = 69;\npub const SYS_MSGRCV: u32 = 70;\npub const SYS_MSGCTL: u32 = 71;\npub const SYS_FCNTL: u32 = 72;\npub const SYS_FLOCK: u32 = 73;\npub const SYS_FSYNC: u32 = 74;\npub const SYS_FDATASYNC: u32 = 75;\npub const SYS_TRUNCATE: u32 = 76;\npub const SYS_FTRUNCATE: u32 = 77;\npub const SYS_GETDENTS: u32 = 78;\npub const SYS_GETCWD: u32 = 79;\npub const SYS_CHDIR: u32 = 80;\npub const SYS_FCHDIR: u32 = 81;\npub const SYS_RENAME: u32 = 82;\npub const SYS_MKDIR: u32 = 83;\npub const SYS_RMDIR: u32 = 84;\npub const SYS_CREAT: u32 = 85;\npub const SYS_LINK: u32 = 86;\npub const SYS_UNLINK: u32 = 87;\npub const SYS_SYMLINK: u32 = 88;\npub const SYS_READLINK: u32 = 89;\npub const SYS_CHMOD: u32 = 90;\npub const SYS_FCHMOD: u32 = 91;\npub const SYS_CHOWN: u32 = 92;\npub const SYS_FCHOWN: u32 = 93;\npub const SYS_LCHOWN: u32 = 94;\npub const SYS_UMASK: u32 = 95;\npub const SYS_GETTIMEOFDAY: u32 = 96;\npub const SYS_GETRLIMIT: u32 = 97;\npub const SYS_GETRUSAGE: u32 = 98;\npub const SYS_SYSINFO: u32 = 99;\npub const SYS_TIMES: u32 = 100;\npub const SYS_PTRACE: u32 = 101;\npub const SYS_GETUID: u32 = 102;\npub const SYS_SYSLOG: u32 = 103;\npub const SYS_GETGID: u32 = 104;\npub const SYS_SETUID: u32 = 105;\npub const SYS_SETGID: u32 = 106;\npub const SYS_GETEUID: u32 = 107;\npub const SYS_GETEGID: u32 = 108;\npub const SYS_SETPGID: u32 = 109;\npub const SYS_GETPPID: u32 = 110;\npub const SYS_GETPGRP: u32 = 111;\npub const SYS_SETSID: u32 = 112;\npub const SYS_SETREUID: u32 = 113;\npub const SYS_SETREGID: u32 = 114;\npub const SYS_GETGROUPS: u32 = 115;\npub const SYS_SETGROUPS: u32 = 116;\npub const SYS_SETRESUID: u32 = 117;\npub const SYS_GETRESUID: u32 = 118;\npub const SYS_SETRESGID: u32 = 119;\npub const SYS_GETRESGID: u32 = 120;\npub const SYS_GETPGID: u32 = 121;\npub const SYS_SETFSUID: u32 = 122;\npub const SYS_SETFSGID: u32 = 123;\npub const SYS_GETSID: u32 = 124;\npub const SYS_CAPGET: u32 = 125;\npub const SYS_CAPSET: u32 = 126;\npub const SYS_RT_SIGPENDING: u32 = 127;\npub const SYS_RT_SIGTIMEDWAIT: u32 = 128;\npub const SYS_RT_SIGQUEUEINFO: u32 = 129;\npub const SYS_RT_SIGSUSPEND: u32 = 130;\npub const SYS_SIGALTSTACK: u32 = 131;\npub const SYS_UTIME: u32 = 132;\npub const SYS_MKNOD: u32 = 133;\npub const SYS_USELIB: u32 = 134;\npub const SYS_PERSONALITY: u32 = 135;\npub const SYS_USTAT: u32 = 136;\npub const SYS_STATFS: u32 = 137;\npub const SYS_FSTATFS: u32 = 138;\npub const SYS_SYSFS: u32 = 139;\npub const SYS_GETPRIORITY: u32 = 140;\npub const SYS_SETPRIORITY: u32 = 141;\npub const SYS_SCHED_SETPARAM: u32 = 142;\npub const SYS_SCHED_GETPARAM: u32 = 143;\npub const SYS_SCHED_SETSCHEDULER: u32 = 144;\npub const SYS_SCHED_GETSCHEDULER: u32 = 145;\npub const SYS_SCHED_GET_PRIORITY_MAX: u32 = 146;\npub const SYS_SCHED_GET_PRIORITY_MIN: u32 = 147;\npub const SYS_SCHED_RR_GET_INTERVAL: u32 = 148;\npub const SYS_MLOCK: u32 = 149;\npub const SYS_MUNLOCK: u32 = 150;\npub const SYS_MLOCKALL: u32 = 151;\npub const SYS_MUNLOCKALL: u32 = 152;\npub const SYS_VHANGUP: u32 = 153;\npub const SYS_MODIFY_LDT: u32 = 154;\npub const SYS_PIVOT_ROOT: u32 = 155;\npub const SYS__SYSCTL: u32 = 156;\npub const SYS_PRCTL: u32 = 157;\npub const SYS_ARCH_PRCTL: u32 = 158;\npub const SYS_ADJTIMEX: u32 = 159;\npub const SYS_SETRLIMIT: u32 = 160;\npub const SYS_CHROOT: u32 = 161;\npub const SYS_SYNC: u32 = 162;\npub const SYS_ACCT: u32 = 163;\npub const SYS_SETTIMEOFDAY: u32 = 164;\npub const SYS_MOUNT: u32 = 165;\npub const SYS_UMOUNT2: u32 = 166;\npub const SYS_SWAPON: u32 = 167;\npub const SYS_SWAPOFF: u32 = 168;\npub const SYS_REBOOT: u32 = 169;\npub const SYS_SETHOSTNAME: u32 = 170;\npub const SYS_SETDOMAINNAME: u32 = 171;\npub const SYS_IOPL: u32 = 172;\npub const SYS_IOPERM: u32 = 173;\npub const SYS_CREATE_MODULE: u32 = 174;\npub const SYS_INIT_MODULE: u32 = 175;\npub const SYS_DELETE_MODULE: u32 = 176;\npub const SYS_GET_KERNEL_SYMS: u32 = 177;\npub const SYS_QUERY_MODULE: u32 = 178;\npub const SYS_QUOTACTL: u32 = 179;\npub const SYS_NFSSERVCTL: u32 = 180;\npub const SYS_GETPMSG: u32 = 181;\npub const SYS_PUTPMSG: u32 = 182;\npub const SYS_AFS_SYSCALL: u32 = 183;\npub const SYS_TUXCALL: u32 = 184;\npub const SYS_SECURITY: u32 = 185;\npub const SYS_GETTID: u32 = 186;\npub const SYS_READAHEAD: u32 = 187;\npub const SYS_SETXATTR: u32 = 188;\npub const SYS_LSETXATTR: u32 = 189;\npub const SYS_FSETXATTR: u32 = 190;\npub const SYS_GETXATTR: u32 = 191;\npub const SYS_LGETXATTR: u32 = 192;\npub const SYS_FGETXATTR: u32 = 193;\npub const SYS_LISTXATTR: u32 = 194;\npub const SYS_LLISTXATTR: u32 = 195;\npub const SYS_FLISTXATTR: u32 = 196;\npub const SYS_REMOVEXATTR: u32 = 197;\npub const SYS_LREMOVEXATTR: u32 = 198;\npub const SYS_FREMOVEXATTR: u32 = 199;\npub const SYS_TKILL: u32 = 200;\npub const SYS_TIME: u32 = 201;\npub const SYS_FUTEX: u32 = 202;\npub const SYS_SCHED_SETAFFINITY: u32 = 203;\npub const SYS_SCHED_GETAFFINITY: u32 = 204;\npub const SYS_SET_THREAD_AREA: u32 = 205;\npub const SYS_IO_SETUP: u32 = 206;\npub const SYS_IO_DESTROY: u32 = 207;\npub const SYS_IO_GETEVENTS: u32 = 208;\npub const SYS_IO_SUBMIT: u32 = 209;\npub const SYS_IO_CANCEL: u32 = 210;\npub const SYS_GET_THREAD_AREA: u32 = 211;\npub const SYS_LOOKUP_DCOOKIE: u32 = 212;\npub const SYS_EPOLL_CREATE: u32 = 213;\npub const SYS_EPOLL_CTL_OLD: u32 = 214;\npub const SYS_EPOLL_WAIT_OLD: u32 = 215;\npub const SYS_REMAP_FILE_PAGES: u32 = 216;\npub const SYS_GETDENTS64: u32 = 217;\npub const SYS_SET_TID_ADDRESS: u32 = 218;\npub const SYS_RESTART_SYSCALL: u32 = 219;\npub const SYS_SEMTIMEDOP: u32 = 220;\npub const SYS_FADVISE64: u32 = 221;\npub const SYS_TIMER_CREATE: u32 = 222;\npub const SYS_TIMER_SETTIME: u32 = 223;\npub const SYS_TIMER_GETTIME: u32 = 224;\npub const SYS_TIMER_GETOVERRUN: u32 = 225;\npub const SYS_TIMER_DELETE: u32 = 226;\npub const SYS_CLOCK_SETTIME: u32 = 227;\npub const SYS_CLOCK_GETTIME: u32 = 228;\npub const SYS_CLOCK_GETRES: u32 = 229;\npub const SYS_CLOCK_NANOSLEEP: u32 = 230;\npub const SYS_EXIT_GROUP: u32 = 231;\npub const SYS_EPOLL_WAIT: u32 = 232;\npub const SYS_EPOLL_CTL: u32 = 233;\npub const SYS_TGKILL: u32 = 234;\npub const SYS_UTIMES: u32 = 235;\npub const SYS_VSERVER: u32 = 236;\npub const SYS_MBIND: u32 = 237;\npub const SYS_SET_MEMPOLICY: u32 = 238;\npub const SYS_GET_MEMPOLICY: u32 = 239;\npub const SYS_MQ_OPEN: u32 = 240;\npub const SYS_MQ_UNLINK: u32 = 241;\npub const SYS_MQ_TIMEDSEND: u32 = 242;\npub const SYS_MQ_TIMEDRECEIVE: u32 = 243;\npub const SYS_MQ_NOTIFY: u32 = 244;\npub const SYS_MQ_GETSETATTR: u32 = 245;\npub const SYS_KEXEC_LOAD: u32 = 246;\npub const SYS_WAITID: u32 = 247;\npub const SYS_ADD_KEY: u32 = 248;\npub const SYS_REQUEST_KEY: u32 = 249;\npub const SYS_KEYCTL: u32 = 250;\npub const SYS_IOPRIO_SET: u32 = 251;\npub const SYS_IOPRIO_GET: u32 = 252;\npub const SYS_INOTIFY_INIT: u32 = 253;\npub const SYS_INOTIFY_ADD_WATCH: u32 = 254;\npub const SYS_INOTIFY_RM_WATCH: u32 = 255;\npub const SYS_MIGRATE_PAGES: u32 = 256;\npub const SYS_OPENAT: u32 = 257;\npub const SYS_MKDIRAT: u32 = 258;\npub const SYS_MKNODAT: u32 = 259;\npub const SYS_FCHOWNAT: u32 = 260;\npub const SYS_FUTIMESAT: u32 = 261;\npub const SYS_NEWFSTATAT: u32 = 262;\npub const SYS_UNLINKAT: u32 = 263;\npub const SYS_RENAMEAT: u32 = 264;\npub const SYS_LINKAT: u32 = 265;\npub const SYS_SYMLINKAT: u32 = 266;\npub const SYS_READLINKAT: u32 = 267;\npub const SYS_FCHMODAT: u32 = 268;\npub const SYS_FACCESSAT: u32 = 269;\npub const SYS_PSELECT6: u32 = 270;\npub const SYS_PPOLL: u32 = 271;\npub const SYS_UNSHARE: u32 = 272;\npub const SYS_SET_ROBUST_LIST: u32 = 273;\npub const SYS_GET_ROBUST_LIST: u32 = 274;\npub const SYS_SPLICE: u32 = 275;\npub const SYS_TEE: u32 = 276;\npub const SYS_SYNC_FILE_RANGE: u32 = 277;\npub const SYS_VMSPLICE: u32 = 278;\npub const SYS_MOVE_PAGES: u32 = 279;\npub const SYS_UTIMENSAT: u32 = 280;\npub const SYS_EPOLL_PWAIT: u32 = 281;\npub const SYS_SIGNALFD: u32 = 282;\npub const SYS_TIMERFD_CREATE: u32 = 283;\npub const SYS_EVENTFD: u32 = 284;\npub const SYS_FALLOCATE: u32 = 285;\npub const SYS_TIMERFD_SETTIME: u32 = 286;\npub const SYS_TIMERFD_GETTIME: u32 = 287;\npub const SYS_ACCEPT4: u32 = 288;\npub const SYS_SIGNALFD4: u32 = 289;\npub const SYS_EVENTFD2: u32 = 290;\npub const SYS_EPOLL_CREATE1: u32 = 291;\npub const SYS_DUP3: u32 = 292;\npub const SYS_PIPE2: u32 = 293;\npub const SYS_INOTIFY_INIT1: u32 = 294;\npub const SYS_PREADV: u32 = 295;\npub const SYS_PWRITEV: u32 = 296;\npub const SYS_RT_TGSIGQUEUEINFO: u32 = 297;\npub const SYS_PERF_EVENT_OPEN: u32 = 298;\npub const SYS_RECVMMSG: u32 = 299;\npub const SYS_FANOTIFY_INIT: u32 = 300;\npub const SYS_FANOTIFY_MARK: u32 = 301;\npub const SYS_PRLIMIT64: u32 = 302;\npub const SYS_NAME_TO_HANDLE_AT: u32 = 303;\npub const SYS_OPEN_BY_HANDLE_AT: u32 = 304;\npub const SYS_CLOCK_ADJTIME: u32 = 305;\npub const SYS_SYNCFS: u32 = 306;\npub const SYS_SENDMMSG: u32 = 307;\npub const SYS_SETNS: u32 = 308;\npub const SYS_GETCPU: u32 = 309;\npub const SYS_PROCESS_VM_READV: u32 = 310;\npub const SYS_PROCESS_VM_WRITEV: u32 = 311;\npub const SYS_KCMP: u32 = 312;\npub const SYS_FINIT_MODULE: u32 = 313;\npub const SYS_SCHED_SETATTR: u32 = 314;\npub const SYS_SCHED_GETATTR: u32 = 315;\npub const SYS_RENAMEAT2: u32 = 316;\npub const SYS_SECCOMP: u32 = 317;\npub const SYS_GETRANDOM: u32 = 318;\npub const SYS_MEMFD_CREATE: u32 = 319;\npub const SYS_KEXEC_FILE_LOAD: u32 = 320;\npub const SYS_BPF: u32 = 321;\npub const SYS_EXECVEAT: u32 = 322;\npub const SYS_USERFAULTFD: u32 = 323;\npub const SYS_MEMBARRIER: u32 = 324;\npub const SYS_MLOCK2: u32 = 325;\npub const SYS_COPY_FILE_RANGE: u32 = 326;\npub const SYS_PREADV2: u32 = 327;\npub const SYS_PWRITEV2: u32 = 328;\npub const SYS_PKEY_MPROTECT: u32 = 329;\npub const SYS_PKEY_ALLOC: u32 = 330;\npub const SYS_PKEY_FREE: u32 = 331;\npub const SYS_STATX: u32 = 332;\npub const SYS_IO_PGETEVENTS: u32 = 333;\npub const SYS_RSEQ: u32 = 334;\npub const SYS_PIDFD_SEND_SIGNAL: u32 = 424;\npub const SYS_IO_URING_SETUP: u32 = 425;\npub const SYS_IO_URING_ENTER: u32 = 426;\npub const SYS_IO_URING_REGISTER: u32 = 427;\npub const SYS_OPEN_TREE: u32 = 428;\npub const SYS_MOVE_MOUNT: u32 = 429;\npub const SYS_FSOPEN: u32 = 430;\npub const SYS_FSCONFIG: u32 = 431;\npub const SYS_FSMOUNT: u32 = 432;\npub const SYS_FSPICK: u32 = 433;\npub const SYS_PIDFD_OPEN: u32 = 434;\npub const SYS_CLONE3: u32 = 435;\npub const SYS_OPENAT2: u32 = 437;\npub const SYS_PIDFD_GETFD: u32 = 438;\npub const SYS_FACCESSAT2: u32 = 439;\n\n// Manually transformed from /usr/include/asm-generic/errno-base.h\n// and /usr/include/asm-generic/errno.h\npub const EPERM: u32 = 1;\npub const ENOENT: u32 = 2;\npub const ESRCH: u32 = 3;\npub const EINTR: u32 = 4;\npub const EIO: u32 = 5;\npub const ENXIO: u32 = 6;\npub const E2BIG: u32 = 7;\npub const ENOEXEC: u32 = 8;\npub const EBADF: u32 = 9;\npub const ECHILD: u32 = 10;\npub const EAGAIN: u32 = 11;\npub const ENOMEM: u32 = 12;\npub const EACCES: u32 = 13;\npub const EFAULT: u32 = 14;\npub const ENOTBLK: u32 = 15;\npub const EBUSY: u32 = 16;\npub const EEXIST: u32 = 17;\npub const EXDEV: u32 = 18;\npub const ENODEV: u32 = 19;\npub const ENOTDIR: u32 = 20;\npub const EISDIR: u32 = 21;\npub const EINVAL: u32 = 22;\npub const ENFILE: u32 = 23;\npub const EMFILE: u32 = 24;\npub const ENOTTY: u32 = 25;\npub const ETXTBSY: u32 = 26;\npub const EFBIG: u32 = 27;\npub const ENOSPC: u32 = 28;\npub const ESPIPE: u32 = 29;\npub const EROFS: u32 = 30;\npub const EMLINK: u32 = 31;\npub const EPIPE: u32 = 32;\npub const EDOM: u32 = 33;\npub const ERANGE: u32 = 34;\npub const EDEADLK: u32 = 35;\npub const ENAMETOOLONG: u32 = 36;\npub const ENOLCK: u32 = 37;\npub const ENOSYS: u32 = 38;\npub const ENOTEMPTY: u32 = 39;\npub const ELOOP: u32 = 40;\npub const EWOULDBLOCK: u32 = 11; // EAGAIN\npub const ENOMSG: u32 = 42;\npub const EIDRM: u32 = 43;\npub const ECHRNG: u32 = 44;\npub const EL2NSYNC: u32 = 45;\npub const EL3HLT: u32 = 46;\npub const EL3RST: u32 = 47;\npub const ELNRNG: u32 = 48;\npub const EUNATCH: u32 = 49;\npub const ENOCSI: u32 = 50;\npub const EL2HLT: u32 = 51;\npub const EBADE: u32 = 52;\npub const EBADR: u32 = 53;\npub const EXFULL: u32 = 54;\npub const ENOANO: u32 = 55;\npub const EBADRQC: u32 = 56;\npub const EBADSLT: u32 = 57;\npub const EDEADLOCK: u32 = 35; // EDEADLK\npub const EBFONT: u32 = 59;\npub const ENOSTR: u32 = 60;\npub const ENODATA: u32 = 61;\npub const ETIME: u32 = 62;\npub const ENOSR: u32 = 63;\npub const ENONET: u32 = 64;\npub const ENOPKG: u32 = 65;\npub const EREMOTE: u32 = 66;\npub const ENOLINK: u32 = 67;\npub const EADV: u32 = 68;\npub const ESRMNT: u32 = 69;\npub const ECOMM: u32 = 70;\npub const EPROTO: u32 = 71;\npub const EMULTIHOP: u32 = 72;\npub const EDOTDOT: u32 = 73;\npub const EBADMSG: u32 = 74;\npub const EOVERFLOW: u32 = 75;\npub const ENOTUNIQ: u32 = 76;\npub const EBADFD: u32 = 77;\npub const EREMCHG: u32 = 78;\npub const ELIBACC: u32 = 79;\npub const ELIBBAD: u32 = 80;\npub const ELIBSCN: u32 = 81;\npub const ELIBMAX: u32 = 82;\npub const ELIBEXEC: u32 = 83;\npub const EILSEQ: u32 = 84;\npub const ERESTART: u32 = 85;\npub const ESTRPIPE: u32 = 86;\npub const EUSERS: u32 = 87;\npub const ENOTSOCK: u32 = 88;\npub const EDESTADDRREQ: u32 = 89;\npub const EMSGSIZE: u32 = 90;\npub const EPROTOTYPE: u32 = 91;\npub const ENOPROTOOPT: u32 = 92;\npub const EPROTONOSUPPORT: u32 = 93;\npub const ESOCKTNOSUPPORT: u32 = 94;\npub const EOPNOTSUPP: u32 = 95;\npub const EPFNOSUPPORT: u32 = 96;\npub const EAFNOSUPPORT: u32 = 97;\npub const EADDRINUSE: u32 = 98;\npub const EADDRNOTAVAIL: u32 = 99;\npub const ENETDOWN: u32 = 100;\npub const ENETUNREACH: u32 = 101;\npub const ENETRESET: u32 = 102;\npub const ECONNABORTED: u32 = 103;\npub const ECONNRESET: u32 = 104;\npub const ENOBUFS: u32 = 105;\npub const EISCONN: u32 = 106;\npub const ENOTCONN: u32 = 107;\npub const ESHUTDOWN: u32 = 108;\npub const ETOOMANYREFS: u32 = 109;\npub const ETIMEDOUT: u32 = 110;\npub const ECONNREFUSED: u32 = 111;\npub const EHOSTDOWN: u32 = 112;\npub const EHOSTUNREACH: u32 = 113;\npub const EALREADY: u32 = 114;\npub const EINPROGRESS: u32 = 115;\npub const ESTALE: u32 = 116;\npub const EUCLEAN: u32 = 117;\npub const ENOTNAM: u32 = 118;\npub const ENAVAIL: u32 = 119;\npub const EISNAM: u32 = 120;\npub const EREMOTEIO: u32 = 121;\npub const EDQUOT: u32 = 122;\npub const ENOMEDIUM: u32 = 123;\npub const EMEDIUMTYPE: u32 = 124;\npub const ECANCELED: u32 = 125;\npub const ENOKEY: u32 = 126;\npub const EKEYEXPIRED: u32 = 127;\npub const EKEYREVOKED: u32 = 128;\npub const EKEYREJECTED: u32 = 129;\npub const EOWNERDEAD: u32 = 130;\npub const ENOTRECOVERABLE: u32 = 131;\npub const ERFKILL: u32 = 132;\npub const EHWPOISON: u32 = 133;\n\n//\n\npub const O_DIRECT: i32 = 0x4000;\npub const O_DIRECTORY: i32 = 0x10000;\npub const O_NOFOLLOW: i32 = 0x20000;\npub const O_APPEND: i32 = 1024;\npub const O_CREAT: i32 = 64;\npub const O_EXCL: i32 = 128;\npub const O_NOCTTY: i32 = 256;\npub const O_NONBLOCK: i32 = 2048;\npub const O_SYNC: i32 = 1052672;\npub const O_RSYNC: i32 = 1052672;\npub const O_DSYNC: i32 = 4096;\npub const O_FSYNC: i32 = 0x101000;\npub const O_NOATIME: i32 = 0o1000000;\npub const O_PATH: i32 = 0o10000000;\npub const O_TMPFILE: i32 = 0o20000000 | O_DIRECTORY;\n\npub const SOL_SOCKET: i32 = 1;\n\npub const SO_REUSEADDR: i32 = 2;\npub const SO_TYPE: i32 = 3;\npub const SO_ERROR: i32 = 4;\npub const SO_DONTROUTE: i32 = 5;\npub const SO_BROADCAST: i32 = 6;\npub const SO_SNDBUF: i32 = 7;\npub const SO_RCVBUF: i32 = 8;\npub const SO_SNDBUFFORCE: i32 = 32;\npub const SO_RCVBUFFORCE: i32 = 33;\npub const SO_KEEPALIVE: i32 = 9;\npub const SO_OOBINLINE: i32 = 10;\npub const SO_NO_CHECK: i32 = 11;\npub const SO_PRIORITY: i32 = 12;\npub const SO_LINGER: i32 = 13;\npub const SO_BSDCOMPAT: i32 = 14;\npub const SO_REUSEPORT: i32 = 15;\npub const SO_PASSCRED: i32 = 16;\npub const SO_PEERCRED: i32 = 17;\npub const SO_RCVLOWAT: i32 = 18;\npub const SO_SNDLOWAT: i32 = 19;\npub const SO_RCVTIMEO: i32 = 20;\npub const SO_SNDTIMEO: i32 = 21;\npub const SO_SECURITY_AUTHENTICATION: i32 = 22;\npub const SO_SECURITY_ENCRYPTION_TRANSPORT: i32 = 23;\npub const SO_SECURITY_ENCRYPTION_NETWORK: i32 = 24;\npub const SO_BINDTODEVICE: i32 = 25;\npub const SO_ATTACH_FILTER: i32 = 26;\npub const SO_DETACH_FILTER: i32 = 27;\npub const SO_GET_FILTER: i32 = SO_ATTACH_FILTER;\npub const SO_PEERNAME: i32 = 28;\npub const SO_TIMESTAMP: i32 = 29;\npub const SO_ACCEPTCONN: i32 = 30;\npub const SO_PEERSEC: i32 = 31;\npub const SO_PASSSEC: i32 = 34;\npub const SO_TIMESTAMPNS: i32 = 35;\npub const SCM_TIMESTAMPNS: i32 = SO_TIMESTAMPNS;\npub const SO_MARK: i32 = 36;\npub const SO_PROTOCOL: i32 = 38;\npub const SO_DOMAIN: i32 = 39;\npub const SO_RXQ_OVFL: i32 = 40;\npub const SO_WIFI_STATUS: i32 = 41;\npub const SCM_WIFI_STATUS: i32 = SO_WIFI_STATUS;\npub const SO_PEEK_OFF: i32 = 42;\npub const SO_NOFCS: i32 = 43;\npub const SO_LOCK_FILTER: i32 = 44;\npub const SO_SELECT_ERR_QUEUE: i32 = 45;\npub const SO_BUSY_POLL: i32 = 46;\npub const SO_MAX_PACING_RATE: i32 = 47;\npub const SO_BPF_EXTENSIONS: i32 = 48;\npub const SO_INCOMING_CPU: i32 = 49;\npub const SO_ATTACH_BPF: i32 = 50;\npub const SO_DETACH_BPF: i32 = SO_DETACH_FILTER;\npub const SO_ATTACH_REUSEPORT_CBPF: i32 = 51;\npub const SO_ATTACH_REUSEPORT_EBPF: i32 = 52;\npub const SO_CNX_ADVICE: i32 = 53;\npub const SCM_TIMESTAMPING_OPT_STATS: i32 = 54;\npub const SO_MEMINFO: i32 = 55;\npub const SO_INCOMING_NAPI_ID: i32 = 56;\npub const SO_COOKIE: i32 = 57;\npub const SCM_TIMESTAMPING_PKTINFO: i32 = 58;\npub const SO_PEERGROUPS: i32 = 59;\npub const SO_ZEROCOPY: i32 = 60;\npub const SO_TXTIME: i32 = 61;\npub const SCM_TXTIME: i32 = SO_TXTIME;\npub const SO_BINDTOIFINDEX: i32 = 62;\npub const SO_TIMESTAMP_NEW: i32 = 63;\npub const SO_TIMESTAMPNS_NEW: i32 = 64;\npub const SO_TIMESTAMPING_NEW: i32 = 65;\npub const SO_RCVTIMEO_NEW: i32 = 66;\npub const SO_SNDTIMEO_NEW: i32 = 67;\npub const SO_DETACH_REUSEPORT_BPF: i32 = 68;\n\npub const SOCK_STREAM: i32 = 1;\npub const SOCK_DGRAM: i32 = 2;\n\npub const IPPROTO_TCP: i32 = 6;\npub const TCP_NODELAY: i32 = 1;\npub const TCP_MAXSEG: i32 = 2;\npub const TCP_CORK: i32 = 3;\npub const TCP_KEEPIDLE: i32 = 4;\npub const TCP_KEEPINTVL: i32 = 5;\npub const TCP_KEEPCNT: i32 = 6;\npub const TCP_SYNCNT: i32 = 7;\npub const TCP_LINGER2: i32 = 8;\npub const TCP_DEFER_ACCEPT: i32 = 9;\npub const TCP_WINDOW_CLAMP: i32 = 10;\npub const TCP_INFO: i32 = 11;\npub const TCP_QUICKACK: i32 = 12;\npub const TCP_CONGESTION: i32 = 13;\npub const TCP_COOKIE_TRANSACTIONS: i32 = 15;\npub const TCP_THIN_LINEAR_TIMEOUTS: i32 = 16;\npub const TCP_THIN_DUPACK: i32 = 17;\npub const TCP_USER_TIMEOUT: i32 = 18;\npub const TCP_REPAIR: i32 = 19;\npub const TCP_REPAIR_QUEUE: i32 = 20;\npub const TCP_QUEUE_SEQ: i32 = 21;\npub const TCP_REPAIR_OPTIONS: i32 = 22;\npub const TCP_FASTOPEN: i32 = 23;\npub const TCP_TIMESTAMP: i32 = 24;\npub const TCP_FASTOPEN_CONNECT: i32 = 30;\n\npub const INADDR_LOOPBACK: u32 = 2130706433;\npub const INADDR_ANY: u32 = 0;\npub const INADDR_BROADCAST: u32 = 4294967295;\npub const INADDR_NONE: u32 = 4294967295;\n\n// EPOLL\n\npub const EPOLL_CTL_ADD: i32 = 1;\npub const EPOLL_CTL_MOD: i32 = 3;\npub const EPOLL_CTL_DEL: i32 = 2;\n\npub const EPOLLIN: u32 = 0x1;\npub const EPOLLPRI: u32 = 0x2;\npub const EPOLLOUT: u32 = 0x4;\npub const EPOLLRDNORM: u32 = 0x40;\npub const EPOLLRDBAND: u32 = 0x80;\npub const EPOLLWRNORM: u32 = 0x100;\npub const EPOLLWRBAND: u32 = 0x200;\npub const EPOLLMSG: u32 = 0x400;\npub const EPOLLERR: u32 = 0x8;\npub const EPOLLHUP: u32 = 0x10;\npub const EPOLLET: u32 = 0x80000000;\npub const EPOLLRDHUP: u32 = 0x2000;\npub const EPOLLEXCLUSIVE: u32 = 0x10000000;\npub const EPOLLONESHOT: u32 = 0x40000000;\n\n// UNSHARE\npub const CLONE_FILES: u32 = 0x400;\n\n// SET_PRIORITY\npub const PRIO_PROCESS: u32 = 0;\n"
  },
  {
    "path": "src/epoll.rs",
    "content": "/*\nFaF is a cutting edge, high performance web server\nCopyright (C) 2021  James Bates\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\nuse crate::const_config::*;\nuse crate::const_sys::*;\nuse crate::http_date;\nuse crate::http_request_path;\nuse crate::net;\nuse crate::sys_call;\nuse core::intrinsics::{likely, unlikely};\nuse core::ops::Add;\nuse core::ops::Sub;\n\n#[repr(C)]\npub union epoll_data {\n   pub ptr: isize,\n   pub fd: i32,\n   pub uint32_t: u32,\n   pub uint64_t: u64,\n}\n\n#[repr(C, packed)]\npub struct epoll_event {\n   pub events: u32,\n   pub data: epoll_data,\n}\n\n#[repr(align(64))]\nstruct AlignedHttpDate([u8; 35]);\n\n#[repr(align(64))]\nstruct AlignedEpollEvents([epoll_event; MAX_EPOLL_EVENTS_RETURNED]);\n\n#[repr(align(64))]\nstruct AlignedEpollEvent(epoll_event);\n\n#[repr(align(64))]\nstruct ReqBufAligned([u8; REQ_BUFF_SIZE * MAX_CONN]);\n\n#[repr(align(64))]\nstruct ResBufAligned([u8; RES_BUFF_SIZE]);\n\nstatic mut HTTP_DATE: AlignedHttpDate = AlignedHttpDate(http_date::get_buff_with_date());\n\nstatic mut NUM_WORKERS_INITED: usize = 0;\n\n#[inline(never)]\npub fn go(port: u16, cb: fn(*const u8, usize, *const u8, usize, *mut u8, *const u8) -> usize) {\n   // Attempt to set a higher process priority, indicated by a negative number. -20 is the highest possible\n   sys_call!(SYS_SETPRIORITY as isize, PRIO_PROCESS as isize, 0, -19);\n\n   // Initialize the DATE before launching workers\n   unsafe {\n      http_date::get_http_date(&mut HTTP_DATE.0);\n   }\n\n   let num_cpu_cores = crate::util::get_num_logical_cpus();\n   for core in 0..num_cpu_cores {\n      let thread_name = format!(\"faf{}\", core);\n      let thread_builder = std::thread::Builder::new().name(thread_name).stack_size(1024 * 1024 * 8);\n      let _ = thread_builder.spawn(move || {\n         // Unshare the file descriptor table between threads to keep the fd number itself low, otherwise all\n         // threads will share the same file descriptor table\n         sys_call!(SYS_UNSHARE as isize, CLONE_FILES as isize);\n         crate::util::set_current_thread_cpu_affinity_to(core);\n         threaded_worker(port, cb, core as i32, num_cpu_cores);\n      });\n      // sleep to ensure workers are initialized in sequence. TODO: refactor to use a semaphore instead\n      std::thread::sleep(std::time::Duration::from_millis(5));\n   }\n\n   {\n      const SLEEP_TIME: http_date::timespec = http_date::timespec { tv_sec: 1, tv_nsec: 0 };\n      loop {\n         unsafe {\n            http_date::get_http_date(&mut HTTP_DATE.0);\n         }\n         sys_call!(SYS_NANOSLEEP as isize, &SLEEP_TIME as *const _ as isize, 0);\n      }\n   }\n}\n\n#[inline(never)]\nfn threaded_worker(\n   port: u16,\n   cb: fn(*const u8, usize, *const u8, usize, *mut u8, *const u8) -> usize,\n   cpu_core: i32,\n   num_cpu_cores: usize,\n) {\n   let (listener_fd, _, _) = net::get_listener_fd(port);\n   net::setup_connection(listener_fd);\n\n   {\n      // Attach REUSEPORT_CBPF for greater locality\n      unsafe { NUM_WORKERS_INITED += 1 }\n      if cpu_core == 0 {\n         // attach after all workers are initiated. Only need to attach once and it will apply to all the workers' listener sockets.\n         const SLEEP_DURATION: core::time::Duration = std::time::Duration::from_micros(1);\n         while unsafe { NUM_WORKERS_INITED } < num_cpu_cores {\n            // With no sleep, the value in NUM_WORKERS_INITED will never be rechecked.. for some reason beyond me.\n            std::thread::sleep(SLEEP_DURATION);\n         }\n         net::attach_reuseport_cbpf(listener_fd);\n      }\n   }\n\n   let epfd = sys_call!(SYS_EPOLL_CREATE1 as isize, 0);\n\n   // Add listener fd to epoll for monitoring\n   {\n      let epoll_event_listener = AlignedEpollEvent(epoll_event { data: epoll_data { fd: listener_fd as i32 }, events: EPOLLIN });\n      sys_call!(SYS_EPOLL_CTL as isize, epfd, EPOLL_CTL_ADD as isize, listener_fd, &epoll_event_listener.0 as *const epoll_event as isize);\n   }\n\n   let epoll_events: AlignedEpollEvents = unsafe { core::mem::zeroed() };\n   let epoll_events_ptr = &epoll_events.0[0] as *const _ as isize;\n\n   let mut saved_event: AlignedEpollEvent = unsafe { core::mem::zeroed() };\n   saved_event.0.events = EPOLLIN;\n\n   let mut reqbuf: ReqBufAligned = unsafe { core::mem::zeroed() };\n\n   // Init state for tracking request buffer position across events\n   let mut reqbuf_cur_addr: [isize; MAX_CONN] = unsafe { core::mem::zeroed() };\n   {\n      let reqbuf_start_address = &mut reqbuf.0[0] as *mut _ as isize;\n      (0..reqbuf_cur_addr.len()).for_each(|i| {\n         reqbuf_cur_addr[i] = reqbuf_start_address + i as isize * REQ_BUFF_SIZE as isize;\n      });\n   }\n\n   // If we receive part of a request due to a split read, we track how many bytes were unparsable so\n   // this number of bytes can be prepended to the next time we try to parse the buffer\n   let mut reqbuf_residual: [usize; MAX_CONN] = unsafe { core::mem::zeroed() };\n\n   let mut resbuf: ResBufAligned = unsafe { core::mem::zeroed() };\n   let resbuf_start_address = &mut resbuf.0[0] as *mut _ as isize;\n\n   let mut epoll_wait_type = EPOLL_TIMEOUT_BLOCKING;\n\n   loop {\n      let num_incoming_events =\n         sys_call!(SYS_EPOLL_WAIT as isize, epfd, epoll_events_ptr, MAX_EPOLL_EVENTS_RETURNED as isize, epoll_wait_type);\n\n      if num_incoming_events <= 0 {\n         epoll_wait_type = EPOLL_TIMEOUT_BLOCKING;\n         continue;\n      }\n\n      epoll_wait_type = EPOLL_TIMEOUT_IMMEDIATE_RETURN;\n\n      for index in 0..num_incoming_events {\n         let cur_fd = unsafe { (epoll_events.0.get_unchecked(index as usize)).data.fd } as isize;\n         let req_buf_start_address = (&mut reqbuf.0[0] as *const u8 as isize).add(cur_fd * REQ_BUFF_SIZE as isize);\n         let req_buf_cur_position = unsafe { reqbuf_cur_addr.get_unchecked_mut(cur_fd as usize) };\n         let residual = unsafe { reqbuf_residual.get_unchecked_mut(cur_fd as usize) };\n\n         if cur_fd == listener_fd {\n            let incoming_fd = sys_call!(SYS_ACCEPT as isize, listener_fd, 0, 0);\n\n            if likely(incoming_fd >= 0 && incoming_fd < MAX_CONN as isize) {\n               *req_buf_cur_position = req_buf_start_address;\n               *residual = 0;\n               net::setup_connection(incoming_fd);\n               saved_event.0.data.fd = incoming_fd as i32;\n\n               sys_call!(SYS_EPOLL_CTL as isize, epfd, EPOLL_CTL_ADD as isize, incoming_fd, &saved_event.0 as *const epoll_event as isize);\n            } else {\n               net::close_connection(epfd, cur_fd);\n            }\n         } else {\n            let buffer_remaining = REQ_BUFF_SIZE as isize - (*req_buf_cur_position - req_buf_start_address);\n\n            let read = sys_call!(SYS_RECVFROM as isize, cur_fd, *req_buf_cur_position, buffer_remaining, 0, 0, 0);\n\n            if likely(read > 0) {\n               let mut request_buffer_offset = 0;\n               let mut response_buffer_filled_total = 0;\n\n               while request_buffer_offset != (read + *residual as isize) {\n                  let mut method: *const i8 = core::ptr::null_mut();\n                  let mut method_len = 0;\n                  let mut path: *const i8 = core::ptr::null_mut();\n                  let mut path_len = 0;\n\n                  let request_buffer_bytes_parsed = unsafe {\n                     http_request_path::parse_request_path_pipelined_simd(\n                        req_buf_cur_position.sub(*residual as isize).add(request_buffer_offset) as *const _,\n                        read as usize + *residual - request_buffer_offset as usize,\n                        &mut method,\n                        &mut method_len,\n                        &mut path,\n                        &mut path_len,\n                     )\n                  };\n\n                  if request_buffer_bytes_parsed > 0 {\n                     request_buffer_offset += request_buffer_bytes_parsed;\n\n                     let response_buffer_filled = unsafe {\n                        cb(\n                           method as *const u8,\n                           method_len,\n                           path as *const u8,\n                           path_len,\n                           resbuf_start_address.add(response_buffer_filled_total) as *mut _,\n                           HTTP_DATE.0.as_ptr(),\n                        )\n                     };\n\n                     response_buffer_filled_total += response_buffer_filled as isize;\n                  } else {\n                     break;\n                  }\n               }\n\n               if request_buffer_offset == 0 || response_buffer_filled_total == 0 {\n                  *req_buf_cur_position = req_buf_start_address;\n                  *residual = 0;\n                  net::close_connection(epfd, cur_fd);\n                  continue;\n               } else if request_buffer_offset == (read + *residual as isize) {\n                  *req_buf_cur_position = req_buf_start_address;\n                  *residual = 0;\n               } else {\n                  *req_buf_cur_position += read;\n                  *residual += (read - request_buffer_offset) as usize;\n               }\n\n               let wrote = sys_call!(SYS_SENDTO as isize, cur_fd, resbuf_start_address, response_buffer_filled_total, 0, 0, 0);\n\n               if likely(wrote == response_buffer_filled_total) {\n               } else if unlikely(-wrote == EAGAIN as isize || -wrote == EINTR as isize) {\n                  *req_buf_cur_position = req_buf_start_address;\n                  *residual = 0;\n                  net::close_connection(epfd, cur_fd);\n                  break;\n               } else {\n                  *req_buf_cur_position = req_buf_start_address;\n                  *residual = 0;\n                  net::close_connection(epfd, cur_fd);\n                  continue;\n               }\n            } else if unlikely(-read == EAGAIN as isize || -read == EINTR as isize) {\n            } else {\n               *req_buf_cur_position = req_buf_start_address;\n               *residual = 0;\n               net::close_connection(epfd, cur_fd);\n            }\n         }\n      }\n   }\n}\n"
  },
  {
    "path": "src/http_content_length.rs",
    "content": "// This particular file is LICENSED AS Unlicense (https://unlicense.org/)\n\n\n\n#![allow(dead_code)]\n\nconst DIGITS_LUT: [char; 200] = [\n   '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', '1', '0', '1',\n   '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0', '2', '1', '2', '2',\n   '2', '3', '2', '4', '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', '3', '0', '3', '1', '3', '2', '3', '3', '3',\n   '4', '3', '5', '3', '6', '3', '7', '3', '8', '3', '9', '4', '0', '4', '1', '4', '2', '4', '3', '4', '4', '4', '5',\n   '4', '6', '4', '7', '4', '8', '4', '9', '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5', '5', '6', '5',\n   '7', '5', '8', '5', '9', '6', '0', '6', '1', '6', '2', '6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8',\n   '6', '9', '7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6', '7', '7', '7', '8', '7', '9', '8',\n   '0', '8', '1', '8', '2', '8', '3', '8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', '9', '0', '9', '1',\n   '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7', '9', '8', '9', '9',\n];\n\n// Basically, convert u64 to ascii string representation to bytes. This is useful for Content-Length\n#[inline]\npub fn u64toa(buf: &mut [i8], value: u64) -> i64 {\n   let mut index: usize = 0;\n   if value < 100000000 {\n      let v: u32 = (value) as u32;\n      if v < 10000 {\n         let d1: u32 = (v / 100) << 1;\n         let d2: u32 = (v % 100) << 1;\n\n         if v >= 1000 {\n            buf[index] = DIGITS_LUT[d1 as usize] as i8;\n            index += 1;\n         }\n\n         if v >= 100 {\n            buf[index] = DIGITS_LUT[d1 as usize + 1] as i8;\n            index += 1;\n         }\n\n         if v >= 10 {\n            buf[index] = DIGITS_LUT[d2 as usize] as i8;\n            index += 1;\n         }\n\n         buf[index] = DIGITS_LUT[d2 as usize + 1] as i8;\n         index += 1;\n      } else {\n         let b: u32 = v / 10000;\n         let c: u32 = v % 10000;\n\n         let d1: u32 = (b / 100) << 1;\n         let d2: u32 = (b % 100) << 1;\n\n         let d3: u32 = (c / 100) << 1;\n         let d4: u32 = (c % 100) << 1;\n\n         if value >= 10000000 {\n            buf[index] = DIGITS_LUT[d1 as usize] as i8;\n            index += 1;\n         }\n\n         if value >= 1000000 {\n            buf[index] = DIGITS_LUT[d1 as usize + 1] as i8;\n            index += 1;\n         }\n\n         if value >= 100000 {\n            buf[index] = DIGITS_LUT[d2 as usize] as i8;\n            index += 1;\n         }\n\n         buf[index] = DIGITS_LUT[d2 as usize + 1] as i8;\n         index += 1;\n\n         buf[index] = DIGITS_LUT[d3 as usize] as i8;\n         index += 1;\n\n         buf[index] = DIGITS_LUT[d3 as usize + 1] as i8;\n         index += 1;\n\n         buf[index] = DIGITS_LUT[d4 as usize] as i8;\n         index += 1;\n\n         buf[index] = DIGITS_LUT[d4 as usize + 1] as i8;\n         index += 1;\n      }\n   }\n\n   index as i64\n}\n"
  },
  {
    "path": "src/http_date.rs",
    "content": "// This particular file is LICENSED AS MIT / Apache 2.0\n\n// This is a stripped and heavily optimized version of https://github.com/pyfisch/httpdate 0.3.2\n\n// faf's inspired version of this ubiquitous algorithm is the fastest in all my tests and only takes ~21ns per execution\n\n// To use this yourself, see https://crates.io/crates/faf-http-date\n\n#[inline(always)]\npub const fn get_buff_with_date() -> [u8; 35] {\n   let buf: [u8; 35] = [\n      // Writing as the following only gives us a reference: b\"Date: Thu, 01 Jan 1970 00:00:00 GMT\"\n      b'D', b'a', b't', b'e', b':', b' ', b' ', b' ', b' ', b',', b' ', b'0', b'0', b' ', b' ', b' ', b' ', b' ', b'0',\n      b'0', b'0', b'0', b' ', b'0', b'0', b':', b'0', b'0', b':', b'0', b'0', b' ', b'G', b'M', b'T',\n   ];\n\n   buf\n}\n\n#[repr(C, align(32))]\npub struct timespec {\n   pub tv_sec: i64,\n   pub tv_nsec: i64,\n}\n\nextern \"C\" {\n   // We use this function instead of a direct syscall because this function uses VDSO, which is faster\n   fn clock_gettime(clk_id: i32, tp: *mut timespec) -> i32;\n}\n\nconst CLOCK_REALTIME: i32 = 0;\n\n#[inline(always)]\npub fn get_http_date(buf: &mut [u8; 35]) {\n   let mut ts: timespec = unsafe { core::mem::MaybeUninit::uninit().assume_init() };\n   unsafe { clock_gettime(CLOCK_REALTIME, &mut ts as *mut timespec) };\n\n   let secs_since_epoch = ts.tv_sec;\n\n   const LEAPOCH: i64 = 11017;\n   const DAYS_PER_400Y: i64 = 365 * 400 + 97;\n   const DAYS_PER_100Y: i64 = 365 * 100 + 24;\n   const DAYS_PER_4Y: i64 = 365 * 4 + 1;\n\n   let days = (secs_since_epoch / 86400) - LEAPOCH;\n   let secs_of_day = secs_since_epoch % 86400;\n\n   let mut qc_cycles = days / DAYS_PER_400Y;\n   let mut remdays = days % DAYS_PER_400Y;\n\n   if remdays < 0 {\n      remdays += DAYS_PER_400Y;\n      qc_cycles -= 1;\n   }\n\n   let mut c_cycles = remdays / DAYS_PER_100Y;\n   if c_cycles == 4 {\n      c_cycles -= 1;\n   }\n   remdays -= c_cycles * DAYS_PER_100Y;\n\n   let mut q_cycles = remdays / DAYS_PER_4Y;\n   if q_cycles == 25 {\n      q_cycles -= 1;\n   }\n   remdays -= q_cycles * DAYS_PER_4Y;\n\n   let mut remyears = remdays / 365;\n   if remyears == 4 {\n      remyears -= 1;\n   }\n   remdays -= remyears * 365;\n\n   let mut year = 2000 + remyears + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles;\n\n   const MONTHS: [i64; 12] = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29];\n   let mut mon = 0;\n   for mon_len in MONTHS.iter() {\n      mon += 1;\n      if remdays < *mon_len {\n         break;\n      }\n      remdays -= *mon_len;\n   }\n   let mday = remdays + 1;\n   let mon = if mon + 2 > 12 {\n      year += 1;\n      mon - 10\n   } else {\n      mon + 2\n   };\n\n   let mut wday = (3 + days) % 7;\n   if wday <= 0 {\n      wday += 7\n   };\n\n   let sec = (secs_of_day % 60) as u8;\n   let min = ((secs_of_day % 3600) / 60) as u8;\n   let hour = (secs_of_day / 3600) as u8;\n   let day = mday as u8;\n   let mon = mon as u8;\n   let year = year as u16;\n   let wday = wday as u8;\n\n   const WDAY_LOOKUP: [&[u8; 3]; 8] = [b\"NOP\", b\"Mon\", b\"Tue\", b\"Wed\", b\"Thu\", b\"Fri\", b\"Sat\", b\"Sun\"];\n\n   const MON_LOOKUP: [&[u8; 3]; 13] =\n      [b\"NOP\", b\"Jan\", b\"Feb\", b\"Mar\", b\"Apr\", b\"May\", b\"Jun\", b\"Jul\", b\"Aug\", b\"Sep\", b\"Oct\", b\"Nov\", b\"Dec\"];\n\n   let wday = unsafe { *WDAY_LOOKUP.get_unchecked(wday as usize) };\n   let mon = unsafe { *MON_LOOKUP.get_unchecked(mon as usize) };\n\n   unsafe {\n      core::ptr::copy_nonoverlapping(wday.as_ptr(), buf.as_mut_ptr().add(6), 3);\n   }\n\n   buf[11] = b'0' + (day / 10) as u8;\n   buf[12] = b'0' + (day % 10) as u8;\n   unsafe {\n      core::ptr::copy_nonoverlapping(mon.as_ptr(), buf.as_mut_ptr().add(14), 3);\n   }\n\n   buf[18] = b'0' + (year / 1000) as u8;\n   buf[19] = b'0' + (year / 100 % 10) as u8;\n   buf[20] = b'0' + (year / 10 % 10) as u8;\n   buf[21] = b'0' + (year % 10) as u8;\n   buf[23] = b'0' + (hour / 10) as u8;\n   buf[24] = b'0' + (hour % 10) as u8;\n   buf[26] = b'0' + (min / 10) as u8;\n   buf[27] = b'0' + (min % 10) as u8;\n   buf[29] = b'0' + (sec / 10) as u8;\n   buf[30] = b'0' + (sec % 10) as u8;\n}\n"
  },
  {
    "path": "src/http_request_path.rs",
    "content": "/*\nFaF is a cutting edge, high performance web server\nCopyright (C) 2021  James Bates\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\n// This is faf's approach to parsing the HTTP request buffer, faster than all tested alternatives\n// * Extract method\n// * Extract path\n// * Return a pointer to the buffer position at the end of the request.\n//   Why? Because requests are pipelined and come in back to back\n\n// It uses SSE4.2, may be able to be improved with AVX, but this old dev laptop I'm working on doesn't support AVX\n\n// One oddity is how it matches two characters back to back (\\r\\n). Due to how _mm_cmpestri works, it doesn't actually\n// match back-to-back characters, so it looks like this is erroneous, but I don't care if the characters are back-to-back,\n// just they are present, because if they are present they 'may' be back-to-back. I test for the back-to-back-ness after the\n// characters are found, with the magic number 0x0a0d0a0d which is \\r\\n\\r\\n\n\nuse core::arch::x86_64::{\n   __m128i, _mm_cmpestri, _mm_load_si128, _mm_loadu_si128, _SIDD_CMP_EQUAL_ORDERED, _SIDD_UBYTE_OPS,\n};\nuse core::intrinsics::{likely, unlikely};\n\nconst SPACE: i8 = b' ' as i8;\n\n#[repr(align(64))]\npub struct AlignedPattern([u8; 2]);\nconst EOL_PATTERN: AlignedPattern = AlignedPattern(*b\"\\r\\n\");\n\n#[inline]\npub unsafe fn find_sequence_simd(buf_start: *const i8, buf_end: *const i8) -> *const i8 {\n   const OP: i32 = _SIDD_CMP_EQUAL_ORDERED | _SIDD_UBYTE_OPS;\n   let mut buf: *const i8 = buf_start;\n\n   // We only use two bytes as our pattern, and that is ok\n   let sixteen_byte_pattern: __m128i = _mm_load_si128(EOL_PATTERN.0.as_ptr() as *const __m128i);\n\n   loop {\n      let sixteen_bytes_from_buffer: __m128i = _mm_loadu_si128(buf as *const __m128i);\n      let found_at_byte_pos = _mm_cmpestri::<OP>(sixteen_byte_pattern, 2, sixteen_bytes_from_buffer, 16);\n\n      // If found_at_byte_pos == 16, then we didn't find a match. We found a match if less than 16\n      if found_at_byte_pos != 16 {\n         //Increment buf by found_at_byte_pos, which is the position in the 16 byte search\n         buf = buf.add(found_at_byte_pos as usize);\n         return buf;\n      }\n\n      //Increment by 15 bytes instead of 16 bytes to ensure \\r\\n is never split/overlaps between searches\n      buf = buf.add(15);\n      if buf >= buf_end {\n         break;\n      }\n   }\n\n   buf_end\n}\n\n#[inline(always)]\npub unsafe fn parse_request_path_pipelined_simd(\n   buf_start: *const i8,\n   mut len: usize,\n   method: *mut *const i8,\n   method_len: *mut usize,\n   path: *mut *const i8,\n   path_len: *mut usize,\n) -> isize {\n   let mut buf: *const i8 = buf_start;\n   let buf_end: *const i8 = buf_start.add(len);\n   let mut i = 0;\n\n   // The longest HTTP 1.1 request method is 7 characters, + 1 character for the space after\n   while likely(i < 9) {\n      if *(buf.add(i)) == SPACE {\n         *method = buf;\n         *method_len = i;\n         i += 1;\n         while unlikely(*(buf.add(i)) == SPACE) {\n            i += 1\n         }\n         break;\n      }\n\n      i += 1;\n   }\n\n   buf = buf.add(i);\n   len -= i;\n   i = 0;\n   while likely(i < len) {\n      if *(buf.add(i)) == SPACE {\n         *path = buf;\n         *path_len = i;\n         i += 1;\n         while unlikely(*(buf.add(i)) == SPACE) {\n            i += 1\n         }\n         break;\n      }\n\n      i += 1;\n   }\n\n   if unlikely(*path_len == 0 || *method_len == 0) {\n      return -1;\n   };\n\n   buf = buf.add(i);\n   while likely(buf < buf_end) {\n      buf = find_sequence_simd(buf, buf_end);\n      if *(buf as *const u32) == 0x0a0d0a0d {\n         buf = buf.add(4);\n         return (buf as usize - buf_start as usize) as isize;\n      } else {\n         buf = buf.add(2);\n      }\n   }\n\n   -2\n}\n"
  },
  {
    "path": "src/lib.rs",
    "content": "/*\nFaF is a cutting edge, high performance web server\nCopyright (C) 2021  James Bates\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\n#![allow(clippy::missing_safety_doc, clippy::uninit_assumed_init, dead_code)]\n#![feature(const_size_of_val, core_intrinsics)]\n\npub mod const_config;\npub mod const_http;\nmod const_sys;\npub mod epoll;\nmod http_content_length;\nmod http_date;\nmod http_request_path;\nmod net;\nmod syscall;\npub mod util;\n"
  },
  {
    "path": "src/net.rs",
    "content": "/*\nFaF is a cutting edge, high performance web server\nCopyright (C) 2021  James Bates\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\nuse crate::const_config::MAX_CONN;\nuse crate::const_sys::*;\nuse crate::sys_call;\n\n#[inline(always)]\npub fn htons(u: u16) -> u16 {\n   u.to_be()\n}\n\n#[inline(always)]\npub fn htonl(u: u32) -> u32 {\n   u.to_be()\n}\n\n#[repr(C)]\npub struct in_addr {\n   pub s_addr: u32,\n}\n\n#[repr(C, align(16))]\npub struct sockaddr_in {\n   pub sin_family: u16,\n   pub sin_port: u16,\n   pub sin_addr: in_addr,\n   pub sin_zero: [u8; 8],\n}\n\n#[repr(C, align(16))]\npub struct linger {\n   pub l_onoff: i32,\n   pub l_linger: i32,\n}\n\n#[repr(C)]\npub struct sock_filter {\n   pub code: u16,\n   pub jt: u8,\n   pub jf: u8,\n   pub k: u32,\n}\n\n#[repr(C)]\npub struct sock_fprog {\n   pub len: u16,\n   pub filter: *mut sock_filter,\n}\n\nconst OPTVAL: isize = 1;\nconst OPTVAL_BUSYPOLL: isize = 50;\npub const O_NONBLOCK: isize = 2048;\nconst F_SETFL: isize = 4;\n\n#[inline]\npub fn get_listener_fd(port: u16) -> (isize, sockaddr_in, u32) {\n   const _OPTVAL_TCPDEFERACCEPT_TIMEOUT: isize = 10;\n   const OPTVAL_TCPFASTOPEN_QUEUE_LEN: isize = MAX_CONN as isize;\n   const AF_INET: i32 = 2;\n\n   unsafe {\n      let fd_listener = sys_call!(SYS_SOCKET as isize, AF_INET as isize, SOCK_STREAM as isize, 0);\n      let size_of_optval = core::mem::size_of_val(&OPTVAL) as u32;\n\n      // sys_call!(\n      //    SYS_SETSOCKOPT as isize,\n      //    fd_listener,\n      //    SOL_SOCKET as isize,\n      //    SO_REUSEADDR as isize,\n      //    &OPTVAL as *const _ as _,\n      //    size_of_optval as isize\n      // );\n\n      sys_call!(\n         SYS_SETSOCKOPT as isize,\n         fd_listener,\n         SOL_SOCKET as isize,\n         SO_REUSEPORT as isize,\n         &OPTVAL as *const isize as _,\n         size_of_optval as isize\n      );\n\n      // sys_call!(\n      //    SYS_SETSOCKOPT as isize,\n      //    fd_listener,\n      //    SOL_SOCKET as isize,\n      //    SO_REUSEPORT as isize,\n      //    &OPTVAL as *const isize as _,\n      //    size_of_optval as isize\n      // );\n\n      // sys_call!(\n      //    SYS_SETSOCKOPT as isize,\n      //    fd_listener,\n      //    IPPROTO_TCP as isize,\n      //    TCP_QUICKACK as isize,\n      //    &OPTVAL as *const _ as _,\n      //    core::mem::size_of_val(&OPTVAL) as isize\n      // );\n\n      // sys_call!(\n      //    SYS_SETSOCKOPT as isize,\n      //    fd_listener,\n      //    IPPROTO_TCP as isize,\n      //    TCP_FASTOPEN as isize,\n      //    &MAX_CONN as *const _ as _,\n      //    core::mem::size_of_val(&MAX_CONN) as isize\n      // );\n\n      // Does not add much throughput, if any. Also, can hide dead connections. Not useful.\n      // sys_call!(\n      //    SYS_SETSOCKOPT as isize,\n      //    fd_listener,\n      //    IPPROTO_TCP as isize,\n      //    TCP_DEFER_ACCEPT as isize,\n      //    &_OPTVAL_TCPDEFERACCEPT_TIMEOUT as *const _ as _,\n      //    core::mem::size_of_val(&_OPTVAL_TCPDEFERACCEPT_TIMEOUT) as isize\n      // );\n\n      //https://stackoverflow.com/a/49900878\n      // sys_call!(\n      //    SYS_SETSOCKOPT as isize,\n      //    fd_listener,\n      //    SOL_SOCKET as isize,\n      //    SO_ZEROCOPY as isize,\n      //    &OPTVAL as *const _ as _,\n      //    core::mem::size_of_val(&OPTVAL) as isize\n      // );\n\n      let addr = sockaddr_in {\n         sin_family: AF_INET as u16,\n         sin_port: htons(port),\n         sin_addr: in_addr { s_addr: htonl(INADDR_ANY) },\n         sin_zero: core::mem::zeroed(),\n      };\n\n      sys_call!(SYS_BIND as isize, fd_listener, &addr as *const _ as _, core::mem::size_of_val(&addr) as isize);\n\n      sys_call!(SYS_LISTEN as isize, fd_listener, OPTVAL_TCPFASTOPEN_QUEUE_LEN);\n\n      let sock_len: u32 = core::mem::size_of::<sockaddr_in>() as u32;\n      (fd_listener, addr, sock_len)\n   }\n}\n\n#[inline]\npub fn setup_connection(fd: isize) {\n   //Doesn't help with throughput, just latency per request, and may actually reduce throughput.\n   //May be Useful for this test. I'm not entirely convinced though\n   sys_call!(\n      SYS_SETSOCKOPT as isize,\n      fd,\n      IPPROTO_TCP as isize,\n      TCP_NODELAY as isize,\n      &OPTVAL as *const _ as _,\n      core::mem::size_of_val(&OPTVAL) as isize\n   );\n\n   // Since quickack has to be set every time, it isn't worth setting\n   // sys_call!(\n   //    SYS_SETSOCKOPT as isize,\n   //    fd,\n   //    IPPROTO_TCP as isize,\n   //    TCP_QUICKACK as isize,\n   //    &OPTVAL as *const _ as _,\n   //    core::mem::size_of_val(&OPTVAL) as isize\n   // );\n\n   //https://stackoverflow.com/a/49900878\n   // sys_call!(\n   //    SYS_SETSOCKOPT as isize,\n   //    fd,\n   //    SOL_SOCKET as isize,\n   //    SO_ZEROCOPY as isize,\n   //    &OPTVAL as *const isize as _,\n   //    core::mem::size_of_val(&OPTVAL) as isize\n   // );\n\n   // Only useful when using blocking reads, not non-blocking reads as I am\n   // sys_call!(\n   //    SYS_SETSOCKOPT as isize,\n   //    fd,\n   //    SOL_SOCKET as isize,\n   //    SO_BUSY_POLL as isize,\n   //    &OPTVAL_BUSYPOLL as *const _ as _,\n   //    core::mem::size_of_val(&OPTVAL_BUSYPOLL) as isize\n   // );\n\n   sys_call!(SYS_FCNTL as isize, fd, F_SETFL, O_NONBLOCK);\n}\n\n#[inline(always)]\npub fn close_connection(epfd: isize, fd: isize) {\n   const OPTVAL_SOLINGER_TIMEOUT: linger = linger { l_onoff: 1, l_linger: 0 };\n   sys_call!(\n      SYS_SETSOCKOPT as isize,\n      fd,\n      SOL_SOCKET as isize,\n      SO_LINGER as isize,\n      &OPTVAL_SOLINGER_TIMEOUT as *const _ as _,\n      core::mem::size_of_val(&OPTVAL_SOLINGER_TIMEOUT) as isize\n   );\n\n   // Could defer deletes for performance reasons. Wouldn't cause problems as fds are reused. Not going to do this as it would\n   // require tracking fd state more granually to avoid the wasted EPOLL_CTL_ADD when new connections come in. I don't know\n   // how much of a benefit, performance-wise I'd get\n   sys_call!(SYS_EPOLL_CTL as isize, epfd, EPOLL_CTL_DEL as isize, fd, 0);\n\n   sys_call!(SYS_CLOSE as isize, fd);\n}\n\n#[inline(always)]\npub fn attach_reuseport_cbpf(fd: isize) {\n   // https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/bpf_common.h\n   // BPF_CLASS\n   const BPF_LD: u16 = 0x00;\n   const BPF_RET: u16 = 0x06;\n\n   // BPF_SIZE\n   const BPF_W: u16 = 0x00;\n\n   // BPF_MODE\n   const BPF_ABS: u16 = 0x20;\n\n   // https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/filter.h\n   // BPF_RVAL\n   const BPF_A: u16 = 0x10;\n\n   // SKF\n   const SKF_AD_OFF: i32 = -0x1000;\n   const SKF_AD_CPU: i32 = 36;\n\n   let mut code: [sock_filter; 2] = [\n      sock_filter { code: BPF_LD | BPF_W | BPF_ABS, jt: 0, jf: 0, k: (SKF_AD_OFF + SKF_AD_CPU) as u32 },\n      sock_filter { code: BPF_RET | BPF_A, jt: 0, jf: 0, k: 0 },\n   ];\n\n   let prog = sock_fprog { len: code.len() as u16, filter: code.as_mut_ptr() };\n\n   let ret = sys_call!(\n      SYS_SETSOCKOPT as isize,\n      fd,\n      SOL_SOCKET as isize,\n      SO_ATTACH_REUSEPORT_CBPF as isize,\n      &prog as *const _ as _,\n      core::mem::size_of::<sock_fprog>() as isize\n   );\n\n   //println!(\"SO_ATTACH_REUSEPORT_CBPF ret: {}, size = {}\", ret, core::mem::size_of::<sock_fprog>() as isize);\n}\n\n#[inline(always)]\npub fn debug_incoming_cpu(incoming_fd: isize, listener_fd: isize, cpu_core: i32) {\n   let incoming_cpu: i32 = -1;\n   let incoming_ret = sys_call!(\n      SYS_GETSOCKOPT as isize,\n      incoming_fd,\n      SOL_SOCKET as isize,\n      SO_INCOMING_CPU as isize,\n      &incoming_cpu as *const _ as _,\n      &core::mem::size_of_val(&incoming_cpu) as *const _ as _\n   );\n\n   let listener_cpu: i32 = -1;\n   let listener_ret = sys_call!(\n      SYS_GETSOCKOPT as isize,\n      listener_fd,\n      SOL_SOCKET as isize,\n      SO_INCOMING_CPU as isize,\n      &listener_cpu as *const _ as _,\n      &core::mem::size_of_val(&listener_cpu) as *const _ as _\n   );\n\n   let incoming_napi_id: i32 = -1;\n   let incoming_napi_id_ret = sys_call!(\n      SYS_GETSOCKOPT as isize,\n      incoming_fd,\n      SOL_SOCKET as isize,\n      SO_INCOMING_NAPI_ID as isize,\n      &incoming_napi_id as *const _ as _,\n      &core::mem::size_of_val(&incoming_napi_id) as *const _ as _\n   );\n\n   println!(\n       \"fd: {}, received request on core {} with ret value {}, should be core {}, listener_fd is on core {} with ret value {}, with napi id {} with ret {}\",\n       incoming_fd, incoming_cpu, incoming_ret, cpu_core, listener_cpu, listener_ret, incoming_napi_id, incoming_napi_id_ret\n    );\n}\n"
  },
  {
    "path": "src/syscall.rs",
    "content": "// This particular file is LICENSED AS Unlicense (https://unlicense.org/)\n\n// To use this yourself, see  https://crates.io/crates/faf-syscall\n\nuse core::arch::asm;\n\n#[macro_export(local_inner_macros)]\nmacro_rules! sys_call {\n   ($num:ident) => {\n      $crate::syscall::sys_call0($num)\n   };\n   ($num:expr, $arg1:expr) => {\n      $crate::syscall::sys_call1($num, $arg1)\n   };\n   ($num:expr, $arg1:expr, $arg2:expr) => {\n      $crate::syscall::sys_call2($num, $arg1, $arg2)\n   };\n   ($num:expr, $arg1:expr, $arg2:expr, $arg3:expr) => {\n      $crate::syscall::sys_call3($num, $arg1, $arg2, $arg3)\n   };\n   ($num:expr, $arg1:expr, $arg2:expr, $arg3:expr, $arg4:expr) => {\n      $crate::syscall::sys_call4($num, $arg1, $arg2, $arg3, $arg4)\n   };\n   ($num:expr, $arg1:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5:expr) => {\n      $crate::syscall::sys_call5($num, $arg1, $arg2, $arg3, $arg4, $arg5)\n   };\n   ($num:expr, $arg1:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5:expr, $arg6:expr) => {\n      $crate::syscall::sys_call6($num, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6)\n   };\n}\n\n#[inline(always)]\npub fn sys_call0(mut num: isize) -> isize {\n   unsafe {\n      asm!(\n         \"syscall\",\n         in(\"rax\") num,\n         out(\"rcx\") _,\n         out(\"r11\") _,\n         lateout(\"rax\") num,\n         options(nostack, preserves_flags));\n\n      num\n   }\n}\n\n#[inline(always)]\npub fn sys_call1(mut num: isize, arg1: isize) -> isize {\n   unsafe {\n      asm!(\n         \"syscall\",\n         in(\"rax\") num,\n         in(\"rdi\") arg1,\n         out(\"rcx\") _,\n         out(\"r11\") _,\n         lateout(\"rax\") num,\n         options(nostack, preserves_flags));\n      num\n   }\n}\n\n#[inline(always)]\npub fn sys_call2(mut num: isize, arg1: isize, arg2: isize) -> isize {\n   unsafe {\n      asm!(\n         \"syscall\",\n         in(\"rax\") num,\n         in(\"rdi\") arg1,\n         in(\"rsi\") arg2,\n         out(\"rcx\") _,\n         out(\"r11\") _,\n         lateout(\"rax\") num,\n         options(nostack, preserves_flags));\n      num\n   }\n}\n\n#[inline(always)]\npub fn sys_call3(mut num: isize, arg1: isize, arg2: isize, arg3: isize) -> isize {\n   unsafe {\n      asm!(\n         \"syscall\",\n         in(\"rax\") num,\n         in(\"rdi\") arg1,\n         in(\"rsi\") arg2,\n         in(\"rdx\") arg3,\n         out(\"rcx\") _,\n         out(\"r11\") _,\n         lateout(\"rax\") num,\n         options(nostack, preserves_flags));\n      num\n   }\n}\n\n#[inline(always)]\npub fn sys_call4(mut num: isize, arg1: isize, arg2: isize, arg3: isize, arg4: isize) -> isize {\n   unsafe {\n      asm!(\n         \"syscall\",\n         in(\"rax\") num,\n         in(\"rdi\") arg1,\n         in(\"rsi\") arg2,\n         in(\"rdx\") arg3,\n         in(\"r10\") arg4,\n         out(\"rcx\") _,\n         out(\"r11\") _,\n         lateout(\"rax\") num,\n         options(nostack, preserves_flags));\n      num\n   }\n}\n\n#[inline(always)]\npub fn sys_call5(mut num: isize, arg1: isize, arg2: isize, arg3: isize, arg4: isize, arg5: isize) -> isize {\n   unsafe {\n      asm!(\n         \"syscall\",\n         in(\"rax\") num,\n         in(\"rdi\") arg1,\n         in(\"rsi\") arg2,\n         in(\"rdx\") arg3,\n         in(\"r10\") arg4,\n         in(\"r8\") arg5,\n         out(\"rcx\") _,\n         out(\"r11\") _,\n         lateout(\"rax\") num,\n         options(nostack, preserves_flags));\n      num\n   }\n}\n\n#[inline(always)]\npub fn sys_call6(\n   mut num: isize,\n   arg1: isize,\n   arg2: isize,\n   arg3: isize,\n   arg4: isize,\n   arg5: isize,\n   arg6: isize,\n) -> isize {\n   unsafe {\n      asm!(\n         \"syscall\",\n         in(\"rax\") num,\n         in(\"rdi\") arg1,\n         in(\"rsi\") arg2,\n         in(\"rdx\") arg3,\n         in(\"r10\") arg4,\n         in(\"r8\") arg5,\n         in(\"r9\") arg6,\n         out(\"rcx\") _,\n         out(\"r11\") _,\n         lateout(\"rax\") num,\n         options(nostack, preserves_flags));\n      num\n   }\n}"
  },
  {
    "path": "src/util.rs",
    "content": "/*\nFaF is a cutting edge, high performance web server\nCopyright (C) 2021  James Bates\n\nThis program is free software: you can redistribute it and/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program.  If not, see <https://www.gnu.org/licenses/>.\n*/\n\nconst _SC_NPROCESSORS_ONLN: i32 = 84;\n\nextern \"C\" {\n   pub fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32;\n   fn sysconf(name: i32) -> isize;\n\n   fn sched_getaffinity(pid: i32, cpusetsize: usize, cpuset: *mut cpu_set_t) -> i32;\n   fn sched_setaffinity(pid: i32, cpusetsize: usize, cpuset: *const cpu_set_t) -> i32;\n}\n\nconst POINTER_WIDTH_IN_BITS: usize = core::mem::size_of::<usize>() * 8;\n\n// We always want a total of 1024 bits, so 16 segments on 64-bit platforms, 32 segments on 32-bit platforms\nconst CPU_SET_LEN: usize = 1024 / POINTER_WIDTH_IN_BITS;\n\n#[repr(C, align(64))]\nstruct cpu_set_t([usize; CPU_SET_LEN]);\n\n#[inline]\nfn cpu_isset(cpu_num: usize, set: &cpu_set_t) -> bool {\n   let chunk_index = cpu_num / POINTER_WIDTH_IN_BITS;\n   let chunk_offset = cpu_num % POINTER_WIDTH_IN_BITS;\n   ((1 << chunk_offset) & set.0[chunk_index]) != 0\n}\n\n#[inline]\nfn cpu_set(cpu_num: usize, set: &mut cpu_set_t) {\n   let chunk_index = cpu_num / POINTER_WIDTH_IN_BITS;\n   let chunk_offset = cpu_num % POINTER_WIDTH_IN_BITS;\n   set.0[chunk_index] |= 1 << chunk_offset;\n}\n\n// 0 indicates the current thread's PID for this API\nconst CURRENT_THREAD_CONTROL_PID: i32 = 0;\n\n#[inline]\npub fn set_current_thread_cpu_affinity_to(cpu_num: usize) {\n   let mut set: cpu_set_t = unsafe { core::mem::MaybeUninit::zeroed().assume_init() };\n   unsafe { sched_getaffinity(CURRENT_THREAD_CONTROL_PID, core::mem::size_of::<cpu_set_t>(), &mut set) };\n   if !cpu_isset(cpu_num, &set) {\n      eprintln!(\"Cannot set affinity for cpu {}\", cpu_num);\n   } else {\n      let mut set_control: cpu_set_t = unsafe { core::mem::MaybeUninit::zeroed().assume_init() };\n      cpu_set(cpu_num, &mut set_control);\n      unsafe { sched_setaffinity(0, core::mem::size_of::<cpu_set_t>(), &set_control) };\n   }\n}\n\n#[inline]\npub fn get_num_logical_cpus() -> usize {\n   let cpus = unsafe { sysconf(_SC_NPROCESSORS_ONLN) };\n   if cpus <= 0 {\n      eprintln!(\"Cannot determine the number of logical cpus with sysconf, performance will be severely impacted\");\n      1\n   } else {\n      cpus as usize\n   }\n}\n\n#[inline]\npub const unsafe fn transmute<From, To>(from: From) -> To {\n   union Transmute<From, To> {\n      from: core::mem::ManuallyDrop<From>,\n      to: core::mem::ManuallyDrop<To>,\n   }\n\n   core::mem::ManuallyDrop::into_inner(Transmute { from: core::mem::ManuallyDrop::new(from) }.to)\n}\n\n#[inline]\npub const unsafe fn concat<First, Second, Out>(a: &[u8], b: &[u8]) -> Out\nwhere\n   First: Copy,\n   Second: Copy,\n   Out: Copy,\n{\n   #[repr(C)]\n   #[derive(Copy, Clone)]\n   struct Both<A, B>(A, B);\n\n   let arr: Both<First, Second> =\n      Both(*transmute::<_, *const First>(a.as_ptr()), *transmute::<_, *const Second>(b.as_ptr()));\n\n   transmute(arr)\n}\n\n#[inline]\npub const fn const_len<T>(con: &[T]) -> usize {\n   con.len()\n}\n\n// _mm_prefetch\n#[allow(clippy::not_unsafe_ptr_arg_deref)]\n#[inline]\nfn prefetch(p: *const u8, offset: isize) {\n   unsafe { core::intrinsics::prefetch_read_data(p.offset(offset) as *const u8, 3) };\n}\n"
  }
]