Repository: errantmind/faf Branch: master Commit: 2b1456d3fb49 Files: 16 Total size: 101.7 KB Directory structure: gitextract_owuti4i4/ ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── rustfmt.toml └── src/ ├── const_config.rs ├── const_http.rs ├── const_sys.rs ├── epoll.rs ├── http_content_length.rs ├── http_date.rs ├── http_request_path.rs ├── lib.rs ├── net.rs ├── syscall.rs └── util.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ /target /docs /.vscode /prof /tests /src/scratch.rs /benches REF.md ================================================ FILE: Cargo.toml ================================================ [package] name = "faf" version = "0.6.0" authors = ["James Bates "] edition = "2021" [features] default = [] [dependencies] ================================================ FILE: LICENSE ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: README.md ================================================ # FaF FaF (Fast as Fuck) is a Linux webserver written in Rust. FaF.. - 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`) - 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. - is open to community contributions that further improve its speed or eliminate redundancy - is open to issues that clearly demonstrate a security vulnerability. - 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. ## Requirements and How-To FaF requires: - linux x86_64 - nightly Rust FaF recommends: - 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` - 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 To 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. ## Design Principles 1. 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. 2. 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. 3. 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. (in that order) ## Code Tour Just look at `epoll.rs`, everything is either there or referenced there and, even then, it is only ~200 lines of code. Aside: 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. ## Contributions Contributions 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. ## License All code is licensed under AGPL 3.0 unless an individual source file specifies otherwise. ================================================ FILE: rustfmt.toml ================================================ use_small_heuristics = "Max" tab_spaces = 3 max_width = 140 reorder_imports = true ================================================ FILE: src/const_config.rs ================================================ /* FaF is a cutting edge, high performance web server Copyright (C) 2021 James Bates This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ #[macro_export(local_inner_macros)] macro_rules! const_concat_bytes { () => { "" }; ($a:expr) => { $a }; ($a:expr, $b:expr) => {{ let bytes: &'static [u8] = unsafe { &$crate::util::concat::< [u8; $a.len()], [u8; $b.len()], [u8; $a.len() + $b.len()], >($a, $b) }; unsafe { $crate::util::transmute(bytes) } }}; ($a:expr, $($rest:expr),*) => {{ pub const TAIL: &[u8] = const_concat_bytes!($($rest),*); const_concat_bytes!($a, TAIL) }}; ($a:expr, $($rest:expr),*,) => { const_concat_bytes!($a, $($rest),*) }; } /// faf spawns one thread per core, meaning each thread can handle 1024 connections pub const MAX_CONN: usize = 1024; /// the buffer size of the request buffer. Currently set to 4096 bytes pub const REQ_BUFF_SIZE: usize = 4096; /// the buffer size of both the response buffers. Currently set to 4096 bytes pub const RES_BUFF_SIZE: usize = 4096; /// our syscall to wait for epoll events will block indefinitely when this value is used pub const EPOLL_TIMEOUT_BLOCKING: isize = -1; /// our syscall to wait for epoll events will return immediately when this value is used pub const EPOLL_TIMEOUT_IMMEDIATE_RETURN: isize = 0; /// 4096 bytes / 12 byte epoll_event size = ~340. pub const MAX_EPOLL_EVENTS_RETURNED: usize = 340; ================================================ FILE: src/const_http.rs ================================================ /* FaF is a cutting edge, high performance web server Copyright (C) 2021 James Bates This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ #![allow(dead_code)] use crate::util::const_len; pub const GET: &[u8] = b"GET"; pub const GET_LEN: usize = const_len(GET); pub const HEAD: &[u8] = b"HEAD"; pub const HEAD_LEN: usize = const_len(HEAD); pub const POST: &[u8] = b"POST"; pub const POST_LEN: usize = const_len(POST); pub const PUT: &[u8] = b"PUT"; pub const PUT_LEN: usize = const_len(PUT); pub const DELETE: &[u8] = b"DELETE"; pub const DELETE_LEN: usize = const_len(DELETE); pub const CONNECT: &[u8] = b"CONNECT"; pub const CONNECT_LEN: usize = const_len(CONNECT); pub const OPTIONS: &[u8] = b"OPTIONS"; pub const OPTIONS_LEN: usize = const_len(OPTIONS); pub const TRACE: &[u8] = b"TRACE"; pub const TRACE_LEN: usize = const_len(TRACE); pub const PATCH: &[u8] = b"PATCH"; pub const PATCH_LEN: usize = const_len(PATCH); pub const CRLF: &[u8] = b"\r\n"; pub const CRLF_LEN: usize = 2; pub const CRLFCRLF: &[u8] = b"\r\n\r\n"; pub const CRLFCRLF_LEN: usize = 4; pub const SERVER: &[u8] = b"Server: F"; pub const DATE_LEN: usize = 35; pub const HTTP_200_OK: &[u8] = b"HTTP/1.1 200 OK"; pub const HTTP_200_OK_LEN: usize = const_len(HTTP_200_OK); pub const HTTP_404_NOTFOUND: &[u8] = b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"; pub const HTTP_404_NOTFOUND_LEN: usize = const_len(HTTP_404_NOTFOUND); pub const HTTP_405_NOTALLOWED: &[u8] = b"HTTP/1.1 405 Method Not Allowed\r\nContent-Length: 0\r\n\r\n"; pub const HTTP_405_NOTALLOWED_LEN: usize = const_len(HTTP_405_NOTALLOWED); pub const HTTP_500_NOTFOUND: &[u8] = b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n"; pub const HTTP_500_NOTFOUND_LEN: usize = const_len(HTTP_500_NOTFOUND); pub 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!"; pub const EXAMPLE_HTTP_RESPONSE_LEN: usize = const_len(EXAMPLE_HTTP_RESPONSE); ================================================ FILE: src/const_sys.rs ================================================ // This particular file is LICENSED AS GPLv2 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html) #![allow(dead_code)] // Manually transformed from /usr/include/x86_64-linux-gnu/asm/unistd_64.h pub const SYS_READ: u32 = 0; pub const SYS_WRITE: u32 = 1; pub const SYS_OPEN: u32 = 2; pub const SYS_CLOSE: u32 = 3; pub const SYS_STAT: u32 = 4; pub const SYS_FSTAT: u32 = 5; pub const SYS_LSTAT: u32 = 6; pub const SYS_POLL: u32 = 7; pub const SYS_LSEEK: u32 = 8; pub const SYS_MMAP: u32 = 9; pub const SYS_MPROTECT: u32 = 10; pub const SYS_MUNMAP: u32 = 11; pub const SYS_BRK: u32 = 12; pub const SYS_RT_SIGACTION: u32 = 13; pub const SYS_RT_SIGPROCMASK: u32 = 14; pub const SYS_RT_SIGRETURN: u32 = 15; pub const SYS_IOCTL: u32 = 16; pub const SYS_PREAD64: u32 = 17; pub const SYS_PWRITE64: u32 = 18; pub const SYS_READV: u32 = 19; pub const SYS_WRITEV: u32 = 20; pub const SYS_ACCESS: u32 = 21; pub const SYS_PIPE: u32 = 22; pub const SYS_SELECT: u32 = 23; pub const SYS_SCHED_YIELD: u32 = 24; pub const SYS_MREMAP: u32 = 25; pub const SYS_MSYNC: u32 = 26; pub const SYS_MINCORE: u32 = 27; pub const SYS_MADVISE: u32 = 28; pub const SYS_SHMGET: u32 = 29; pub const SYS_SHMAT: u32 = 30; pub const SYS_SHMCTL: u32 = 31; pub const SYS_DUP: u32 = 32; pub const SYS_DUP2: u32 = 33; pub const SYS_PAUSE: u32 = 34; pub const SYS_NANOSLEEP: u32 = 35; pub const SYS_GETITIMER: u32 = 36; pub const SYS_ALARM: u32 = 37; pub const SYS_SETITIMER: u32 = 38; pub const SYS_GETPID: u32 = 39; pub const SYS_SENDFILE: u32 = 40; pub const SYS_SOCKET: u32 = 41; pub const SYS_CONNECT: u32 = 42; pub const SYS_ACCEPT: u32 = 43; pub const SYS_SENDTO: u32 = 44; pub const SYS_RECVFROM: u32 = 45; pub const SYS_SENDMSG: u32 = 46; pub const SYS_RECVMSG: u32 = 47; pub const SYS_SHUTDOWN: u32 = 48; pub const SYS_BIND: u32 = 49; pub const SYS_LISTEN: u32 = 50; pub const SYS_GETSOCKNAME: u32 = 51; pub const SYS_GETPEERNAME: u32 = 52; pub const SYS_SOCKETPAIR: u32 = 53; pub const SYS_SETSOCKOPT: u32 = 54; pub const SYS_GETSOCKOPT: u32 = 55; pub const SYS_CLONE: u32 = 56; pub const SYS_FORK: u32 = 57; pub const SYS_VFORK: u32 = 58; pub const SYS_EXECVE: u32 = 59; pub const SYS_EXIT: u32 = 60; pub const SYS_WAIT4: u32 = 61; pub const SYS_KILL: u32 = 62; pub const SYS_UNAME: u32 = 63; pub const SYS_SEMGET: u32 = 64; pub const SYS_SEMOP: u32 = 65; pub const SYS_SEMCTL: u32 = 66; pub const SYS_SHMDT: u32 = 67; pub const SYS_MSGGET: u32 = 68; pub const SYS_MSGSND: u32 = 69; pub const SYS_MSGRCV: u32 = 70; pub const SYS_MSGCTL: u32 = 71; pub const SYS_FCNTL: u32 = 72; pub const SYS_FLOCK: u32 = 73; pub const SYS_FSYNC: u32 = 74; pub const SYS_FDATASYNC: u32 = 75; pub const SYS_TRUNCATE: u32 = 76; pub const SYS_FTRUNCATE: u32 = 77; pub const SYS_GETDENTS: u32 = 78; pub const SYS_GETCWD: u32 = 79; pub const SYS_CHDIR: u32 = 80; pub const SYS_FCHDIR: u32 = 81; pub const SYS_RENAME: u32 = 82; pub const SYS_MKDIR: u32 = 83; pub const SYS_RMDIR: u32 = 84; pub const SYS_CREAT: u32 = 85; pub const SYS_LINK: u32 = 86; pub const SYS_UNLINK: u32 = 87; pub const SYS_SYMLINK: u32 = 88; pub const SYS_READLINK: u32 = 89; pub const SYS_CHMOD: u32 = 90; pub const SYS_FCHMOD: u32 = 91; pub const SYS_CHOWN: u32 = 92; pub const SYS_FCHOWN: u32 = 93; pub const SYS_LCHOWN: u32 = 94; pub const SYS_UMASK: u32 = 95; pub const SYS_GETTIMEOFDAY: u32 = 96; pub const SYS_GETRLIMIT: u32 = 97; pub const SYS_GETRUSAGE: u32 = 98; pub const SYS_SYSINFO: u32 = 99; pub const SYS_TIMES: u32 = 100; pub const SYS_PTRACE: u32 = 101; pub const SYS_GETUID: u32 = 102; pub const SYS_SYSLOG: u32 = 103; pub const SYS_GETGID: u32 = 104; pub const SYS_SETUID: u32 = 105; pub const SYS_SETGID: u32 = 106; pub const SYS_GETEUID: u32 = 107; pub const SYS_GETEGID: u32 = 108; pub const SYS_SETPGID: u32 = 109; pub const SYS_GETPPID: u32 = 110; pub const SYS_GETPGRP: u32 = 111; pub const SYS_SETSID: u32 = 112; pub const SYS_SETREUID: u32 = 113; pub const SYS_SETREGID: u32 = 114; pub const SYS_GETGROUPS: u32 = 115; pub const SYS_SETGROUPS: u32 = 116; pub const SYS_SETRESUID: u32 = 117; pub const SYS_GETRESUID: u32 = 118; pub const SYS_SETRESGID: u32 = 119; pub const SYS_GETRESGID: u32 = 120; pub const SYS_GETPGID: u32 = 121; pub const SYS_SETFSUID: u32 = 122; pub const SYS_SETFSGID: u32 = 123; pub const SYS_GETSID: u32 = 124; pub const SYS_CAPGET: u32 = 125; pub const SYS_CAPSET: u32 = 126; pub const SYS_RT_SIGPENDING: u32 = 127; pub const SYS_RT_SIGTIMEDWAIT: u32 = 128; pub const SYS_RT_SIGQUEUEINFO: u32 = 129; pub const SYS_RT_SIGSUSPEND: u32 = 130; pub const SYS_SIGALTSTACK: u32 = 131; pub const SYS_UTIME: u32 = 132; pub const SYS_MKNOD: u32 = 133; pub const SYS_USELIB: u32 = 134; pub const SYS_PERSONALITY: u32 = 135; pub const SYS_USTAT: u32 = 136; pub const SYS_STATFS: u32 = 137; pub const SYS_FSTATFS: u32 = 138; pub const SYS_SYSFS: u32 = 139; pub const SYS_GETPRIORITY: u32 = 140; pub const SYS_SETPRIORITY: u32 = 141; pub const SYS_SCHED_SETPARAM: u32 = 142; pub const SYS_SCHED_GETPARAM: u32 = 143; pub const SYS_SCHED_SETSCHEDULER: u32 = 144; pub const SYS_SCHED_GETSCHEDULER: u32 = 145; pub const SYS_SCHED_GET_PRIORITY_MAX: u32 = 146; pub const SYS_SCHED_GET_PRIORITY_MIN: u32 = 147; pub const SYS_SCHED_RR_GET_INTERVAL: u32 = 148; pub const SYS_MLOCK: u32 = 149; pub const SYS_MUNLOCK: u32 = 150; pub const SYS_MLOCKALL: u32 = 151; pub const SYS_MUNLOCKALL: u32 = 152; pub const SYS_VHANGUP: u32 = 153; pub const SYS_MODIFY_LDT: u32 = 154; pub const SYS_PIVOT_ROOT: u32 = 155; pub const SYS__SYSCTL: u32 = 156; pub const SYS_PRCTL: u32 = 157; pub const SYS_ARCH_PRCTL: u32 = 158; pub const SYS_ADJTIMEX: u32 = 159; pub const SYS_SETRLIMIT: u32 = 160; pub const SYS_CHROOT: u32 = 161; pub const SYS_SYNC: u32 = 162; pub const SYS_ACCT: u32 = 163; pub const SYS_SETTIMEOFDAY: u32 = 164; pub const SYS_MOUNT: u32 = 165; pub const SYS_UMOUNT2: u32 = 166; pub const SYS_SWAPON: u32 = 167; pub const SYS_SWAPOFF: u32 = 168; pub const SYS_REBOOT: u32 = 169; pub const SYS_SETHOSTNAME: u32 = 170; pub const SYS_SETDOMAINNAME: u32 = 171; pub const SYS_IOPL: u32 = 172; pub const SYS_IOPERM: u32 = 173; pub const SYS_CREATE_MODULE: u32 = 174; pub const SYS_INIT_MODULE: u32 = 175; pub const SYS_DELETE_MODULE: u32 = 176; pub const SYS_GET_KERNEL_SYMS: u32 = 177; pub const SYS_QUERY_MODULE: u32 = 178; pub const SYS_QUOTACTL: u32 = 179; pub const SYS_NFSSERVCTL: u32 = 180; pub const SYS_GETPMSG: u32 = 181; pub const SYS_PUTPMSG: u32 = 182; pub const SYS_AFS_SYSCALL: u32 = 183; pub const SYS_TUXCALL: u32 = 184; pub const SYS_SECURITY: u32 = 185; pub const SYS_GETTID: u32 = 186; pub const SYS_READAHEAD: u32 = 187; pub const SYS_SETXATTR: u32 = 188; pub const SYS_LSETXATTR: u32 = 189; pub const SYS_FSETXATTR: u32 = 190; pub const SYS_GETXATTR: u32 = 191; pub const SYS_LGETXATTR: u32 = 192; pub const SYS_FGETXATTR: u32 = 193; pub const SYS_LISTXATTR: u32 = 194; pub const SYS_LLISTXATTR: u32 = 195; pub const SYS_FLISTXATTR: u32 = 196; pub const SYS_REMOVEXATTR: u32 = 197; pub const SYS_LREMOVEXATTR: u32 = 198; pub const SYS_FREMOVEXATTR: u32 = 199; pub const SYS_TKILL: u32 = 200; pub const SYS_TIME: u32 = 201; pub const SYS_FUTEX: u32 = 202; pub const SYS_SCHED_SETAFFINITY: u32 = 203; pub const SYS_SCHED_GETAFFINITY: u32 = 204; pub const SYS_SET_THREAD_AREA: u32 = 205; pub const SYS_IO_SETUP: u32 = 206; pub const SYS_IO_DESTROY: u32 = 207; pub const SYS_IO_GETEVENTS: u32 = 208; pub const SYS_IO_SUBMIT: u32 = 209; pub const SYS_IO_CANCEL: u32 = 210; pub const SYS_GET_THREAD_AREA: u32 = 211; pub const SYS_LOOKUP_DCOOKIE: u32 = 212; pub const SYS_EPOLL_CREATE: u32 = 213; pub const SYS_EPOLL_CTL_OLD: u32 = 214; pub const SYS_EPOLL_WAIT_OLD: u32 = 215; pub const SYS_REMAP_FILE_PAGES: u32 = 216; pub const SYS_GETDENTS64: u32 = 217; pub const SYS_SET_TID_ADDRESS: u32 = 218; pub const SYS_RESTART_SYSCALL: u32 = 219; pub const SYS_SEMTIMEDOP: u32 = 220; pub const SYS_FADVISE64: u32 = 221; pub const SYS_TIMER_CREATE: u32 = 222; pub const SYS_TIMER_SETTIME: u32 = 223; pub const SYS_TIMER_GETTIME: u32 = 224; pub const SYS_TIMER_GETOVERRUN: u32 = 225; pub const SYS_TIMER_DELETE: u32 = 226; pub const SYS_CLOCK_SETTIME: u32 = 227; pub const SYS_CLOCK_GETTIME: u32 = 228; pub const SYS_CLOCK_GETRES: u32 = 229; pub const SYS_CLOCK_NANOSLEEP: u32 = 230; pub const SYS_EXIT_GROUP: u32 = 231; pub const SYS_EPOLL_WAIT: u32 = 232; pub const SYS_EPOLL_CTL: u32 = 233; pub const SYS_TGKILL: u32 = 234; pub const SYS_UTIMES: u32 = 235; pub const SYS_VSERVER: u32 = 236; pub const SYS_MBIND: u32 = 237; pub const SYS_SET_MEMPOLICY: u32 = 238; pub const SYS_GET_MEMPOLICY: u32 = 239; pub const SYS_MQ_OPEN: u32 = 240; pub const SYS_MQ_UNLINK: u32 = 241; pub const SYS_MQ_TIMEDSEND: u32 = 242; pub const SYS_MQ_TIMEDRECEIVE: u32 = 243; pub const SYS_MQ_NOTIFY: u32 = 244; pub const SYS_MQ_GETSETATTR: u32 = 245; pub const SYS_KEXEC_LOAD: u32 = 246; pub const SYS_WAITID: u32 = 247; pub const SYS_ADD_KEY: u32 = 248; pub const SYS_REQUEST_KEY: u32 = 249; pub const SYS_KEYCTL: u32 = 250; pub const SYS_IOPRIO_SET: u32 = 251; pub const SYS_IOPRIO_GET: u32 = 252; pub const SYS_INOTIFY_INIT: u32 = 253; pub const SYS_INOTIFY_ADD_WATCH: u32 = 254; pub const SYS_INOTIFY_RM_WATCH: u32 = 255; pub const SYS_MIGRATE_PAGES: u32 = 256; pub const SYS_OPENAT: u32 = 257; pub const SYS_MKDIRAT: u32 = 258; pub const SYS_MKNODAT: u32 = 259; pub const SYS_FCHOWNAT: u32 = 260; pub const SYS_FUTIMESAT: u32 = 261; pub const SYS_NEWFSTATAT: u32 = 262; pub const SYS_UNLINKAT: u32 = 263; pub const SYS_RENAMEAT: u32 = 264; pub const SYS_LINKAT: u32 = 265; pub const SYS_SYMLINKAT: u32 = 266; pub const SYS_READLINKAT: u32 = 267; pub const SYS_FCHMODAT: u32 = 268; pub const SYS_FACCESSAT: u32 = 269; pub const SYS_PSELECT6: u32 = 270; pub const SYS_PPOLL: u32 = 271; pub const SYS_UNSHARE: u32 = 272; pub const SYS_SET_ROBUST_LIST: u32 = 273; pub const SYS_GET_ROBUST_LIST: u32 = 274; pub const SYS_SPLICE: u32 = 275; pub const SYS_TEE: u32 = 276; pub const SYS_SYNC_FILE_RANGE: u32 = 277; pub const SYS_VMSPLICE: u32 = 278; pub const SYS_MOVE_PAGES: u32 = 279; pub const SYS_UTIMENSAT: u32 = 280; pub const SYS_EPOLL_PWAIT: u32 = 281; pub const SYS_SIGNALFD: u32 = 282; pub const SYS_TIMERFD_CREATE: u32 = 283; pub const SYS_EVENTFD: u32 = 284; pub const SYS_FALLOCATE: u32 = 285; pub const SYS_TIMERFD_SETTIME: u32 = 286; pub const SYS_TIMERFD_GETTIME: u32 = 287; pub const SYS_ACCEPT4: u32 = 288; pub const SYS_SIGNALFD4: u32 = 289; pub const SYS_EVENTFD2: u32 = 290; pub const SYS_EPOLL_CREATE1: u32 = 291; pub const SYS_DUP3: u32 = 292; pub const SYS_PIPE2: u32 = 293; pub const SYS_INOTIFY_INIT1: u32 = 294; pub const SYS_PREADV: u32 = 295; pub const SYS_PWRITEV: u32 = 296; pub const SYS_RT_TGSIGQUEUEINFO: u32 = 297; pub const SYS_PERF_EVENT_OPEN: u32 = 298; pub const SYS_RECVMMSG: u32 = 299; pub const SYS_FANOTIFY_INIT: u32 = 300; pub const SYS_FANOTIFY_MARK: u32 = 301; pub const SYS_PRLIMIT64: u32 = 302; pub const SYS_NAME_TO_HANDLE_AT: u32 = 303; pub const SYS_OPEN_BY_HANDLE_AT: u32 = 304; pub const SYS_CLOCK_ADJTIME: u32 = 305; pub const SYS_SYNCFS: u32 = 306; pub const SYS_SENDMMSG: u32 = 307; pub const SYS_SETNS: u32 = 308; pub const SYS_GETCPU: u32 = 309; pub const SYS_PROCESS_VM_READV: u32 = 310; pub const SYS_PROCESS_VM_WRITEV: u32 = 311; pub const SYS_KCMP: u32 = 312; pub const SYS_FINIT_MODULE: u32 = 313; pub const SYS_SCHED_SETATTR: u32 = 314; pub const SYS_SCHED_GETATTR: u32 = 315; pub const SYS_RENAMEAT2: u32 = 316; pub const SYS_SECCOMP: u32 = 317; pub const SYS_GETRANDOM: u32 = 318; pub const SYS_MEMFD_CREATE: u32 = 319; pub const SYS_KEXEC_FILE_LOAD: u32 = 320; pub const SYS_BPF: u32 = 321; pub const SYS_EXECVEAT: u32 = 322; pub const SYS_USERFAULTFD: u32 = 323; pub const SYS_MEMBARRIER: u32 = 324; pub const SYS_MLOCK2: u32 = 325; pub const SYS_COPY_FILE_RANGE: u32 = 326; pub const SYS_PREADV2: u32 = 327; pub const SYS_PWRITEV2: u32 = 328; pub const SYS_PKEY_MPROTECT: u32 = 329; pub const SYS_PKEY_ALLOC: u32 = 330; pub const SYS_PKEY_FREE: u32 = 331; pub const SYS_STATX: u32 = 332; pub const SYS_IO_PGETEVENTS: u32 = 333; pub const SYS_RSEQ: u32 = 334; pub const SYS_PIDFD_SEND_SIGNAL: u32 = 424; pub const SYS_IO_URING_SETUP: u32 = 425; pub const SYS_IO_URING_ENTER: u32 = 426; pub const SYS_IO_URING_REGISTER: u32 = 427; pub const SYS_OPEN_TREE: u32 = 428; pub const SYS_MOVE_MOUNT: u32 = 429; pub const SYS_FSOPEN: u32 = 430; pub const SYS_FSCONFIG: u32 = 431; pub const SYS_FSMOUNT: u32 = 432; pub const SYS_FSPICK: u32 = 433; pub const SYS_PIDFD_OPEN: u32 = 434; pub const SYS_CLONE3: u32 = 435; pub const SYS_OPENAT2: u32 = 437; pub const SYS_PIDFD_GETFD: u32 = 438; pub const SYS_FACCESSAT2: u32 = 439; // Manually transformed from /usr/include/asm-generic/errno-base.h // and /usr/include/asm-generic/errno.h pub const EPERM: u32 = 1; pub const ENOENT: u32 = 2; pub const ESRCH: u32 = 3; pub const EINTR: u32 = 4; pub const EIO: u32 = 5; pub const ENXIO: u32 = 6; pub const E2BIG: u32 = 7; pub const ENOEXEC: u32 = 8; pub const EBADF: u32 = 9; pub const ECHILD: u32 = 10; pub const EAGAIN: u32 = 11; pub const ENOMEM: u32 = 12; pub const EACCES: u32 = 13; pub const EFAULT: u32 = 14; pub const ENOTBLK: u32 = 15; pub const EBUSY: u32 = 16; pub const EEXIST: u32 = 17; pub const EXDEV: u32 = 18; pub const ENODEV: u32 = 19; pub const ENOTDIR: u32 = 20; pub const EISDIR: u32 = 21; pub const EINVAL: u32 = 22; pub const ENFILE: u32 = 23; pub const EMFILE: u32 = 24; pub const ENOTTY: u32 = 25; pub const ETXTBSY: u32 = 26; pub const EFBIG: u32 = 27; pub const ENOSPC: u32 = 28; pub const ESPIPE: u32 = 29; pub const EROFS: u32 = 30; pub const EMLINK: u32 = 31; pub const EPIPE: u32 = 32; pub const EDOM: u32 = 33; pub const ERANGE: u32 = 34; pub const EDEADLK: u32 = 35; pub const ENAMETOOLONG: u32 = 36; pub const ENOLCK: u32 = 37; pub const ENOSYS: u32 = 38; pub const ENOTEMPTY: u32 = 39; pub const ELOOP: u32 = 40; pub const EWOULDBLOCK: u32 = 11; // EAGAIN pub const ENOMSG: u32 = 42; pub const EIDRM: u32 = 43; pub const ECHRNG: u32 = 44; pub const EL2NSYNC: u32 = 45; pub const EL3HLT: u32 = 46; pub const EL3RST: u32 = 47; pub const ELNRNG: u32 = 48; pub const EUNATCH: u32 = 49; pub const ENOCSI: u32 = 50; pub const EL2HLT: u32 = 51; pub const EBADE: u32 = 52; pub const EBADR: u32 = 53; pub const EXFULL: u32 = 54; pub const ENOANO: u32 = 55; pub const EBADRQC: u32 = 56; pub const EBADSLT: u32 = 57; pub const EDEADLOCK: u32 = 35; // EDEADLK pub const EBFONT: u32 = 59; pub const ENOSTR: u32 = 60; pub const ENODATA: u32 = 61; pub const ETIME: u32 = 62; pub const ENOSR: u32 = 63; pub const ENONET: u32 = 64; pub const ENOPKG: u32 = 65; pub const EREMOTE: u32 = 66; pub const ENOLINK: u32 = 67; pub const EADV: u32 = 68; pub const ESRMNT: u32 = 69; pub const ECOMM: u32 = 70; pub const EPROTO: u32 = 71; pub const EMULTIHOP: u32 = 72; pub const EDOTDOT: u32 = 73; pub const EBADMSG: u32 = 74; pub const EOVERFLOW: u32 = 75; pub const ENOTUNIQ: u32 = 76; pub const EBADFD: u32 = 77; pub const EREMCHG: u32 = 78; pub const ELIBACC: u32 = 79; pub const ELIBBAD: u32 = 80; pub const ELIBSCN: u32 = 81; pub const ELIBMAX: u32 = 82; pub const ELIBEXEC: u32 = 83; pub const EILSEQ: u32 = 84; pub const ERESTART: u32 = 85; pub const ESTRPIPE: u32 = 86; pub const EUSERS: u32 = 87; pub const ENOTSOCK: u32 = 88; pub const EDESTADDRREQ: u32 = 89; pub const EMSGSIZE: u32 = 90; pub const EPROTOTYPE: u32 = 91; pub const ENOPROTOOPT: u32 = 92; pub const EPROTONOSUPPORT: u32 = 93; pub const ESOCKTNOSUPPORT: u32 = 94; pub const EOPNOTSUPP: u32 = 95; pub const EPFNOSUPPORT: u32 = 96; pub const EAFNOSUPPORT: u32 = 97; pub const EADDRINUSE: u32 = 98; pub const EADDRNOTAVAIL: u32 = 99; pub const ENETDOWN: u32 = 100; pub const ENETUNREACH: u32 = 101; pub const ENETRESET: u32 = 102; pub const ECONNABORTED: u32 = 103; pub const ECONNRESET: u32 = 104; pub const ENOBUFS: u32 = 105; pub const EISCONN: u32 = 106; pub const ENOTCONN: u32 = 107; pub const ESHUTDOWN: u32 = 108; pub const ETOOMANYREFS: u32 = 109; pub const ETIMEDOUT: u32 = 110; pub const ECONNREFUSED: u32 = 111; pub const EHOSTDOWN: u32 = 112; pub const EHOSTUNREACH: u32 = 113; pub const EALREADY: u32 = 114; pub const EINPROGRESS: u32 = 115; pub const ESTALE: u32 = 116; pub const EUCLEAN: u32 = 117; pub const ENOTNAM: u32 = 118; pub const ENAVAIL: u32 = 119; pub const EISNAM: u32 = 120; pub const EREMOTEIO: u32 = 121; pub const EDQUOT: u32 = 122; pub const ENOMEDIUM: u32 = 123; pub const EMEDIUMTYPE: u32 = 124; pub const ECANCELED: u32 = 125; pub const ENOKEY: u32 = 126; pub const EKEYEXPIRED: u32 = 127; pub const EKEYREVOKED: u32 = 128; pub const EKEYREJECTED: u32 = 129; pub const EOWNERDEAD: u32 = 130; pub const ENOTRECOVERABLE: u32 = 131; pub const ERFKILL: u32 = 132; pub const EHWPOISON: u32 = 133; // pub const O_DIRECT: i32 = 0x4000; pub const O_DIRECTORY: i32 = 0x10000; pub const O_NOFOLLOW: i32 = 0x20000; pub const O_APPEND: i32 = 1024; pub const O_CREAT: i32 = 64; pub const O_EXCL: i32 = 128; pub const O_NOCTTY: i32 = 256; pub const O_NONBLOCK: i32 = 2048; pub const O_SYNC: i32 = 1052672; pub const O_RSYNC: i32 = 1052672; pub const O_DSYNC: i32 = 4096; pub const O_FSYNC: i32 = 0x101000; pub const O_NOATIME: i32 = 0o1000000; pub const O_PATH: i32 = 0o10000000; pub const O_TMPFILE: i32 = 0o20000000 | O_DIRECTORY; pub const SOL_SOCKET: i32 = 1; pub const SO_REUSEADDR: i32 = 2; pub const SO_TYPE: i32 = 3; pub const SO_ERROR: i32 = 4; pub const SO_DONTROUTE: i32 = 5; pub const SO_BROADCAST: i32 = 6; pub const SO_SNDBUF: i32 = 7; pub const SO_RCVBUF: i32 = 8; pub const SO_SNDBUFFORCE: i32 = 32; pub const SO_RCVBUFFORCE: i32 = 33; pub const SO_KEEPALIVE: i32 = 9; pub const SO_OOBINLINE: i32 = 10; pub const SO_NO_CHECK: i32 = 11; pub const SO_PRIORITY: i32 = 12; pub const SO_LINGER: i32 = 13; pub const SO_BSDCOMPAT: i32 = 14; pub const SO_REUSEPORT: i32 = 15; pub const SO_PASSCRED: i32 = 16; pub const SO_PEERCRED: i32 = 17; pub const SO_RCVLOWAT: i32 = 18; pub const SO_SNDLOWAT: i32 = 19; pub const SO_RCVTIMEO: i32 = 20; pub const SO_SNDTIMEO: i32 = 21; pub const SO_SECURITY_AUTHENTICATION: i32 = 22; pub const SO_SECURITY_ENCRYPTION_TRANSPORT: i32 = 23; pub const SO_SECURITY_ENCRYPTION_NETWORK: i32 = 24; pub const SO_BINDTODEVICE: i32 = 25; pub const SO_ATTACH_FILTER: i32 = 26; pub const SO_DETACH_FILTER: i32 = 27; pub const SO_GET_FILTER: i32 = SO_ATTACH_FILTER; pub const SO_PEERNAME: i32 = 28; pub const SO_TIMESTAMP: i32 = 29; pub const SO_ACCEPTCONN: i32 = 30; pub const SO_PEERSEC: i32 = 31; pub const SO_PASSSEC: i32 = 34; pub const SO_TIMESTAMPNS: i32 = 35; pub const SCM_TIMESTAMPNS: i32 = SO_TIMESTAMPNS; pub const SO_MARK: i32 = 36; pub const SO_PROTOCOL: i32 = 38; pub const SO_DOMAIN: i32 = 39; pub const SO_RXQ_OVFL: i32 = 40; pub const SO_WIFI_STATUS: i32 = 41; pub const SCM_WIFI_STATUS: i32 = SO_WIFI_STATUS; pub const SO_PEEK_OFF: i32 = 42; pub const SO_NOFCS: i32 = 43; pub const SO_LOCK_FILTER: i32 = 44; pub const SO_SELECT_ERR_QUEUE: i32 = 45; pub const SO_BUSY_POLL: i32 = 46; pub const SO_MAX_PACING_RATE: i32 = 47; pub const SO_BPF_EXTENSIONS: i32 = 48; pub const SO_INCOMING_CPU: i32 = 49; pub const SO_ATTACH_BPF: i32 = 50; pub const SO_DETACH_BPF: i32 = SO_DETACH_FILTER; pub const SO_ATTACH_REUSEPORT_CBPF: i32 = 51; pub const SO_ATTACH_REUSEPORT_EBPF: i32 = 52; pub const SO_CNX_ADVICE: i32 = 53; pub const SCM_TIMESTAMPING_OPT_STATS: i32 = 54; pub const SO_MEMINFO: i32 = 55; pub const SO_INCOMING_NAPI_ID: i32 = 56; pub const SO_COOKIE: i32 = 57; pub const SCM_TIMESTAMPING_PKTINFO: i32 = 58; pub const SO_PEERGROUPS: i32 = 59; pub const SO_ZEROCOPY: i32 = 60; pub const SO_TXTIME: i32 = 61; pub const SCM_TXTIME: i32 = SO_TXTIME; pub const SO_BINDTOIFINDEX: i32 = 62; pub const SO_TIMESTAMP_NEW: i32 = 63; pub const SO_TIMESTAMPNS_NEW: i32 = 64; pub const SO_TIMESTAMPING_NEW: i32 = 65; pub const SO_RCVTIMEO_NEW: i32 = 66; pub const SO_SNDTIMEO_NEW: i32 = 67; pub const SO_DETACH_REUSEPORT_BPF: i32 = 68; pub const SOCK_STREAM: i32 = 1; pub const SOCK_DGRAM: i32 = 2; pub const IPPROTO_TCP: i32 = 6; pub const TCP_NODELAY: i32 = 1; pub const TCP_MAXSEG: i32 = 2; pub const TCP_CORK: i32 = 3; pub const TCP_KEEPIDLE: i32 = 4; pub const TCP_KEEPINTVL: i32 = 5; pub const TCP_KEEPCNT: i32 = 6; pub const TCP_SYNCNT: i32 = 7; pub const TCP_LINGER2: i32 = 8; pub const TCP_DEFER_ACCEPT: i32 = 9; pub const TCP_WINDOW_CLAMP: i32 = 10; pub const TCP_INFO: i32 = 11; pub const TCP_QUICKACK: i32 = 12; pub const TCP_CONGESTION: i32 = 13; pub const TCP_COOKIE_TRANSACTIONS: i32 = 15; pub const TCP_THIN_LINEAR_TIMEOUTS: i32 = 16; pub const TCP_THIN_DUPACK: i32 = 17; pub const TCP_USER_TIMEOUT: i32 = 18; pub const TCP_REPAIR: i32 = 19; pub const TCP_REPAIR_QUEUE: i32 = 20; pub const TCP_QUEUE_SEQ: i32 = 21; pub const TCP_REPAIR_OPTIONS: i32 = 22; pub const TCP_FASTOPEN: i32 = 23; pub const TCP_TIMESTAMP: i32 = 24; pub const TCP_FASTOPEN_CONNECT: i32 = 30; pub const INADDR_LOOPBACK: u32 = 2130706433; pub const INADDR_ANY: u32 = 0; pub const INADDR_BROADCAST: u32 = 4294967295; pub const INADDR_NONE: u32 = 4294967295; // EPOLL pub const EPOLL_CTL_ADD: i32 = 1; pub const EPOLL_CTL_MOD: i32 = 3; pub const EPOLL_CTL_DEL: i32 = 2; pub const EPOLLIN: u32 = 0x1; pub const EPOLLPRI: u32 = 0x2; pub const EPOLLOUT: u32 = 0x4; pub const EPOLLRDNORM: u32 = 0x40; pub const EPOLLRDBAND: u32 = 0x80; pub const EPOLLWRNORM: u32 = 0x100; pub const EPOLLWRBAND: u32 = 0x200; pub const EPOLLMSG: u32 = 0x400; pub const EPOLLERR: u32 = 0x8; pub const EPOLLHUP: u32 = 0x10; pub const EPOLLET: u32 = 0x80000000; pub const EPOLLRDHUP: u32 = 0x2000; pub const EPOLLEXCLUSIVE: u32 = 0x10000000; pub const EPOLLONESHOT: u32 = 0x40000000; // UNSHARE pub const CLONE_FILES: u32 = 0x400; // SET_PRIORITY pub const PRIO_PROCESS: u32 = 0; ================================================ FILE: src/epoll.rs ================================================ /* FaF is a cutting edge, high performance web server Copyright (C) 2021 James Bates This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ use crate::const_config::*; use crate::const_sys::*; use crate::http_date; use crate::http_request_path; use crate::net; use crate::sys_call; use core::intrinsics::{likely, unlikely}; use core::ops::Add; use core::ops::Sub; #[repr(C)] pub union epoll_data { pub ptr: isize, pub fd: i32, pub uint32_t: u32, pub uint64_t: u64, } #[repr(C, packed)] pub struct epoll_event { pub events: u32, pub data: epoll_data, } #[repr(align(64))] struct AlignedHttpDate([u8; 35]); #[repr(align(64))] struct AlignedEpollEvents([epoll_event; MAX_EPOLL_EVENTS_RETURNED]); #[repr(align(64))] struct AlignedEpollEvent(epoll_event); #[repr(align(64))] struct ReqBufAligned([u8; REQ_BUFF_SIZE * MAX_CONN]); #[repr(align(64))] struct ResBufAligned([u8; RES_BUFF_SIZE]); static mut HTTP_DATE: AlignedHttpDate = AlignedHttpDate(http_date::get_buff_with_date()); static mut NUM_WORKERS_INITED: usize = 0; #[inline(never)] pub fn go(port: u16, cb: fn(*const u8, usize, *const u8, usize, *mut u8, *const u8) -> usize) { // Attempt to set a higher process priority, indicated by a negative number. -20 is the highest possible sys_call!(SYS_SETPRIORITY as isize, PRIO_PROCESS as isize, 0, -19); // Initialize the DATE before launching workers unsafe { http_date::get_http_date(&mut HTTP_DATE.0); } let num_cpu_cores = crate::util::get_num_logical_cpus(); for core in 0..num_cpu_cores { let thread_name = format!("faf{}", core); let thread_builder = std::thread::Builder::new().name(thread_name).stack_size(1024 * 1024 * 8); let _ = thread_builder.spawn(move || { // Unshare the file descriptor table between threads to keep the fd number itself low, otherwise all // threads will share the same file descriptor table sys_call!(SYS_UNSHARE as isize, CLONE_FILES as isize); crate::util::set_current_thread_cpu_affinity_to(core); threaded_worker(port, cb, core as i32, num_cpu_cores); }); // sleep to ensure workers are initialized in sequence. TODO: refactor to use a semaphore instead std::thread::sleep(std::time::Duration::from_millis(5)); } { const SLEEP_TIME: http_date::timespec = http_date::timespec { tv_sec: 1, tv_nsec: 0 }; loop { unsafe { http_date::get_http_date(&mut HTTP_DATE.0); } sys_call!(SYS_NANOSLEEP as isize, &SLEEP_TIME as *const _ as isize, 0); } } } #[inline(never)] fn threaded_worker( port: u16, cb: fn(*const u8, usize, *const u8, usize, *mut u8, *const u8) -> usize, cpu_core: i32, num_cpu_cores: usize, ) { let (listener_fd, _, _) = net::get_listener_fd(port); net::setup_connection(listener_fd); { // Attach REUSEPORT_CBPF for greater locality unsafe { NUM_WORKERS_INITED += 1 } if cpu_core == 0 { // attach after all workers are initiated. Only need to attach once and it will apply to all the workers' listener sockets. const SLEEP_DURATION: core::time::Duration = std::time::Duration::from_micros(1); while unsafe { NUM_WORKERS_INITED } < num_cpu_cores { // With no sleep, the value in NUM_WORKERS_INITED will never be rechecked.. for some reason beyond me. std::thread::sleep(SLEEP_DURATION); } net::attach_reuseport_cbpf(listener_fd); } } let epfd = sys_call!(SYS_EPOLL_CREATE1 as isize, 0); // Add listener fd to epoll for monitoring { let epoll_event_listener = AlignedEpollEvent(epoll_event { data: epoll_data { fd: listener_fd as i32 }, events: EPOLLIN }); 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); } let epoll_events: AlignedEpollEvents = unsafe { core::mem::zeroed() }; let epoll_events_ptr = &epoll_events.0[0] as *const _ as isize; let mut saved_event: AlignedEpollEvent = unsafe { core::mem::zeroed() }; saved_event.0.events = EPOLLIN; let mut reqbuf: ReqBufAligned = unsafe { core::mem::zeroed() }; // Init state for tracking request buffer position across events let mut reqbuf_cur_addr: [isize; MAX_CONN] = unsafe { core::mem::zeroed() }; { let reqbuf_start_address = &mut reqbuf.0[0] as *mut _ as isize; (0..reqbuf_cur_addr.len()).for_each(|i| { reqbuf_cur_addr[i] = reqbuf_start_address + i as isize * REQ_BUFF_SIZE as isize; }); } // If we receive part of a request due to a split read, we track how many bytes were unparsable so // this number of bytes can be prepended to the next time we try to parse the buffer let mut reqbuf_residual: [usize; MAX_CONN] = unsafe { core::mem::zeroed() }; let mut resbuf: ResBufAligned = unsafe { core::mem::zeroed() }; let resbuf_start_address = &mut resbuf.0[0] as *mut _ as isize; let mut epoll_wait_type = EPOLL_TIMEOUT_BLOCKING; loop { let num_incoming_events = sys_call!(SYS_EPOLL_WAIT as isize, epfd, epoll_events_ptr, MAX_EPOLL_EVENTS_RETURNED as isize, epoll_wait_type); if num_incoming_events <= 0 { epoll_wait_type = EPOLL_TIMEOUT_BLOCKING; continue; } epoll_wait_type = EPOLL_TIMEOUT_IMMEDIATE_RETURN; for index in 0..num_incoming_events { let cur_fd = unsafe { (epoll_events.0.get_unchecked(index as usize)).data.fd } as isize; let req_buf_start_address = (&mut reqbuf.0[0] as *const u8 as isize).add(cur_fd * REQ_BUFF_SIZE as isize); let req_buf_cur_position = unsafe { reqbuf_cur_addr.get_unchecked_mut(cur_fd as usize) }; let residual = unsafe { reqbuf_residual.get_unchecked_mut(cur_fd as usize) }; if cur_fd == listener_fd { let incoming_fd = sys_call!(SYS_ACCEPT as isize, listener_fd, 0, 0); if likely(incoming_fd >= 0 && incoming_fd < MAX_CONN as isize) { *req_buf_cur_position = req_buf_start_address; *residual = 0; net::setup_connection(incoming_fd); saved_event.0.data.fd = incoming_fd as i32; sys_call!(SYS_EPOLL_CTL as isize, epfd, EPOLL_CTL_ADD as isize, incoming_fd, &saved_event.0 as *const epoll_event as isize); } else { net::close_connection(epfd, cur_fd); } } else { let buffer_remaining = REQ_BUFF_SIZE as isize - (*req_buf_cur_position - req_buf_start_address); let read = sys_call!(SYS_RECVFROM as isize, cur_fd, *req_buf_cur_position, buffer_remaining, 0, 0, 0); if likely(read > 0) { let mut request_buffer_offset = 0; let mut response_buffer_filled_total = 0; while request_buffer_offset != (read + *residual as isize) { let mut method: *const i8 = core::ptr::null_mut(); let mut method_len = 0; let mut path: *const i8 = core::ptr::null_mut(); let mut path_len = 0; let request_buffer_bytes_parsed = unsafe { http_request_path::parse_request_path_pipelined_simd( req_buf_cur_position.sub(*residual as isize).add(request_buffer_offset) as *const _, read as usize + *residual - request_buffer_offset as usize, &mut method, &mut method_len, &mut path, &mut path_len, ) }; if request_buffer_bytes_parsed > 0 { request_buffer_offset += request_buffer_bytes_parsed; let response_buffer_filled = unsafe { cb( method as *const u8, method_len, path as *const u8, path_len, resbuf_start_address.add(response_buffer_filled_total) as *mut _, HTTP_DATE.0.as_ptr(), ) }; response_buffer_filled_total += response_buffer_filled as isize; } else { break; } } if request_buffer_offset == 0 || response_buffer_filled_total == 0 { *req_buf_cur_position = req_buf_start_address; *residual = 0; net::close_connection(epfd, cur_fd); continue; } else if request_buffer_offset == (read + *residual as isize) { *req_buf_cur_position = req_buf_start_address; *residual = 0; } else { *req_buf_cur_position += read; *residual += (read - request_buffer_offset) as usize; } let wrote = sys_call!(SYS_SENDTO as isize, cur_fd, resbuf_start_address, response_buffer_filled_total, 0, 0, 0); if likely(wrote == response_buffer_filled_total) { } else if unlikely(-wrote == EAGAIN as isize || -wrote == EINTR as isize) { *req_buf_cur_position = req_buf_start_address; *residual = 0; net::close_connection(epfd, cur_fd); break; } else { *req_buf_cur_position = req_buf_start_address; *residual = 0; net::close_connection(epfd, cur_fd); continue; } } else if unlikely(-read == EAGAIN as isize || -read == EINTR as isize) { } else { *req_buf_cur_position = req_buf_start_address; *residual = 0; net::close_connection(epfd, cur_fd); } } } } } ================================================ FILE: src/http_content_length.rs ================================================ // This particular file is LICENSED AS Unlicense (https://unlicense.org/) #![allow(dead_code)] const DIGITS_LUT: [char; 200] = [ '0', '0', '0', '1', '0', '2', '0', '3', '0', '4', '0', '5', '0', '6', '0', '7', '0', '8', '0', '9', '1', '0', '1', '1', '1', '2', '1', '3', '1', '4', '1', '5', '1', '6', '1', '7', '1', '8', '1', '9', '2', '0', '2', '1', '2', '2', '2', '3', '2', '4', '2', '5', '2', '6', '2', '7', '2', '8', '2', '9', '3', '0', '3', '1', '3', '2', '3', '3', '3', '4', '3', '5', '3', '6', '3', '7', '3', '8', '3', '9', '4', '0', '4', '1', '4', '2', '4', '3', '4', '4', '4', '5', '4', '6', '4', '7', '4', '8', '4', '9', '5', '0', '5', '1', '5', '2', '5', '3', '5', '4', '5', '5', '5', '6', '5', '7', '5', '8', '5', '9', '6', '0', '6', '1', '6', '2', '6', '3', '6', '4', '6', '5', '6', '6', '6', '7', '6', '8', '6', '9', '7', '0', '7', '1', '7', '2', '7', '3', '7', '4', '7', '5', '7', '6', '7', '7', '7', '8', '7', '9', '8', '0', '8', '1', '8', '2', '8', '3', '8', '4', '8', '5', '8', '6', '8', '7', '8', '8', '8', '9', '9', '0', '9', '1', '9', '2', '9', '3', '9', '4', '9', '5', '9', '6', '9', '7', '9', '8', '9', '9', ]; // Basically, convert u64 to ascii string representation to bytes. This is useful for Content-Length #[inline] pub fn u64toa(buf: &mut [i8], value: u64) -> i64 { let mut index: usize = 0; if value < 100000000 { let v: u32 = (value) as u32; if v < 10000 { let d1: u32 = (v / 100) << 1; let d2: u32 = (v % 100) << 1; if v >= 1000 { buf[index] = DIGITS_LUT[d1 as usize] as i8; index += 1; } if v >= 100 { buf[index] = DIGITS_LUT[d1 as usize + 1] as i8; index += 1; } if v >= 10 { buf[index] = DIGITS_LUT[d2 as usize] as i8; index += 1; } buf[index] = DIGITS_LUT[d2 as usize + 1] as i8; index += 1; } else { let b: u32 = v / 10000; let c: u32 = v % 10000; let d1: u32 = (b / 100) << 1; let d2: u32 = (b % 100) << 1; let d3: u32 = (c / 100) << 1; let d4: u32 = (c % 100) << 1; if value >= 10000000 { buf[index] = DIGITS_LUT[d1 as usize] as i8; index += 1; } if value >= 1000000 { buf[index] = DIGITS_LUT[d1 as usize + 1] as i8; index += 1; } if value >= 100000 { buf[index] = DIGITS_LUT[d2 as usize] as i8; index += 1; } buf[index] = DIGITS_LUT[d2 as usize + 1] as i8; index += 1; buf[index] = DIGITS_LUT[d3 as usize] as i8; index += 1; buf[index] = DIGITS_LUT[d3 as usize + 1] as i8; index += 1; buf[index] = DIGITS_LUT[d4 as usize] as i8; index += 1; buf[index] = DIGITS_LUT[d4 as usize + 1] as i8; index += 1; } } index as i64 } ================================================ FILE: src/http_date.rs ================================================ // This particular file is LICENSED AS MIT / Apache 2.0 // This is a stripped and heavily optimized version of https://github.com/pyfisch/httpdate 0.3.2 // faf's inspired version of this ubiquitous algorithm is the fastest in all my tests and only takes ~21ns per execution // To use this yourself, see https://crates.io/crates/faf-http-date #[inline(always)] pub const fn get_buff_with_date() -> [u8; 35] { let buf: [u8; 35] = [ // Writing as the following only gives us a reference: b"Date: Thu, 01 Jan 1970 00:00:00 GMT" 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', 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', ]; buf } #[repr(C, align(32))] pub struct timespec { pub tv_sec: i64, pub tv_nsec: i64, } extern "C" { // We use this function instead of a direct syscall because this function uses VDSO, which is faster fn clock_gettime(clk_id: i32, tp: *mut timespec) -> i32; } const CLOCK_REALTIME: i32 = 0; #[inline(always)] pub fn get_http_date(buf: &mut [u8; 35]) { let mut ts: timespec = unsafe { core::mem::MaybeUninit::uninit().assume_init() }; unsafe { clock_gettime(CLOCK_REALTIME, &mut ts as *mut timespec) }; let secs_since_epoch = ts.tv_sec; const LEAPOCH: i64 = 11017; const DAYS_PER_400Y: i64 = 365 * 400 + 97; const DAYS_PER_100Y: i64 = 365 * 100 + 24; const DAYS_PER_4Y: i64 = 365 * 4 + 1; let days = (secs_since_epoch / 86400) - LEAPOCH; let secs_of_day = secs_since_epoch % 86400; let mut qc_cycles = days / DAYS_PER_400Y; let mut remdays = days % DAYS_PER_400Y; if remdays < 0 { remdays += DAYS_PER_400Y; qc_cycles -= 1; } let mut c_cycles = remdays / DAYS_PER_100Y; if c_cycles == 4 { c_cycles -= 1; } remdays -= c_cycles * DAYS_PER_100Y; let mut q_cycles = remdays / DAYS_PER_4Y; if q_cycles == 25 { q_cycles -= 1; } remdays -= q_cycles * DAYS_PER_4Y; let mut remyears = remdays / 365; if remyears == 4 { remyears -= 1; } remdays -= remyears * 365; let mut year = 2000 + remyears + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles; const MONTHS: [i64; 12] = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29]; let mut mon = 0; for mon_len in MONTHS.iter() { mon += 1; if remdays < *mon_len { break; } remdays -= *mon_len; } let mday = remdays + 1; let mon = if mon + 2 > 12 { year += 1; mon - 10 } else { mon + 2 }; let mut wday = (3 + days) % 7; if wday <= 0 { wday += 7 }; let sec = (secs_of_day % 60) as u8; let min = ((secs_of_day % 3600) / 60) as u8; let hour = (secs_of_day / 3600) as u8; let day = mday as u8; let mon = mon as u8; let year = year as u16; let wday = wday as u8; const WDAY_LOOKUP: [&[u8; 3]; 8] = [b"NOP", b"Mon", b"Tue", b"Wed", b"Thu", b"Fri", b"Sat", b"Sun"]; const MON_LOOKUP: [&[u8; 3]; 13] = [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"]; let wday = unsafe { *WDAY_LOOKUP.get_unchecked(wday as usize) }; let mon = unsafe { *MON_LOOKUP.get_unchecked(mon as usize) }; unsafe { core::ptr::copy_nonoverlapping(wday.as_ptr(), buf.as_mut_ptr().add(6), 3); } buf[11] = b'0' + (day / 10) as u8; buf[12] = b'0' + (day % 10) as u8; unsafe { core::ptr::copy_nonoverlapping(mon.as_ptr(), buf.as_mut_ptr().add(14), 3); } buf[18] = b'0' + (year / 1000) as u8; buf[19] = b'0' + (year / 100 % 10) as u8; buf[20] = b'0' + (year / 10 % 10) as u8; buf[21] = b'0' + (year % 10) as u8; buf[23] = b'0' + (hour / 10) as u8; buf[24] = b'0' + (hour % 10) as u8; buf[26] = b'0' + (min / 10) as u8; buf[27] = b'0' + (min % 10) as u8; buf[29] = b'0' + (sec / 10) as u8; buf[30] = b'0' + (sec % 10) as u8; } ================================================ FILE: src/http_request_path.rs ================================================ /* FaF is a cutting edge, high performance web server Copyright (C) 2021 James Bates This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ // This is faf's approach to parsing the HTTP request buffer, faster than all tested alternatives // * Extract method // * Extract path // * Return a pointer to the buffer position at the end of the request. // Why? Because requests are pipelined and come in back to back // 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 // One oddity is how it matches two characters back to back (\r\n). Due to how _mm_cmpestri works, it doesn't actually // match back-to-back characters, so it looks like this is erroneous, but I don't care if the characters are back-to-back, // 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 // characters are found, with the magic number 0x0a0d0a0d which is \r\n\r\n use core::arch::x86_64::{ __m128i, _mm_cmpestri, _mm_load_si128, _mm_loadu_si128, _SIDD_CMP_EQUAL_ORDERED, _SIDD_UBYTE_OPS, }; use core::intrinsics::{likely, unlikely}; const SPACE: i8 = b' ' as i8; #[repr(align(64))] pub struct AlignedPattern([u8; 2]); const EOL_PATTERN: AlignedPattern = AlignedPattern(*b"\r\n"); #[inline] pub unsafe fn find_sequence_simd(buf_start: *const i8, buf_end: *const i8) -> *const i8 { const OP: i32 = _SIDD_CMP_EQUAL_ORDERED | _SIDD_UBYTE_OPS; let mut buf: *const i8 = buf_start; // We only use two bytes as our pattern, and that is ok let sixteen_byte_pattern: __m128i = _mm_load_si128(EOL_PATTERN.0.as_ptr() as *const __m128i); loop { let sixteen_bytes_from_buffer: __m128i = _mm_loadu_si128(buf as *const __m128i); let found_at_byte_pos = _mm_cmpestri::(sixteen_byte_pattern, 2, sixteen_bytes_from_buffer, 16); // If found_at_byte_pos == 16, then we didn't find a match. We found a match if less than 16 if found_at_byte_pos != 16 { //Increment buf by found_at_byte_pos, which is the position in the 16 byte search buf = buf.add(found_at_byte_pos as usize); return buf; } //Increment by 15 bytes instead of 16 bytes to ensure \r\n is never split/overlaps between searches buf = buf.add(15); if buf >= buf_end { break; } } buf_end } #[inline(always)] pub unsafe fn parse_request_path_pipelined_simd( buf_start: *const i8, mut len: usize, method: *mut *const i8, method_len: *mut usize, path: *mut *const i8, path_len: *mut usize, ) -> isize { let mut buf: *const i8 = buf_start; let buf_end: *const i8 = buf_start.add(len); let mut i = 0; // The longest HTTP 1.1 request method is 7 characters, + 1 character for the space after while likely(i < 9) { if *(buf.add(i)) == SPACE { *method = buf; *method_len = i; i += 1; while unlikely(*(buf.add(i)) == SPACE) { i += 1 } break; } i += 1; } buf = buf.add(i); len -= i; i = 0; while likely(i < len) { if *(buf.add(i)) == SPACE { *path = buf; *path_len = i; i += 1; while unlikely(*(buf.add(i)) == SPACE) { i += 1 } break; } i += 1; } if unlikely(*path_len == 0 || *method_len == 0) { return -1; }; buf = buf.add(i); while likely(buf < buf_end) { buf = find_sequence_simd(buf, buf_end); if *(buf as *const u32) == 0x0a0d0a0d { buf = buf.add(4); return (buf as usize - buf_start as usize) as isize; } else { buf = buf.add(2); } } -2 } ================================================ FILE: src/lib.rs ================================================ /* FaF is a cutting edge, high performance web server Copyright (C) 2021 James Bates This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ #![allow(clippy::missing_safety_doc, clippy::uninit_assumed_init, dead_code)] #![feature(const_size_of_val, core_intrinsics)] pub mod const_config; pub mod const_http; mod const_sys; pub mod epoll; mod http_content_length; mod http_date; mod http_request_path; mod net; mod syscall; pub mod util; ================================================ FILE: src/net.rs ================================================ /* FaF is a cutting edge, high performance web server Copyright (C) 2021 James Bates This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ use crate::const_config::MAX_CONN; use crate::const_sys::*; use crate::sys_call; #[inline(always)] pub fn htons(u: u16) -> u16 { u.to_be() } #[inline(always)] pub fn htonl(u: u32) -> u32 { u.to_be() } #[repr(C)] pub struct in_addr { pub s_addr: u32, } #[repr(C, align(16))] pub struct sockaddr_in { pub sin_family: u16, pub sin_port: u16, pub sin_addr: in_addr, pub sin_zero: [u8; 8], } #[repr(C, align(16))] pub struct linger { pub l_onoff: i32, pub l_linger: i32, } #[repr(C)] pub struct sock_filter { pub code: u16, pub jt: u8, pub jf: u8, pub k: u32, } #[repr(C)] pub struct sock_fprog { pub len: u16, pub filter: *mut sock_filter, } const OPTVAL: isize = 1; const OPTVAL_BUSYPOLL: isize = 50; pub const O_NONBLOCK: isize = 2048; const F_SETFL: isize = 4; #[inline] pub fn get_listener_fd(port: u16) -> (isize, sockaddr_in, u32) { const _OPTVAL_TCPDEFERACCEPT_TIMEOUT: isize = 10; const OPTVAL_TCPFASTOPEN_QUEUE_LEN: isize = MAX_CONN as isize; const AF_INET: i32 = 2; unsafe { let fd_listener = sys_call!(SYS_SOCKET as isize, AF_INET as isize, SOCK_STREAM as isize, 0); let size_of_optval = core::mem::size_of_val(&OPTVAL) as u32; // sys_call!( // SYS_SETSOCKOPT as isize, // fd_listener, // SOL_SOCKET as isize, // SO_REUSEADDR as isize, // &OPTVAL as *const _ as _, // size_of_optval as isize // ); sys_call!( SYS_SETSOCKOPT as isize, fd_listener, SOL_SOCKET as isize, SO_REUSEPORT as isize, &OPTVAL as *const isize as _, size_of_optval as isize ); // sys_call!( // SYS_SETSOCKOPT as isize, // fd_listener, // SOL_SOCKET as isize, // SO_REUSEPORT as isize, // &OPTVAL as *const isize as _, // size_of_optval as isize // ); // sys_call!( // SYS_SETSOCKOPT as isize, // fd_listener, // IPPROTO_TCP as isize, // TCP_QUICKACK as isize, // &OPTVAL as *const _ as _, // core::mem::size_of_val(&OPTVAL) as isize // ); // sys_call!( // SYS_SETSOCKOPT as isize, // fd_listener, // IPPROTO_TCP as isize, // TCP_FASTOPEN as isize, // &MAX_CONN as *const _ as _, // core::mem::size_of_val(&MAX_CONN) as isize // ); // Does not add much throughput, if any. Also, can hide dead connections. Not useful. // sys_call!( // SYS_SETSOCKOPT as isize, // fd_listener, // IPPROTO_TCP as isize, // TCP_DEFER_ACCEPT as isize, // &_OPTVAL_TCPDEFERACCEPT_TIMEOUT as *const _ as _, // core::mem::size_of_val(&_OPTVAL_TCPDEFERACCEPT_TIMEOUT) as isize // ); //https://stackoverflow.com/a/49900878 // sys_call!( // SYS_SETSOCKOPT as isize, // fd_listener, // SOL_SOCKET as isize, // SO_ZEROCOPY as isize, // &OPTVAL as *const _ as _, // core::mem::size_of_val(&OPTVAL) as isize // ); let addr = sockaddr_in { sin_family: AF_INET as u16, sin_port: htons(port), sin_addr: in_addr { s_addr: htonl(INADDR_ANY) }, sin_zero: core::mem::zeroed(), }; sys_call!(SYS_BIND as isize, fd_listener, &addr as *const _ as _, core::mem::size_of_val(&addr) as isize); sys_call!(SYS_LISTEN as isize, fd_listener, OPTVAL_TCPFASTOPEN_QUEUE_LEN); let sock_len: u32 = core::mem::size_of::() as u32; (fd_listener, addr, sock_len) } } #[inline] pub fn setup_connection(fd: isize) { //Doesn't help with throughput, just latency per request, and may actually reduce throughput. //May be Useful for this test. I'm not entirely convinced though sys_call!( SYS_SETSOCKOPT as isize, fd, IPPROTO_TCP as isize, TCP_NODELAY as isize, &OPTVAL as *const _ as _, core::mem::size_of_val(&OPTVAL) as isize ); // Since quickack has to be set every time, it isn't worth setting // sys_call!( // SYS_SETSOCKOPT as isize, // fd, // IPPROTO_TCP as isize, // TCP_QUICKACK as isize, // &OPTVAL as *const _ as _, // core::mem::size_of_val(&OPTVAL) as isize // ); //https://stackoverflow.com/a/49900878 // sys_call!( // SYS_SETSOCKOPT as isize, // fd, // SOL_SOCKET as isize, // SO_ZEROCOPY as isize, // &OPTVAL as *const isize as _, // core::mem::size_of_val(&OPTVAL) as isize // ); // Only useful when using blocking reads, not non-blocking reads as I am // sys_call!( // SYS_SETSOCKOPT as isize, // fd, // SOL_SOCKET as isize, // SO_BUSY_POLL as isize, // &OPTVAL_BUSYPOLL as *const _ as _, // core::mem::size_of_val(&OPTVAL_BUSYPOLL) as isize // ); sys_call!(SYS_FCNTL as isize, fd, F_SETFL, O_NONBLOCK); } #[inline(always)] pub fn close_connection(epfd: isize, fd: isize) { const OPTVAL_SOLINGER_TIMEOUT: linger = linger { l_onoff: 1, l_linger: 0 }; sys_call!( SYS_SETSOCKOPT as isize, fd, SOL_SOCKET as isize, SO_LINGER as isize, &OPTVAL_SOLINGER_TIMEOUT as *const _ as _, core::mem::size_of_val(&OPTVAL_SOLINGER_TIMEOUT) as isize ); // Could defer deletes for performance reasons. Wouldn't cause problems as fds are reused. Not going to do this as it would // require tracking fd state more granually to avoid the wasted EPOLL_CTL_ADD when new connections come in. I don't know // how much of a benefit, performance-wise I'd get sys_call!(SYS_EPOLL_CTL as isize, epfd, EPOLL_CTL_DEL as isize, fd, 0); sys_call!(SYS_CLOSE as isize, fd); } #[inline(always)] pub fn attach_reuseport_cbpf(fd: isize) { // https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/bpf_common.h // BPF_CLASS const BPF_LD: u16 = 0x00; const BPF_RET: u16 = 0x06; // BPF_SIZE const BPF_W: u16 = 0x00; // BPF_MODE const BPF_ABS: u16 = 0x20; // https://elixir.bootlin.com/linux/latest/source/include/uapi/linux/filter.h // BPF_RVAL const BPF_A: u16 = 0x10; // SKF const SKF_AD_OFF: i32 = -0x1000; const SKF_AD_CPU: i32 = 36; let mut code: [sock_filter; 2] = [ sock_filter { code: BPF_LD | BPF_W | BPF_ABS, jt: 0, jf: 0, k: (SKF_AD_OFF + SKF_AD_CPU) as u32 }, sock_filter { code: BPF_RET | BPF_A, jt: 0, jf: 0, k: 0 }, ]; let prog = sock_fprog { len: code.len() as u16, filter: code.as_mut_ptr() }; let ret = sys_call!( SYS_SETSOCKOPT as isize, fd, SOL_SOCKET as isize, SO_ATTACH_REUSEPORT_CBPF as isize, &prog as *const _ as _, core::mem::size_of::() as isize ); //println!("SO_ATTACH_REUSEPORT_CBPF ret: {}, size = {}", ret, core::mem::size_of::() as isize); } #[inline(always)] pub fn debug_incoming_cpu(incoming_fd: isize, listener_fd: isize, cpu_core: i32) { let incoming_cpu: i32 = -1; let incoming_ret = sys_call!( SYS_GETSOCKOPT as isize, incoming_fd, SOL_SOCKET as isize, SO_INCOMING_CPU as isize, &incoming_cpu as *const _ as _, &core::mem::size_of_val(&incoming_cpu) as *const _ as _ ); let listener_cpu: i32 = -1; let listener_ret = sys_call!( SYS_GETSOCKOPT as isize, listener_fd, SOL_SOCKET as isize, SO_INCOMING_CPU as isize, &listener_cpu as *const _ as _, &core::mem::size_of_val(&listener_cpu) as *const _ as _ ); let incoming_napi_id: i32 = -1; let incoming_napi_id_ret = sys_call!( SYS_GETSOCKOPT as isize, incoming_fd, SOL_SOCKET as isize, SO_INCOMING_NAPI_ID as isize, &incoming_napi_id as *const _ as _, &core::mem::size_of_val(&incoming_napi_id) as *const _ as _ ); println!( "fd: {}, received request on core {} with ret value {}, should be core {}, listener_fd is on core {} with ret value {}, with napi id {} with ret {}", incoming_fd, incoming_cpu, incoming_ret, cpu_core, listener_cpu, listener_ret, incoming_napi_id, incoming_napi_id_ret ); } ================================================ FILE: src/syscall.rs ================================================ // This particular file is LICENSED AS Unlicense (https://unlicense.org/) // To use this yourself, see https://crates.io/crates/faf-syscall use core::arch::asm; #[macro_export(local_inner_macros)] macro_rules! sys_call { ($num:ident) => { $crate::syscall::sys_call0($num) }; ($num:expr, $arg1:expr) => { $crate::syscall::sys_call1($num, $arg1) }; ($num:expr, $arg1:expr, $arg2:expr) => { $crate::syscall::sys_call2($num, $arg1, $arg2) }; ($num:expr, $arg1:expr, $arg2:expr, $arg3:expr) => { $crate::syscall::sys_call3($num, $arg1, $arg2, $arg3) }; ($num:expr, $arg1:expr, $arg2:expr, $arg3:expr, $arg4:expr) => { $crate::syscall::sys_call4($num, $arg1, $arg2, $arg3, $arg4) }; ($num:expr, $arg1:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5:expr) => { $crate::syscall::sys_call5($num, $arg1, $arg2, $arg3, $arg4, $arg5) }; ($num:expr, $arg1:expr, $arg2:expr, $arg3:expr, $arg4:expr, $arg5:expr, $arg6:expr) => { $crate::syscall::sys_call6($num, $arg1, $arg2, $arg3, $arg4, $arg5, $arg6) }; } #[inline(always)] pub fn sys_call0(mut num: isize) -> isize { unsafe { asm!( "syscall", in("rax") num, out("rcx") _, out("r11") _, lateout("rax") num, options(nostack, preserves_flags)); num } } #[inline(always)] pub fn sys_call1(mut num: isize, arg1: isize) -> isize { unsafe { asm!( "syscall", in("rax") num, in("rdi") arg1, out("rcx") _, out("r11") _, lateout("rax") num, options(nostack, preserves_flags)); num } } #[inline(always)] pub fn sys_call2(mut num: isize, arg1: isize, arg2: isize) -> isize { unsafe { asm!( "syscall", in("rax") num, in("rdi") arg1, in("rsi") arg2, out("rcx") _, out("r11") _, lateout("rax") num, options(nostack, preserves_flags)); num } } #[inline(always)] pub fn sys_call3(mut num: isize, arg1: isize, arg2: isize, arg3: isize) -> isize { unsafe { asm!( "syscall", in("rax") num, in("rdi") arg1, in("rsi") arg2, in("rdx") arg3, out("rcx") _, out("r11") _, lateout("rax") num, options(nostack, preserves_flags)); num } } #[inline(always)] pub fn sys_call4(mut num: isize, arg1: isize, arg2: isize, arg3: isize, arg4: isize) -> isize { unsafe { asm!( "syscall", in("rax") num, in("rdi") arg1, in("rsi") arg2, in("rdx") arg3, in("r10") arg4, out("rcx") _, out("r11") _, lateout("rax") num, options(nostack, preserves_flags)); num } } #[inline(always)] pub fn sys_call5(mut num: isize, arg1: isize, arg2: isize, arg3: isize, arg4: isize, arg5: isize) -> isize { unsafe { asm!( "syscall", in("rax") num, in("rdi") arg1, in("rsi") arg2, in("rdx") arg3, in("r10") arg4, in("r8") arg5, out("rcx") _, out("r11") _, lateout("rax") num, options(nostack, preserves_flags)); num } } #[inline(always)] pub fn sys_call6( mut num: isize, arg1: isize, arg2: isize, arg3: isize, arg4: isize, arg5: isize, arg6: isize, ) -> isize { unsafe { asm!( "syscall", in("rax") num, in("rdi") arg1, in("rsi") arg2, in("rdx") arg3, in("r10") arg4, in("r8") arg5, in("r9") arg6, out("rcx") _, out("r11") _, lateout("rax") num, options(nostack, preserves_flags)); num } } ================================================ FILE: src/util.rs ================================================ /* FaF is a cutting edge, high performance web server Copyright (C) 2021 James Bates This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . */ const _SC_NPROCESSORS_ONLN: i32 = 84; extern "C" { pub fn memcmp(s1: *const u8, s2: *const u8, n: usize) -> i32; fn sysconf(name: i32) -> isize; fn sched_getaffinity(pid: i32, cpusetsize: usize, cpuset: *mut cpu_set_t) -> i32; fn sched_setaffinity(pid: i32, cpusetsize: usize, cpuset: *const cpu_set_t) -> i32; } const POINTER_WIDTH_IN_BITS: usize = core::mem::size_of::() * 8; // We always want a total of 1024 bits, so 16 segments on 64-bit platforms, 32 segments on 32-bit platforms const CPU_SET_LEN: usize = 1024 / POINTER_WIDTH_IN_BITS; #[repr(C, align(64))] struct cpu_set_t([usize; CPU_SET_LEN]); #[inline] fn cpu_isset(cpu_num: usize, set: &cpu_set_t) -> bool { let chunk_index = cpu_num / POINTER_WIDTH_IN_BITS; let chunk_offset = cpu_num % POINTER_WIDTH_IN_BITS; ((1 << chunk_offset) & set.0[chunk_index]) != 0 } #[inline] fn cpu_set(cpu_num: usize, set: &mut cpu_set_t) { let chunk_index = cpu_num / POINTER_WIDTH_IN_BITS; let chunk_offset = cpu_num % POINTER_WIDTH_IN_BITS; set.0[chunk_index] |= 1 << chunk_offset; } // 0 indicates the current thread's PID for this API const CURRENT_THREAD_CONTROL_PID: i32 = 0; #[inline] pub fn set_current_thread_cpu_affinity_to(cpu_num: usize) { let mut set: cpu_set_t = unsafe { core::mem::MaybeUninit::zeroed().assume_init() }; unsafe { sched_getaffinity(CURRENT_THREAD_CONTROL_PID, core::mem::size_of::(), &mut set) }; if !cpu_isset(cpu_num, &set) { eprintln!("Cannot set affinity for cpu {}", cpu_num); } else { let mut set_control: cpu_set_t = unsafe { core::mem::MaybeUninit::zeroed().assume_init() }; cpu_set(cpu_num, &mut set_control); unsafe { sched_setaffinity(0, core::mem::size_of::(), &set_control) }; } } #[inline] pub fn get_num_logical_cpus() -> usize { let cpus = unsafe { sysconf(_SC_NPROCESSORS_ONLN) }; if cpus <= 0 { eprintln!("Cannot determine the number of logical cpus with sysconf, performance will be severely impacted"); 1 } else { cpus as usize } } #[inline] pub const unsafe fn transmute(from: From) -> To { union Transmute { from: core::mem::ManuallyDrop, to: core::mem::ManuallyDrop, } core::mem::ManuallyDrop::into_inner(Transmute { from: core::mem::ManuallyDrop::new(from) }.to) } #[inline] pub const unsafe fn concat(a: &[u8], b: &[u8]) -> Out where First: Copy, Second: Copy, Out: Copy, { #[repr(C)] #[derive(Copy, Clone)] struct Both(A, B); let arr: Both = Both(*transmute::<_, *const First>(a.as_ptr()), *transmute::<_, *const Second>(b.as_ptr())); transmute(arr) } #[inline] pub const fn const_len(con: &[T]) -> usize { con.len() } // _mm_prefetch #[allow(clippy::not_unsafe_ptr_arg_deref)] #[inline] fn prefetch(p: *const u8, offset: isize) { unsafe { core::intrinsics::prefetch_read_data(p.offset(offset) as *const u8, 3) }; }