···11+22+# Contributor Covenant Code of Conduct
33+44+## Our Pledge
55+66+We as members, contributors, and leaders pledge to make participation in our
77+community a harassment-free experience for everyone, regardless of age, body
88+size, visible or invisible disability, ethnicity, sex characteristics, gender
99+identity and expression, level of experience, education, socio-economic status,
1010+nationality, personal appearance, race, caste, color, religion, or sexual
1111+identity and orientation.
1212+1313+We pledge to act and interact in ways that contribute to an open, welcoming,
1414+diverse, inclusive, and healthy community.
1515+1616+## Our Standards
1717+1818+Examples of behavior that contributes to a positive environment for our
1919+community include:
2020+2121+* Demonstrating empathy and kindness toward other people
2222+* Being respectful of differing opinions, viewpoints, and experiences
2323+* Giving and gracefully accepting constructive feedback
2424+* Accepting responsibility and apologizing to those affected by our mistakes,
2525+ and learning from the experience
2626+* Focusing on what is best not just for us as individuals, but for the overall
2727+ community
2828+2929+Examples of unacceptable behavior include:
3030+3131+* The use of sexualized language or imagery, and sexual attention or advances of
3232+ any kind
3333+* Trolling, insulting or derogatory comments, and personal or political attacks
3434+* Public or private harassment
3535+* Publishing others' private information, such as a physical or email address,
3636+ without their explicit permission
3737+* Other conduct which could reasonably be considered inappropriate in a
3838+ professional setting
3939+4040+## Enforcement Responsibilities
4141+4242+Community leaders are responsible for clarifying and enforcing our standards of
4343+acceptable behavior and will take appropriate and fair corrective action in
4444+response to any behavior that they deem inappropriate, threatening, offensive,
4545+or harmful.
4646+4747+Community leaders have the right and responsibility to remove, edit, or reject
4848+comments, commits, code, wiki edits, issues, and other contributions that are
4949+not aligned to this Code of Conduct, and will communicate reasons for moderation
5050+decisions when appropriate.
5151+5252+## Scope
5353+5454+This Code of Conduct applies within all community spaces, and also applies when
5555+an individual is officially representing the community in public spaces.
5656+Examples of representing our community include using an official e-mail address,
5757+posting via an official social media account, or acting as an appointed
5858+representative at an online or offline event.
5959+6060+## Enforcement
6161+6262+Instances of abusive, harassing, or otherwise unacceptable behavior may be
6363+reported to the community leaders responsible for enforcement over email at
6464+<sachymetsu@tutamail.com>.
6565+All complaints will be reviewed and investigated promptly and fairly.
6666+6767+All community leaders are obligated to respect the privacy and security of the
6868+reporter of any incident.
6969+7070+## Enforcement Guidelines
7171+7272+Community leaders will follow these Community Impact Guidelines in determining
7373+the consequences for any action they deem in violation of this Code of Conduct:
7474+7575+### 1. Correction
7676+7777+**Community Impact**: Use of inappropriate language or other behavior deemed
7878+unprofessional or unwelcome in the community.
7979+8080+**Consequence**: A private, written warning from community leaders, providing
8181+clarity around the nature of the violation and an explanation of why the
8282+behavior was inappropriate. A public apology may be requested.
8383+8484+### 2. Warning
8585+8686+**Community Impact**: A violation through a single incident or series of
8787+actions.
8888+8989+**Consequence**: A warning with consequences for continued behavior. No
9090+interaction with the people involved, including unsolicited interaction with
9191+those enforcing the Code of Conduct, for a specified period of time. This
9292+includes avoiding interactions in community spaces as well as external channels
9393+like social media. Violating these terms may lead to a temporary or permanent
9494+ban.
9595+9696+### 3. Temporary Ban
9797+9898+**Community Impact**: A serious violation of community standards, including
9999+sustained inappropriate behavior.
100100+101101+**Consequence**: A temporary ban from any sort of interaction or public
102102+communication with the community for a specified period of time. No public or
103103+private interaction with the people involved, including unsolicited interaction
104104+with those enforcing the Code of Conduct, is allowed during this period.
105105+Violating these terms may lead to a permanent ban.
106106+107107+### 4. Permanent Ban
108108+109109+**Community Impact**: Demonstrating a pattern of violation of community
110110+standards, including sustained inappropriate behavior, harassment of an
111111+individual, or aggression toward or disparagement of classes of individuals.
112112+113113+**Consequence**: A permanent ban from any sort of public interaction within the
114114+community.
115115+116116+## Attribution
117117+118118+This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119119+version 2.1, available at
120120+[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
121121+122122+Community Impact Guidelines were inspired by
123123+[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
124124+125125+For answers to common questions about this code of conduct, see the FAQ at
126126+[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
127127+[https://www.contributor-covenant.org/translations][translations].
128128+129129+[homepage]: https://www.contributor-covenant.org
130130+[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
131131+[Mozilla CoC]: https://github.com/mozilla/diversity
132132+[FAQ]: https://www.contributor-covenant.org/faq
133133+[translations]: https://www.contributor-covenant.org/translations
+71
CONTRIBUTING.md
···11+# Contributing to Nailpit
22+33+Nailpit is software written by humans *for* humans. Or at least, software written by humans to deter (misbehaving) machines. As such, all contributions should not be using AI in any form. There is no pressure to "ship it" here, no investor baiting, no tech hyping. This project is a temple to the art and joy of coding, and thus should be enjoyed for what it is, not delegated to an unthinking machine. There is no expectation of perfection, only for understanding and for doing one's best.
44+55+That's the starting point: *Be Human*
66+77+From there, contributing is as simple as creating a fork of this project, get it to compile on your local environment, creating a branch, then publishing the branch once you are done. Create a pull request (PR) and then hope for the best!
88+99+To contribute, there is the expectation that you are at least familiar with:
1010+1111+- git
1212+- Rust and its toolchains, cargo, etc
1313+- HTML and web stuff.
1414+1515+If the above are not things you are familiar with, then please take the time to learn them. There are resources for this.
1616+1717+## Implementing a feature/improvement
1818+1919+Before starting work on a feature, check if there isn't an open issue or PR already. If there's something on the roadmap that hasn't been done, or if there isn't and you feel it would be a good addition, feel free to take up on that task. First, create a specific issue for that feature and try to outline the following:
2020+2121+- Feature to be worked on, explaining why it is needed
2222+- (Optional) Outline the proposed implementation, or implementations if soliciting wider feedback.
2323+- If it is a large feature, outline smaller steps for completing the work.
2424+2525+If the issue is reviewed/discussed and the consensus is to go forward, then feel free to create a PR. You can also create draft PRs if you wish to take more exploratory work upfront in order to get more information on a given approach. Such work should still be pinned to an issue in order to track progress.
2626+2727+PR's should have a clear and concise title outling the feature. The PR description should then provide an explanation of the feature implementation, and also how to test it, as well as any breaking changes. If the PR implements a feature completely, ensure there is a link back to the issue stating "Closes #issue number"
2828+2929+Once the PR is reviewed and it passes all CI checks, it will get merged and the feature issue updated/closed.
3030+3131+## Submitting bug fixes
3232+3333+If a bug is found, create an issue detailing the following:
3434+3535+- Nailpit version (branch, commit, etc)
3636+- Hardware/OS versions (example, Raspberry Pi 5 8GB, Debian arm64)
3737+- Situation which bug was found
3838+ - Expected behaviour
3939+ - Actual (buggy) behaviour
4040+4141+Include a minimal reproducible example of the code for showcasing the bug if it involves library/crate code, else include the configuration that triggers the bug if it is for the application itself.
4242+4343+Ensure the bug issue is created first before submitting a PR to fix the bug. This is to help track the issue and also any impact. The PR should reference the original issue with "Closes #issue number".
4444+4545+## Documentation
4646+4747+All submitted code should have *some* documentation in place. It does not need to be extensive, but it should explain and detail the implementation, how to use new APIs/methods, etc. More extensive documentation can be added later, but such efforts should have a dedicated issue to track the progress. All documentation should not be written/generated by LLMs. Please take the time to write it yourself. Any poor english/grammar can always be fixed through code review. It's more important to have true understanding of what you are writing about and being able to communicate very intricate technical details, nuances and concepts that LLMs are utterly inadequate with.
4848+4949+## Unsafe code
5050+5151+If you are not completely comfortable writing `unsafe` code, then don't. Stick to safe rust. If you are comfortable with writing `unsafe` rust, stick to safe rust. Break out the `unsafe` only when there is reason for it, and be prepared to document that reasoning extensively. It is important to get it correct, both for testing with Miri, but to ensure any future contributors can come in and understand what can be touched and what shouldn't.
5252+5353+If in the future, Rust comes out with a feature that allows existing `unsafe` code to be written in safe rust without perf regressions, then that code will be refactored to safe rust.
5454+5555+The idea here is we only employ `unsafe` code where necessary. Make use of tools like Miri to check any unsafe code, and be thorough with tests to ensure all corner cases are caught.
5656+5757+## Where to go from here?
5858+5959+Still interested in contributing? Check out the [roadmap here](https://tangled.org/sachy.dev/nailpit) if you need a high-level view of what the goals are and what needs to be worked on. That should give you a general idea of what the state of the project is and what to take on in terms of tasks.
6060+6161+## But why no AI?
6262+6363+As the maintainer of this project, I expect any and all contributors to truly understand the code they are contributing. What does it do? What are the pros of the approach? What are the cons and trade-offs? I am not expecting super high quality code, but I am expecting code that has been crafted with full understanding of that implementation. This has benefits for both myself a maintainer and for you as a contributor:
6464+6565+1. Code that is understood is more easily maintained. Knowing what are the edge-cases helps narrow down sources of bugs and providing suitable fixes, and also allows for future work to be planned around the provided code.
6666+2. Code that is understood is less likely to need to be constantly refactored, reducing churn and tech-debt.
6767+3. Code that is understood is easier to write accurate documentation for, and provide examples for. And during code review, you'll be able to explain what you've done more confidently.
6868+6969+By using an AI/LLM to generate the code, you are trading this understanding for speed and convenience. But for Open Source Software, what matters more is providing code that others can understand and maintain. You might contribute a feature, but that feature will then need to be maintained by myself and others in the future, so ensuring everything is clear and well documented is of vital importance. If you can't code a feature without the assistance of an AI tool, then you can't code with any level of understanding. But it isn't hard to do so! It just might take longer (and you might learn a few things in the process by doing so).
7070+7171+Other reasons for not wanting AI/LLM generated contributions is for legal reasons (questions regarding copyright & licensing violations on data which these models are trained on), and ethical reasons (such as the power consumption and exorbitant water requirements these models require). Best to avoid all that by just not accepting AI/LLM generated contributions.
···11+ GNU AFFERO GENERAL PUBLIC LICENSE
22+ Version 3, 19 November 2007
33+44+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
55+ Everyone is permitted to copy and distribute verbatim copies
66+ of this license document, but changing it is not allowed.
77+88+ Preamble
99+1010+ The GNU Affero General Public License is a free, copyleft license for
1111+software and other kinds of works, specifically designed to ensure
1212+cooperation with the community in the case of network server software.
1313+1414+ The licenses for most software and other practical works are designed
1515+to take away your freedom to share and change the works. By contrast,
1616+our General Public Licenses are intended to guarantee your freedom to
1717+share and change all versions of a program--to make sure it remains free
1818+software for all its users.
1919+2020+ When we speak of free software, we are referring to freedom, not
2121+price. Our General Public Licenses are designed to make sure that you
2222+have the freedom to distribute copies of free software (and charge for
2323+them if you wish), that you receive source code or can get it if you
2424+want it, that you can change the software or use pieces of it in new
2525+free programs, and that you know you can do these things.
2626+2727+ Developers that use our General Public Licenses protect your rights
2828+with two steps: (1) assert copyright on the software, and (2) offer
2929+you this License which gives you legal permission to copy, distribute
3030+and/or modify the software.
3131+3232+ A secondary benefit of defending all users' freedom is that
3333+improvements made in alternate versions of the program, if they
3434+receive widespread use, become available for other developers to
3535+incorporate. Many developers of free software are heartened and
3636+encouraged by the resulting cooperation. However, in the case of
3737+software used on network servers, this result may fail to come about.
3838+The GNU General Public License permits making a modified version and
3939+letting the public access it on a server without ever releasing its
4040+source code to the public.
4141+4242+ The GNU Affero General Public License is designed specifically to
4343+ensure that, in such cases, the modified source code becomes available
4444+to the community. It requires the operator of a network server to
4545+provide the source code of the modified version running there to the
4646+users of that server. Therefore, public use of a modified version, on
4747+a publicly accessible server, gives the public access to the source
4848+code of the modified version.
4949+5050+ An older license, called the Affero General Public License and
5151+published by Affero, was designed to accomplish similar goals. This is
5252+a different license, not a version of the Affero GPL, but Affero has
5353+released a new version of the Affero GPL which permits relicensing under
5454+this license.
5555+5656+ The precise terms and conditions for copying, distribution and
5757+modification follow.
5858+5959+ TERMS AND CONDITIONS
6060+6161+ 0. Definitions.
6262+6363+ "This License" refers to version 3 of the GNU Affero General Public License.
6464+6565+ "Copyright" also means copyright-like laws that apply to other kinds of
6666+works, such as semiconductor masks.
6767+6868+ "The Program" refers to any copyrightable work licensed under this
6969+License. Each licensee is addressed as "you". "Licensees" and
7070+"recipients" may be individuals or organizations.
7171+7272+ To "modify" a work means to copy from or adapt all or part of the work
7373+in a fashion requiring copyright permission, other than the making of an
7474+exact copy. The resulting work is called a "modified version" of the
7575+earlier work or a work "based on" the earlier work.
7676+7777+ A "covered work" means either the unmodified Program or a work based
7878+on the Program.
7979+8080+ To "propagate" a work means to do anything with it that, without
8181+permission, would make you directly or secondarily liable for
8282+infringement under applicable copyright law, except executing it on a
8383+computer or modifying a private copy. Propagation includes copying,
8484+distribution (with or without modification), making available to the
8585+public, and in some countries other activities as well.
8686+8787+ To "convey" a work means any kind of propagation that enables other
8888+parties to make or receive copies. Mere interaction with a user through
8989+a computer network, with no transfer of a copy, is not conveying.
9090+9191+ An interactive user interface displays "Appropriate Legal Notices"
9292+to the extent that it includes a convenient and prominently visible
9393+feature that (1) displays an appropriate copyright notice, and (2)
9494+tells the user that there is no warranty for the work (except to the
9595+extent that warranties are provided), that licensees may convey the
9696+work under this License, and how to view a copy of this License. If
9797+the interface presents a list of user commands or options, such as a
9898+menu, a prominent item in the list meets this criterion.
9999+100100+ 1. Source Code.
101101+102102+ The "source code" for a work means the preferred form of the work
103103+for making modifications to it. "Object code" means any non-source
104104+form of a work.
105105+106106+ A "Standard Interface" means an interface that either is an official
107107+standard defined by a recognized standards body, or, in the case of
108108+interfaces specified for a particular programming language, one that
109109+is widely used among developers working in that language.
110110+111111+ The "System Libraries" of an executable work include anything, other
112112+than the work as a whole, that (a) is included in the normal form of
113113+packaging a Major Component, but which is not part of that Major
114114+Component, and (b) serves only to enable use of the work with that
115115+Major Component, or to implement a Standard Interface for which an
116116+implementation is available to the public in source code form. A
117117+"Major Component", in this context, means a major essential component
118118+(kernel, window system, and so on) of the specific operating system
119119+(if any) on which the executable work runs, or a compiler used to
120120+produce the work, or an object code interpreter used to run it.
121121+122122+ The "Corresponding Source" for a work in object code form means all
123123+the source code needed to generate, install, and (for an executable
124124+work) run the object code and to modify the work, including scripts to
125125+control those activities. However, it does not include the work's
126126+System Libraries, or general-purpose tools or generally available free
127127+programs which are used unmodified in performing those activities but
128128+which are not part of the work. For example, Corresponding Source
129129+includes interface definition files associated with source files for
130130+the work, and the source code for shared libraries and dynamically
131131+linked subprograms that the work is specifically designed to require,
132132+such as by intimate data communication or control flow between those
133133+subprograms and other parts of the work.
134134+135135+ The Corresponding Source need not include anything that users
136136+can regenerate automatically from other parts of the Corresponding
137137+Source.
138138+139139+ The Corresponding Source for a work in source code form is that
140140+same work.
141141+142142+ 2. Basic Permissions.
143143+144144+ All rights granted under this License are granted for the term of
145145+copyright on the Program, and are irrevocable provided the stated
146146+conditions are met. This License explicitly affirms your unlimited
147147+permission to run the unmodified Program. The output from running a
148148+covered work is covered by this License only if the output, given its
149149+content, constitutes a covered work. This License acknowledges your
150150+rights of fair use or other equivalent, as provided by copyright law.
151151+152152+ You may make, run and propagate covered works that you do not
153153+convey, without conditions so long as your license otherwise remains
154154+in force. You may convey covered works to others for the sole purpose
155155+of having them make modifications exclusively for you, or provide you
156156+with facilities for running those works, provided that you comply with
157157+the terms of this License in conveying all material for which you do
158158+not control copyright. Those thus making or running the covered works
159159+for you must do so exclusively on your behalf, under your direction
160160+and control, on terms that prohibit them from making any copies of
161161+your copyrighted material outside their relationship with you.
162162+163163+ Conveying under any other circumstances is permitted solely under
164164+the conditions stated below. Sublicensing is not allowed; section 10
165165+makes it unnecessary.
166166+167167+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168168+169169+ No covered work shall be deemed part of an effective technological
170170+measure under any applicable law fulfilling obligations under article
171171+11 of the WIPO copyright treaty adopted on 20 December 1996, or
172172+similar laws prohibiting or restricting circumvention of such
173173+measures.
174174+175175+ When you convey a covered work, you waive any legal power to forbid
176176+circumvention of technological measures to the extent such circumvention
177177+is effected by exercising rights under this License with respect to
178178+the covered work, and you disclaim any intention to limit operation or
179179+modification of the work as a means of enforcing, against the work's
180180+users, your or third parties' legal rights to forbid circumvention of
181181+technological measures.
182182+183183+ 4. Conveying Verbatim Copies.
184184+185185+ You may convey verbatim copies of the Program's source code as you
186186+receive it, in any medium, provided that you conspicuously and
187187+appropriately publish on each copy an appropriate copyright notice;
188188+keep intact all notices stating that this License and any
189189+non-permissive terms added in accord with section 7 apply to the code;
190190+keep intact all notices of the absence of any warranty; and give all
191191+recipients a copy of this License along with the Program.
192192+193193+ You may charge any price or no price for each copy that you convey,
194194+and you may offer support or warranty protection for a fee.
195195+196196+ 5. Conveying Modified Source Versions.
197197+198198+ You may convey a work based on the Program, or the modifications to
199199+produce it from the Program, in the form of source code under the
200200+terms of section 4, provided that you also meet all of these conditions:
201201+202202+ a) The work must carry prominent notices stating that you modified
203203+ it, and giving a relevant date.
204204+205205+ b) The work must carry prominent notices stating that it is
206206+ released under this License and any conditions added under section
207207+ 7. This requirement modifies the requirement in section 4 to
208208+ "keep intact all notices".
209209+210210+ c) You must license the entire work, as a whole, under this
211211+ License to anyone who comes into possession of a copy. This
212212+ License will therefore apply, along with any applicable section 7
213213+ additional terms, to the whole of the work, and all its parts,
214214+ regardless of how they are packaged. This License gives no
215215+ permission to license the work in any other way, but it does not
216216+ invalidate such permission if you have separately received it.
217217+218218+ d) If the work has interactive user interfaces, each must display
219219+ Appropriate Legal Notices; however, if the Program has interactive
220220+ interfaces that do not display Appropriate Legal Notices, your
221221+ work need not make them do so.
222222+223223+ A compilation of a covered work with other separate and independent
224224+works, which are not by their nature extensions of the covered work,
225225+and which are not combined with it such as to form a larger program,
226226+in or on a volume of a storage or distribution medium, is called an
227227+"aggregate" if the compilation and its resulting copyright are not
228228+used to limit the access or legal rights of the compilation's users
229229+beyond what the individual works permit. Inclusion of a covered work
230230+in an aggregate does not cause this License to apply to the other
231231+parts of the aggregate.
232232+233233+ 6. Conveying Non-Source Forms.
234234+235235+ You may convey a covered work in object code form under the terms
236236+of sections 4 and 5, provided that you also convey the
237237+machine-readable Corresponding Source under the terms of this License,
238238+in one of these ways:
239239+240240+ a) Convey the object code in, or embodied in, a physical product
241241+ (including a physical distribution medium), accompanied by the
242242+ Corresponding Source fixed on a durable physical medium
243243+ customarily used for software interchange.
244244+245245+ b) Convey the object code in, or embodied in, a physical product
246246+ (including a physical distribution medium), accompanied by a
247247+ written offer, valid for at least three years and valid for as
248248+ long as you offer spare parts or customer support for that product
249249+ model, to give anyone who possesses the object code either (1) a
250250+ copy of the Corresponding Source for all the software in the
251251+ product that is covered by this License, on a durable physical
252252+ medium customarily used for software interchange, for a price no
253253+ more than your reasonable cost of physically performing this
254254+ conveying of source, or (2) access to copy the
255255+ Corresponding Source from a network server at no charge.
256256+257257+ c) Convey individual copies of the object code with a copy of the
258258+ written offer to provide the Corresponding Source. This
259259+ alternative is allowed only occasionally and noncommercially, and
260260+ only if you received the object code with such an offer, in accord
261261+ with subsection 6b.
262262+263263+ d) Convey the object code by offering access from a designated
264264+ place (gratis or for a charge), and offer equivalent access to the
265265+ Corresponding Source in the same way through the same place at no
266266+ further charge. You need not require recipients to copy the
267267+ Corresponding Source along with the object code. If the place to
268268+ copy the object code is a network server, the Corresponding Source
269269+ may be on a different server (operated by you or a third party)
270270+ that supports equivalent copying facilities, provided you maintain
271271+ clear directions next to the object code saying where to find the
272272+ Corresponding Source. Regardless of what server hosts the
273273+ Corresponding Source, you remain obligated to ensure that it is
274274+ available for as long as needed to satisfy these requirements.
275275+276276+ e) Convey the object code using peer-to-peer transmission, provided
277277+ you inform other peers where the object code and Corresponding
278278+ Source of the work are being offered to the general public at no
279279+ charge under subsection 6d.
280280+281281+ A separable portion of the object code, whose source code is excluded
282282+from the Corresponding Source as a System Library, need not be
283283+included in conveying the object code work.
284284+285285+ A "User Product" is either (1) a "consumer product", which means any
286286+tangible personal property which is normally used for personal, family,
287287+or household purposes, or (2) anything designed or sold for incorporation
288288+into a dwelling. In determining whether a product is a consumer product,
289289+doubtful cases shall be resolved in favor of coverage. For a particular
290290+product received by a particular user, "normally used" refers to a
291291+typical or common use of that class of product, regardless of the status
292292+of the particular user or of the way in which the particular user
293293+actually uses, or expects or is expected to use, the product. A product
294294+is a consumer product regardless of whether the product has substantial
295295+commercial, industrial or non-consumer uses, unless such uses represent
296296+the only significant mode of use of the product.
297297+298298+ "Installation Information" for a User Product means any methods,
299299+procedures, authorization keys, or other information required to install
300300+and execute modified versions of a covered work in that User Product from
301301+a modified version of its Corresponding Source. The information must
302302+suffice to ensure that the continued functioning of the modified object
303303+code is in no case prevented or interfered with solely because
304304+modification has been made.
305305+306306+ If you convey an object code work under this section in, or with, or
307307+specifically for use in, a User Product, and the conveying occurs as
308308+part of a transaction in which the right of possession and use of the
309309+User Product is transferred to the recipient in perpetuity or for a
310310+fixed term (regardless of how the transaction is characterized), the
311311+Corresponding Source conveyed under this section must be accompanied
312312+by the Installation Information. But this requirement does not apply
313313+if neither you nor any third party retains the ability to install
314314+modified object code on the User Product (for example, the work has
315315+been installed in ROM).
316316+317317+ The requirement to provide Installation Information does not include a
318318+requirement to continue to provide support service, warranty, or updates
319319+for a work that has been modified or installed by the recipient, or for
320320+the User Product in which it has been modified or installed. Access to a
321321+network may be denied when the modification itself materially and
322322+adversely affects the operation of the network or violates the rules and
323323+protocols for communication across the network.
324324+325325+ Corresponding Source conveyed, and Installation Information provided,
326326+in accord with this section must be in a format that is publicly
327327+documented (and with an implementation available to the public in
328328+source code form), and must require no special password or key for
329329+unpacking, reading or copying.
330330+331331+ 7. Additional Terms.
332332+333333+ "Additional permissions" are terms that supplement the terms of this
334334+License by making exceptions from one or more of its conditions.
335335+Additional permissions that are applicable to the entire Program shall
336336+be treated as though they were included in this License, to the extent
337337+that they are valid under applicable law. If additional permissions
338338+apply only to part of the Program, that part may be used separately
339339+under those permissions, but the entire Program remains governed by
340340+this License without regard to the additional permissions.
341341+342342+ When you convey a copy of a covered work, you may at your option
343343+remove any additional permissions from that copy, or from any part of
344344+it. (Additional permissions may be written to require their own
345345+removal in certain cases when you modify the work.) You may place
346346+additional permissions on material, added by you to a covered work,
347347+for which you have or can give appropriate copyright permission.
348348+349349+ Notwithstanding any other provision of this License, for material you
350350+add to a covered work, you may (if authorized by the copyright holders of
351351+that material) supplement the terms of this License with terms:
352352+353353+ a) Disclaiming warranty or limiting liability differently from the
354354+ terms of sections 15 and 16 of this License; or
355355+356356+ b) Requiring preservation of specified reasonable legal notices or
357357+ author attributions in that material or in the Appropriate Legal
358358+ Notices displayed by works containing it; or
359359+360360+ c) Prohibiting misrepresentation of the origin of that material, or
361361+ requiring that modified versions of such material be marked in
362362+ reasonable ways as different from the original version; or
363363+364364+ d) Limiting the use for publicity purposes of names of licensors or
365365+ authors of the material; or
366366+367367+ e) Declining to grant rights under trademark law for use of some
368368+ trade names, trademarks, or service marks; or
369369+370370+ f) Requiring indemnification of licensors and authors of that
371371+ material by anyone who conveys the material (or modified versions of
372372+ it) with contractual assumptions of liability to the recipient, for
373373+ any liability that these contractual assumptions directly impose on
374374+ those licensors and authors.
375375+376376+ All other non-permissive additional terms are considered "further
377377+restrictions" within the meaning of section 10. If the Program as you
378378+received it, or any part of it, contains a notice stating that it is
379379+governed by this License along with a term that is a further
380380+restriction, you may remove that term. If a license document contains
381381+a further restriction but permits relicensing or conveying under this
382382+License, you may add to a covered work material governed by the terms
383383+of that license document, provided that the further restriction does
384384+not survive such relicensing or conveying.
385385+386386+ If you add terms to a covered work in accord with this section, you
387387+must place, in the relevant source files, a statement of the
388388+additional terms that apply to those files, or a notice indicating
389389+where to find the applicable terms.
390390+391391+ Additional terms, permissive or non-permissive, may be stated in the
392392+form of a separately written license, or stated as exceptions;
393393+the above requirements apply either way.
394394+395395+ 8. Termination.
396396+397397+ You may not propagate or modify a covered work except as expressly
398398+provided under this License. Any attempt otherwise to propagate or
399399+modify it is void, and will automatically terminate your rights under
400400+this License (including any patent licenses granted under the third
401401+paragraph of section 11).
402402+403403+ However, if you cease all violation of this License, then your
404404+license from a particular copyright holder is reinstated (a)
405405+provisionally, unless and until the copyright holder explicitly and
406406+finally terminates your license, and (b) permanently, if the copyright
407407+holder fails to notify you of the violation by some reasonable means
408408+prior to 60 days after the cessation.
409409+410410+ Moreover, your license from a particular copyright holder is
411411+reinstated permanently if the copyright holder notifies you of the
412412+violation by some reasonable means, this is the first time you have
413413+received notice of violation of this License (for any work) from that
414414+copyright holder, and you cure the violation prior to 30 days after
415415+your receipt of the notice.
416416+417417+ Termination of your rights under this section does not terminate the
418418+licenses of parties who have received copies or rights from you under
419419+this License. If your rights have been terminated and not permanently
420420+reinstated, you do not qualify to receive new licenses for the same
421421+material under section 10.
422422+423423+ 9. Acceptance Not Required for Having Copies.
424424+425425+ You are not required to accept this License in order to receive or
426426+run a copy of the Program. Ancillary propagation of a covered work
427427+occurring solely as a consequence of using peer-to-peer transmission
428428+to receive a copy likewise does not require acceptance. However,
429429+nothing other than this License grants you permission to propagate or
430430+modify any covered work. These actions infringe copyright if you do
431431+not accept this License. Therefore, by modifying or propagating a
432432+covered work, you indicate your acceptance of this License to do so.
433433+434434+ 10. Automatic Licensing of Downstream Recipients.
435435+436436+ Each time you convey a covered work, the recipient automatically
437437+receives a license from the original licensors, to run, modify and
438438+propagate that work, subject to this License. You are not responsible
439439+for enforcing compliance by third parties with this License.
440440+441441+ An "entity transaction" is a transaction transferring control of an
442442+organization, or substantially all assets of one, or subdividing an
443443+organization, or merging organizations. If propagation of a covered
444444+work results from an entity transaction, each party to that
445445+transaction who receives a copy of the work also receives whatever
446446+licenses to the work the party's predecessor in interest had or could
447447+give under the previous paragraph, plus a right to possession of the
448448+Corresponding Source of the work from the predecessor in interest, if
449449+the predecessor has it or can get it with reasonable efforts.
450450+451451+ You may not impose any further restrictions on the exercise of the
452452+rights granted or affirmed under this License. For example, you may
453453+not impose a license fee, royalty, or other charge for exercise of
454454+rights granted under this License, and you may not initiate litigation
455455+(including a cross-claim or counterclaim in a lawsuit) alleging that
456456+any patent claim is infringed by making, using, selling, offering for
457457+sale, or importing the Program or any portion of it.
458458+459459+ 11. Patents.
460460+461461+ A "contributor" is a copyright holder who authorizes use under this
462462+License of the Program or a work on which the Program is based. The
463463+work thus licensed is called the contributor's "contributor version".
464464+465465+ A contributor's "essential patent claims" are all patent claims
466466+owned or controlled by the contributor, whether already acquired or
467467+hereafter acquired, that would be infringed by some manner, permitted
468468+by this License, of making, using, or selling its contributor version,
469469+but do not include claims that would be infringed only as a
470470+consequence of further modification of the contributor version. For
471471+purposes of this definition, "control" includes the right to grant
472472+patent sublicenses in a manner consistent with the requirements of
473473+this License.
474474+475475+ Each contributor grants you a non-exclusive, worldwide, royalty-free
476476+patent license under the contributor's essential patent claims, to
477477+make, use, sell, offer for sale, import and otherwise run, modify and
478478+propagate the contents of its contributor version.
479479+480480+ In the following three paragraphs, a "patent license" is any express
481481+agreement or commitment, however denominated, not to enforce a patent
482482+(such as an express permission to practice a patent or covenant not to
483483+sue for patent infringement). To "grant" such a patent license to a
484484+party means to make such an agreement or commitment not to enforce a
485485+patent against the party.
486486+487487+ If you convey a covered work, knowingly relying on a patent license,
488488+and the Corresponding Source of the work is not available for anyone
489489+to copy, free of charge and under the terms of this License, through a
490490+publicly available network server or other readily accessible means,
491491+then you must either (1) cause the Corresponding Source to be so
492492+available, or (2) arrange to deprive yourself of the benefit of the
493493+patent license for this particular work, or (3) arrange, in a manner
494494+consistent with the requirements of this License, to extend the patent
495495+license to downstream recipients. "Knowingly relying" means you have
496496+actual knowledge that, but for the patent license, your conveying the
497497+covered work in a country, or your recipient's use of the covered work
498498+in a country, would infringe one or more identifiable patents in that
499499+country that you have reason to believe are valid.
500500+501501+ If, pursuant to or in connection with a single transaction or
502502+arrangement, you convey, or propagate by procuring conveyance of, a
503503+covered work, and grant a patent license to some of the parties
504504+receiving the covered work authorizing them to use, propagate, modify
505505+or convey a specific copy of the covered work, then the patent license
506506+you grant is automatically extended to all recipients of the covered
507507+work and works based on it.
508508+509509+ A patent license is "discriminatory" if it does not include within
510510+the scope of its coverage, prohibits the exercise of, or is
511511+conditioned on the non-exercise of one or more of the rights that are
512512+specifically granted under this License. You may not convey a covered
513513+work if you are a party to an arrangement with a third party that is
514514+in the business of distributing software, under which you make payment
515515+to the third party based on the extent of your activity of conveying
516516+the work, and under which the third party grants, to any of the
517517+parties who would receive the covered work from you, a discriminatory
518518+patent license (a) in connection with copies of the covered work
519519+conveyed by you (or copies made from those copies), or (b) primarily
520520+for and in connection with specific products or compilations that
521521+contain the covered work, unless you entered into that arrangement,
522522+or that patent license was granted, prior to 28 March 2007.
523523+524524+ Nothing in this License shall be construed as excluding or limiting
525525+any implied license or other defenses to infringement that may
526526+otherwise be available to you under applicable patent law.
527527+528528+ 12. No Surrender of Others' Freedom.
529529+530530+ If conditions are imposed on you (whether by court order, agreement or
531531+otherwise) that contradict the conditions of this License, they do not
532532+excuse you from the conditions of this License. If you cannot convey a
533533+covered work so as to satisfy simultaneously your obligations under this
534534+License and any other pertinent obligations, then as a consequence you may
535535+not convey it at all. For example, if you agree to terms that obligate you
536536+to collect a royalty for further conveying from those to whom you convey
537537+the Program, the only way you could satisfy both those terms and this
538538+License would be to refrain entirely from conveying the Program.
539539+540540+ 13. Remote Network Interaction; Use with the GNU General Public License.
541541+542542+ Notwithstanding any other provision of this License, if you modify the
543543+Program, your modified version must prominently offer all users
544544+interacting with it remotely through a computer network (if your version
545545+supports such interaction) an opportunity to receive the Corresponding
546546+Source of your version by providing access to the Corresponding Source
547547+from a network server at no charge, through some standard or customary
548548+means of facilitating copying of software. This Corresponding Source
549549+shall include the Corresponding Source for any work covered by version 3
550550+of the GNU General Public License that is incorporated pursuant to the
551551+following paragraph.
552552+553553+ Notwithstanding any other provision of this License, you have
554554+permission to link or combine any covered work with a work licensed
555555+under version 3 of the GNU General Public License into a single
556556+combined work, and to convey the resulting work. The terms of this
557557+License will continue to apply to the part which is the covered work,
558558+but the work with which it is combined will remain governed by version
559559+3 of the GNU General Public License.
560560+561561+ 14. Revised Versions of this License.
562562+563563+ The Free Software Foundation may publish revised and/or new versions of
564564+the GNU Affero General Public License from time to time. Such new versions
565565+will be similar in spirit to the present version, but may differ in detail to
566566+address new problems or concerns.
567567+568568+ Each version is given a distinguishing version number. If the
569569+Program specifies that a certain numbered version of the GNU Affero General
570570+Public License "or any later version" applies to it, you have the
571571+option of following the terms and conditions either of that numbered
572572+version or of any later version published by the Free Software
573573+Foundation. If the Program does not specify a version number of the
574574+GNU Affero General Public License, you may choose any version ever published
575575+by the Free Software Foundation.
576576+577577+ If the Program specifies that a proxy can decide which future
578578+versions of the GNU Affero General Public License can be used, that proxy's
579579+public statement of acceptance of a version permanently authorizes you
580580+to choose that version for the Program.
581581+582582+ Later license versions may give you additional or different
583583+permissions. However, no additional obligations are imposed on any
584584+author or copyright holder as a result of your choosing to follow a
585585+later version.
586586+587587+ 15. Disclaimer of Warranty.
588588+589589+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590590+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591591+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592592+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593593+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594594+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595595+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596596+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597597+598598+ 16. Limitation of Liability.
599599+600600+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601601+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602602+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603603+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604604+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605605+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606606+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607607+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608608+SUCH DAMAGES.
609609+610610+ 17. Interpretation of Sections 15 and 16.
611611+612612+ If the disclaimer of warranty and limitation of liability provided
613613+above cannot be given local legal effect according to their terms,
614614+reviewing courts shall apply local law that most closely approximates
615615+an absolute waiver of all civil liability in connection with the
616616+Program, unless a warranty or assumption of liability accompanies a
617617+copy of the Program in return for a fee.
618618+619619+ END OF TERMS AND CONDITIONS
620620+621621+ How to Apply These Terms to Your New Programs
622622+623623+ If you develop a new program, and you want it to be of the greatest
624624+possible use to the public, the best way to achieve this is to make it
625625+free software which everyone can redistribute and change under these terms.
626626+627627+ To do so, attach the following notices to the program. It is safest
628628+to attach them to the start of each source file to most effectively
629629+state the exclusion of warranty; and each file should have at least
630630+the "copyright" line and a pointer to where the full notice is found.
631631+632632+ Nailpit - A Pit full of Rusty Nails
633633+ Copyright (C) 2025 Sachy.dev
634634+635635+ This program is free software: you can redistribute it and/or modify
636636+ it under the terms of the GNU Affero General Public License as published
637637+ by the Free Software Foundation, either version 3 of the License, or
638638+ (at your option) any later version.
639639+640640+ This program is distributed in the hope that it will be useful,
641641+ but WITHOUT ANY WARRANTY; without even the implied warranty of
642642+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643643+ GNU Affero General Public License for more details.
644644+645645+ You should have received a copy of the GNU Affero General Public License
646646+ along with this program. If not, see <https://www.gnu.org/licenses/>.
647647+648648+Also add information on how to contact you by electronic and paper mail.
649649+650650+ If your software can interact with users remotely through a computer
651651+network, you should also make sure that it provides a way for users to
652652+get its source. For example, if your program is a web application, its
653653+interface could display a "Source" link that leads users to an archive
654654+of the code. There are many ways you could offer source, and different
655655+solutions will be better for different programs; see section 13 for the
656656+specific requirements.
657657+658658+ You should also get your employer (if you work as a programmer) or school,
659659+if any, to sign a "copyright disclaimer" for the program, if necessary.
660660+For more information on this, and how to apply and follow the GNU AGPL, see
661661+<https://www.gnu.org/licenses/>.
+64
README.md
···11+# Nailpit
22+33+Send Malicious Scrapers into an equally malicious tarpit with added rusty nails. Nailpit is an exercise in offensive security, in which malicious actors (in this case, web scrapers) are targeted and have their resources wasted/attacked. The purpose is to use this against scrapers that *ignore* one's `robots.txt` file and any `Disallow` directives, particularly ones that try to scrape private/non-public sections of one's websites/services. In doing so and with enough volume, such scrapers can constitute an effective DoS attack. *This is bad*. Therefore, this project aims to contribute another tool in making sure such misbehaving scrapers are discouraged from targeting your website by inundating them with garbage and poisoned content.
44+55+## Disclaimer
66+77+Nailpit is intended to not be exposed to the public, only to bots/scrapers. Any link into the tarpit should be hidden to users, and the initial entry point for Nailpit is a disclaimer as well. This project is not responsible for misconfigured deployments or consequences relating to that. You are responsible for ensuring this is deployed correctly and employed against only agents that are ignoring widely used and accepted web standards such as `robots.txt`.
88+99+## Minimum CPU Support
1010+1111+For x86_64/amd64 processors, processors that at least qualify for x86-64-v3 level (so supporting AVX2), and for aarch64, processors from the A53 onwards (with NEON support, so Raspberry PI 3 B+). armv7 and RISCV64 are compiled without instruction optimisations.
1212+1313+## How to use / deploy
1414+1515+By default, `nailpit` won't work unless you provide at least *some* input data. In the directory you are running `nailpit` from, create an `input` directory and add a `.txt` file inside of it. Name it anything, whatever, like `first.txt`. In this file, add in content/text, the more the better, as this will train the markov chain on what to generate. So for example, add many paragraphs of lorem ipsum text to the file just to see it work. Once you have at least *one* txt input, `nailpit` will be able to run. Multiple `.txt` files will act as different markov chains, each one outputting differently structured text to the other, and each time a generated page is requested, these chains are selected at random to produce content for that request. So if you want more varied/randomised content, you want not just very large text files of pure text/content, but also many different files. Do keep in mind that the more content and files you use, the bigger the memory usage of the application, though this is kept in check with some memory optimisation techniques.
1616+1717+The input text files should be pure text. It should not be html or markdown or any other format, just text.
1818+1919+### Docker
2020+2121+The easiest way to run `nailpit` is to run it in a docker container. This makes it fairly easy to deploy and ensures its running environment is consistent. This does add *a bit more* overhead, but realistically, not enough to really matter.
2222+2323+If building the image directly from this repo, just use `docker build . -t nailpit`, or if cross-compiling to a different platform like a Raspberry Pi 5, run `docker build --platform=linux/arm64 .`. `nailpit` docker image supports `linux/amd64`, `linux/arm64`, `linux/arm/v7` and `linux/riscv64` platforms. Running the image then becomes the following (with two volumes provided for user overrides):
2424+2525+```
2626+docker run -v ./configuration/:/app/configuration -v ./input/:/app/input -p 3001:3001/tcp nailpit:latest
2727+```
2828+2929+The socket `nailpit` listens to can be overridden with `-e NAILPIT_SOCKET=0.0.0.0:3001`, and it expects the full ip:port string. There's three volumes to be configured, one for `/app/configuration` which is where the default config file lives and will be where your override config file will live, one for `/app/input` which is where the user's input files are located, and the last `/app/templates` for user provided template overrides.
3030+3131+#### Docker Compose
3232+3333+`nailpit` images are available from docker hub via [`docker.io/sachymetsu/nailpit:latest`](https://hub.docker.com/r/sachymetsu/nailpit). Right now, only the latest tag is provided, but these should be stable enough. Using `nailpit` with docker compose can be done with the following example configuration:
3434+3535+```yml
3636+services:
3737+ nailpit:
3838+ container_name: nailpit
3939+ image: docker.io/sachymetsu/nailpit:latest
4040+ restart: unless-stopped
4141+ volumes:
4242+ - /home/user/nailpit/configuration:/app/configuration
4343+ - /home/user/nailpit/input:/app/input
4444+ - /home/user/nailpit/templates:/app/templates
4545+ network_mode: host
4646+```
4747+4848+Images are currently provided for `linux/amd64` and `linux/arm64` platforms.
4949+5050+### Configuration
5151+5252+All of the configuration options are documented in the default config file found [here](./defaults/pit.default.toml). To create your own configuration, create a `pit.toml` file in the configuration folder and add just the configuration options you want to override.
5353+5454+## How to contribute
5555+5656+If you are interested in contributing to this project, check out the [CONTRIBUTING document](CONTRIBUTING.md).
5757+5858+## Code of Conduct
5959+6060+If you are interested in contributing to this project, be sure to review the [CODE OF CONDUCT](CODE_OF_CONDUCT.md).
6161+6262+## License
6363+6464+This project is licensed under AGPL 3.0.
···11+//! Utility crate for deferred initialisation of allocated containers, to lessen stack pressure
22+//! and initialise values directly on the heap. Rust _does_ optimise boxing to not require the
33+//! stack and can initialise directly to the heap, but this does not occur all the time. These
44+//! utils ensure this does happen, by deferring the initialisation of the allocation explicitly.
55+66+use core::pin::Pin;
77+use std::sync::Arc;
88+99+/// Util for deferred initialisation of boxed futures, to lessen stack pressure and initialise
1010+/// the future directly on the heap
1111+#[inline]
1212+pub fn boxed_future_within<'a, T, F, Fut>(fut: F) -> Pin<Box<Fut>>
1313+where
1414+ Fut: Future<Output = T> + Send + 'a,
1515+ F: FnOnce() -> Fut,
1616+{
1717+ let mut boxed = Box::new_uninit();
1818+1919+ boxed.write(fut());
2020+2121+ // SAFETY: We have initialised the Box correctly by writing to
2222+ // the memory in the line above.
2323+ unsafe { Box::into_pin(boxed.assume_init()) }
2424+}
2525+2626+#[inline(always)]
2727+pub fn try_arc_within<T, F, E>(f: F) -> Result<Arc<T>, E>
2828+where
2929+ F: FnOnce() -> Result<T, E>,
3030+{
3131+ let mut arced = Arc::new_uninit();
3232+3333+ Arc::get_mut(&mut arced).unwrap().write(f()?);
3434+3535+ // SAFETY: We have initialised the Arc correctly by writing to
3636+ // the memory in the line above.
3737+ Ok(unsafe { arced.assume_init() })
3838+}
3939+4040+#[inline(always)]
4141+pub fn arc_within<T, F>(f: F) -> Arc<T>
4242+where
4343+ F: FnOnce() -> T,
4444+{
4545+ let mut arced = Arc::new_uninit();
4646+4747+ Arc::get_mut(&mut arced).unwrap().write(f());
4848+4949+ // SAFETY: We have initialised the Arc correctly by writing to
5050+ // the memory in the line above.
5151+ unsafe { arced.assume_init() }
5252+}
5353+5454+#[cfg(test)]
5555+mod tests {
5656+ use super::*;
5757+5858+ #[test]
5959+ fn boxed_futures() {
6060+ let boxed = boxed_future_within(async || 42);
6161+6262+ assert_eq!(size_of_val(&boxed), 8);
6363+ }
6464+6565+ #[test]
6666+ fn arc_init() {
6767+ let arced = arc_within(|| 128u128);
6868+6969+ assert_ne!(size_of_val(&arced), 16);
7070+ assert_eq!(*arced, 128);
7171+ }
7272+7373+ #[test]
7474+ fn try_arc_init() {
7575+ #[derive(Debug, PartialEq, Eq)]
7676+ struct Errored;
7777+7878+ let arced: Result<Arc<u128>, Errored> = try_arc_within(|| Ok(128u128));
7979+8080+ assert_eq!(*arced.unwrap(), 128);
8181+8282+ let arced: Result<Arc<u128>, Errored> = try_arc_within(|| Err(Errored));
8383+8484+ assert_eq!(arced, Err(Errored));
8585+ }
8686+}
···11+//! Crate for parsing `Forwarded` header values, mostly only caring about the first (remotest)
22+//! `for=` value. Supports both IPv6 and IPv4 and is case insensitive.
33+44+use winnow::{
55+ ModalResult,
66+ ascii::{Caseless, space0},
77+ combinator::alt,
88+ stream::Stream,
99+ token::{literal, rest, take_until},
1010+};
1111+1212+pub use winnow::Parser;
1313+1414+/// Check if a header value string begins with `for=`, in order to
1515+/// determine whether it is a valid value for a Forwarded header, and
1616+/// is a part that we are interested in.
1717+fn match_for<'s>(prefix: &mut &'s str) -> ModalResult<&'s str> {
1818+ Caseless("for=").parse_next(prefix)
1919+}
2020+2121+/// Extracts the IPv6 address from the identifier string. Expects the format
2222+/// `"[::1]:8080"`. IPv6 addresses in the Forwarded header are always wrapped in `"`,
2323+/// with the address component wrapped in square brackets. The port component `:8080`
2424+/// may or may not be present in the identifier.
2525+fn extract_ipv6(identifier: &mut &str) -> ModalResult<Box<str>> {
2626+ literal('"').parse_next(identifier)?;
2727+ take_until(0.., '"').map(Into::into).parse_next(identifier)
2828+}
2929+3030+/// Extracts the IPv4 address from the identifier string. Expects the format
3131+/// `192.168.0.1:8080`. IPv4 addresses are not wrapped with `"` in contrast to IPv6
3232+/// addresses. The port component `:8080` may or may not be present in the identifier.
3333+fn extract_ipv4(identifier: &mut &str) -> ModalResult<Box<str>> {
3434+ rest.map(Into::into).parse_next(identifier)
3535+}
3636+3737+/// Extracts the identifier from the Forwarded for value. Attempts to parse the identifier part
3838+/// as either an IPv6 address or IPv4 address. The Forwarded for format supports more identifier
3939+/// types, but we discard those as they are useless to us.
4040+fn extract_identifier(identifier: &mut &str) -> ModalResult<Box<str>> {
4141+ alt((extract_ipv6, extract_ipv4)).parse_next(identifier)
4242+}
4343+4444+/// Extracts the identifier from the Forwarded for value. First it checks for the correct
4545+/// prefix `for=`, then attempts to extract the identifier.
4646+pub fn extract_for(header_part: &mut &str) -> ModalResult<Box<str>> {
4747+ space0(header_part)?;
4848+4949+ match_for(header_part)?;
5050+5151+ let id = extract_identifier(header_part)?;
5252+5353+ header_part.finish();
5454+5555+ Ok(id)
5656+}
5757+5858+#[cfg(test)]
5959+mod tests {
6060+ use super::*;
6161+6262+ #[test]
6363+ fn extracts_for_header_value() -> color_eyre::Result<()> {
6464+ assert_eq!(
6565+ extract_for
6666+ .parse("for=1.2.3.4")
6767+ .map_err(|a| color_eyre::eyre::eyre!("Identifier parsing error:\n{a}"))?,
6868+ Box::from("1.2.3.4")
6969+ );
7070+7171+ assert_eq!(
7272+ extract_for
7373+ .parse("fOr=1.2.3.4:1234")
7474+ .map_err(|a| color_eyre::eyre::eyre!("Identifier parsing error:\n{a}"))?,
7575+ Box::from("1.2.3.4:1234")
7676+ );
7777+7878+ assert_eq!(
7979+ extract_for
8080+ .parse(" fOR=1.2.3.4:1234")
8181+ .map_err(|a| color_eyre::eyre::eyre!("Identifier parsing error:\n{a}"))?,
8282+ Box::from("1.2.3.4:1234")
8383+ );
8484+8585+ assert_eq!(
8686+ extract_for
8787+ .parse("FOr=\"[::1]:1234\"")
8888+ .map_err(|a| color_eyre::eyre::eyre!("Identifier parsing error:\n{a}"))?,
8989+ Box::from("[::1]:1234")
9090+ );
9191+9292+ assert_eq!(
9393+ extract_for
9494+ .parse("FOR=\"[::1]\"")
9595+ .map_err(|a| color_eyre::eyre::eyre!("Identifier parsing error:\n{a}"))?,
9696+ Box::from("[::1]")
9797+ );
9898+9999+ Ok(())
100100+ }
101101+}
···11+use core::pin::Pin;
22+use std::time::Duration;
33+44+use nailconfig::NailConfig;
55+use nailrng::FastRng;
66+use rand::Rng;
77+use tokio::time::{Sleep, sleep};
88+99+use crate::boxed_future_within;
1010+1111+/// Apply a delay/sleep based from provided configuration. Either it provides a set
1212+/// minimum delay, or a randomised value sampled from a range of the minimum and maximum
1313+/// configured delays. If the delay value is `0`, this future will poll ready immediately
1414+/// and no sleep will be invoked.
1515+pub fn delay_output(config: &NailConfig) -> Option<Pin<Box<Sleep>>> {
1616+ let delay = match (config.generator.min_delay, config.generator.max_delay) {
1717+ (min_delay, None) => min_delay,
1818+ (min_delay, Some(max_delay)) => FastRng::default().random_range(min_delay..=max_delay),
1919+ };
2020+2121+ if delay > 0 {
2222+ Some(boxed_future_within(|| sleep(Duration::from_millis(delay))))
2323+ } else {
2424+ None
2525+ }
2626+}
+203
crates/nailgen/src/html_gen.rs
···11+use std::sync::Arc;
22+33+use axum::extract::MatchedPath;
44+use bytes::{Bytes, BytesMut};
55+use nailconfig::NailConfig;
66+use nailkov::{NailKov, interner::Interner};
77+use nailrng::FastRng;
88+use rand::{Rng, RngCore, distr::Alphanumeric, seq::IndexedRandom};
99+1010+/// Provides either the minimum configured size, or a randomised value between
1111+/// the minimum and maximum configured sizes if a maximum is available.
1212+#[inline]
1313+fn get_desired_size(config: &NailConfig, rng: &mut impl RngCore) -> usize {
1414+ match (
1515+ config.generator.min_paragraph_size,
1616+ config.generator.max_paragraph_size,
1717+ ) {
1818+ (min, None) => min,
1919+ (min, Some(max)) => rng.random_range(min..=max),
2020+ }
2121+}
2222+2323+/// Generates text from the markov chain, using the tokens it outputs to pull
2424+/// interned text from the interner.
2525+#[inline]
2626+pub fn text_generator<'a>(
2727+ interner: &'a Interner,
2828+ chain: &'a NailKov,
2929+ size: usize,
3030+ rng: &'a mut impl RngCore,
3131+) -> impl Iterator<Item = &'a u8> + 'a {
3232+ chain
3333+ .generate_tokens(rng)
3434+ .take(size)
3535+ // SAFETY: The id comes from the same interner that allocated it
3636+ .flat_map(|token| unsafe { interner.lookup(token).as_bytes() })
3737+ .skip_while(|&text| !text.is_ascii_alphabetic())
3838+}
3939+4040+#[inline]
4141+pub fn static_title<'a>(text: &'a str) -> impl Iterator<Item = &'a u8> + 'a {
4242+ text.lines()
4343+ .map(str::trim)
4444+ .next()
4545+ .into_iter()
4646+ .flat_map(str::as_bytes)
4747+}
4848+4949+#[inline]
5050+pub fn static_content<'a>(text: &'a str) -> impl Iterator<Item = &'a u8> + 'a {
5151+ text.lines()
5252+ .skip(1)
5353+ .filter_map(|line| {
5454+ let trimmed = line.trim();
5555+5656+ if line.is_empty() {
5757+ None
5858+ } else {
5959+ Some(trimmed.as_bytes())
6060+ }
6161+ })
6262+ .flat_map(|bytes| b"<p>".iter().chain(bytes).chain(b"</p>\n"))
6363+}
6464+6565+pub async fn initial_content(
6666+ buf_mut: BytesMut,
6767+ interner: Arc<Interner>,
6868+ chain: Arc<NailKov>,
6969+ config: Arc<NailConfig>,
7070+ mut rng: FastRng,
7171+) -> Bytes {
7272+ // Randomise how many initial paragraphs we want
7373+ let max_paras: u32 = rng.random_range(1..=3);
7474+7575+ (0..max_paras)
7676+ .fold(buf_mut, |mut acc, _| {
7777+ acc.extend(paragraph(
7878+ &interner,
7979+ &chain,
8080+ get_desired_size(&config, &mut rng),
8181+ &mut rng,
8282+ ));
8383+8484+ acc
8585+ })
8686+ .freeze()
8787+}
8888+8989+pub async fn main_content(
9090+ mut buffer: BytesMut,
9191+ interner: Arc<Interner>,
9292+ chain: Arc<NailKov>,
9393+ config: Arc<NailConfig>,
9494+ mut rng: FastRng,
9595+) -> Bytes {
9696+ buffer.reserve(config.generator.chunk_size * 2);
9797+9898+ loop {
9999+ buffer.extend(header(
100100+ &interner,
101101+ &chain,
102102+ config.generator.header_size,
103103+ &mut rng,
104104+ ));
105105+106106+ // Randomise how many paragraphs we want per section
107107+ let paragraphs = rng.random_range(1..=4);
108108+109109+ (0..paragraphs).for_each(|_| {
110110+ buffer.extend(paragraph(
111111+ &interner,
112112+ &chain,
113113+ get_desired_size(&config, &mut rng),
114114+ &mut rng,
115115+ ));
116116+ });
117117+118118+ // We can generate more before handing it off to be streamed to the client,
119119+ // A bit more latency, but much more throughput, and friendlier to being compressed.
120120+ if buffer.len() >= config.generator.chunk_size {
121121+ return buffer.freeze();
122122+ }
123123+124124+ // Yield to the runtime to allow other tasks a chance to run before we generate
125125+ // another chunk of data
126126+ futures_lite::future::yield_now().await;
127127+ }
128128+}
129129+130130+#[inline]
131131+pub fn extra(buf_mut: &mut BytesMut, config: &NailConfig, rng: &mut FastRng) -> usize {
132132+ let mut written = 0;
133133+134134+ if let Some(prompt) = match config.generator.prompts.len() {
135135+ 0 => None,
136136+ 1 => config.generator.prompts.first(),
137137+ _ => config.generator.prompts.choose(rng),
138138+ } {
139139+ buf_mut.extend(b"<p>".iter().chain(prompt.as_bytes()).chain(b"</p>"));
140140+141141+ written += prompt.len();
142142+ }
143143+144144+ written
145145+}
146146+147147+pub async fn footer(
148148+ mut buf_mut: BytesMut,
149149+ interner: Arc<Interner>,
150150+ chain: Arc<NailKov>,
151151+ path: MatchedPath,
152152+ config: Arc<NailConfig>,
153153+ mut rng: FastRng,
154154+) -> Bytes {
155155+ let path = path.as_str();
156156+157157+ let route = path.strip_suffix("/{*generated}").unwrap_or(path);
158158+159159+ let total_links = rng.random_range(1..=config.generator.max_pit_links);
160160+161161+ buf_mut.extend_from_slice(b"<nav style=\"visibility: hidden;\"><ul>");
162162+163163+ for _ in 1..=total_links {
164164+ buf_mut.extend(b"<li><a href=\"".iter().chain(route.as_bytes()).chain(b"/"));
165165+ buf_mut.extend((&mut rng).sample_iter(Alphanumeric).take(16));
166166+ buf_mut.extend(
167167+ b"\">"
168168+ .iter()
169169+ .chain(text_generator(&interner, &chain, 8, &mut rng))
170170+ .chain(b"</a></li>\n"),
171171+ );
172172+ }
173173+174174+ buf_mut.extend_from_slice(b"</ul></nav>");
175175+176176+ buf_mut.freeze()
177177+}
178178+179179+#[inline]
180180+fn paragraph<'a>(
181181+ interner: &'a Interner,
182182+ chain: &'a NailKov,
183183+ size: usize,
184184+ rng: &'a mut impl RngCore,
185185+) -> impl Iterator<Item = &'a u8> + 'a {
186186+ b"<p>"
187187+ .iter()
188188+ .chain(text_generator(interner, chain, size, rng))
189189+ .chain(b"</p>\n")
190190+}
191191+192192+#[inline]
193193+fn header<'a>(
194194+ interner: &'a Interner,
195195+ chain: &'a NailKov,
196196+ size: usize,
197197+ rng: &'a mut impl RngCore,
198198+) -> impl Iterator<Item = &'a u8> + 'a {
199199+ b"\n<h2>"
200200+ .iter()
201201+ .chain(text_generator(interner, chain, size, rng))
202202+ .chain(b"</h2>\n")
203203+}
···11+//! [`TokenWeights`] are representations of how common [`Token`]s are, and are paired up with
22+//! a [`TokenPair`](crate::token::TokenPair) in a [`NailKov`](crate::NailKov).
33+44+use indexmap::IndexMap;
55+use rand::Rng;
66+use rand_distr::{Distribution, weighted::WeightedAliasIndex};
77+88+use crate::{RandomState, error::NailError, token::Token};
99+1010+/// A distribution of choices and their likelihood.
1111+#[derive(Clone, Debug)]
1212+pub struct TokenWeights {
1313+ /// Mappings of choice indexes to their likelihood.
1414+ dist: WeightedAliasIndex<u32>,
1515+ /// The actual choices
1616+ choices: Box<[Token]>,
1717+}
1818+1919+impl Distribution<Token> for TokenWeights {
2020+ #[inline(always)]
2121+ fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Token {
2222+ // SAFETY: The sampled index from `dist` will always correspond to a valid
2323+ // token in the `choices` slice.
2424+ unsafe { *self.choices.get_unchecked(self.dist.sample(rng)) }
2525+ }
2626+}
2727+2828+/// Builder for [`TokenWeights`].
2929+#[derive(Clone, Debug)]
3030+pub struct TokenWeightsBuilder {
3131+ /// Counts how many times a token is likely to appear.
3232+ occurrences: IndexMap<Token, u32, RandomState>,
3333+}
3434+3535+impl TokenWeightsBuilder {
3636+ pub fn new(hasher: RandomState) -> Self {
3737+ Self {
3838+ occurrences: IndexMap::with_hasher(hasher),
3939+ }
4040+ }
4141+4242+ /// Creates a weighted distribution for the likelihood of tokens to appear.
4343+ pub fn build(self) -> Result<TokenWeights, NailError> {
4444+ let (choices, counts): (Vec<_>, Vec<_>) = self.occurrences.into_iter().unzip();
4545+4646+ if choices.is_empty() {
4747+ return Err(NailError::EmptyInput);
4848+ }
4949+5050+ Ok(TokenWeights {
5151+ dist: WeightedAliasIndex::new(counts)?,
5252+ choices: choices.into(),
5353+ })
5454+ }
5555+5656+ /// Count an occurrence of this token, or add it if it hasn't been seen before.
5757+ pub fn add(&mut self, token: Token) {
5858+ self.occurrences
5959+ .entry(token)
6060+ .and_modify(|count| *count += 1)
6161+ .or_insert(1);
6262+ }
6363+}
6464+6565+impl Default for TokenWeightsBuilder {
6666+ fn default() -> Self {
6767+ Self::new(RandomState::new())
6868+ }
6969+}
···11+use hashbrown::{Equivalent, HashMap};
22+use rapidhash::fast::RandomState;
33+44+use crate::token::Token;
55+66+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77+#[repr(transparent)]
88+struct StringPtr(*const str);
99+1010+impl StringPtr {
1111+ #[inline(always)]
1212+ const fn cast(&self) -> &str {
1313+ // SAFETY: The pointer is stable as it points to memory that is never
1414+ // moved/invalidated while this struct lives, therefore can be safely
1515+ // dereferenced back to a string slice. We own the String instance this
1616+ // references, and all StringPtrs are used within the same scope as the
1717+ // String instances, so when String drops, these will be dropped too.
1818+ unsafe { &*self.0 }
1919+ }
2020+}
2121+2222+impl core::hash::Hash for StringPtr {
2323+ #[inline]
2424+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
2525+ self.cast().hash(state);
2626+ }
2727+}
2828+// SAFETY: StringPtr contains a ptr to the heap, that is never moved or invalidated
2929+// while Interner lives, and all instances of StringPtr live as long as Interner.
3030+// Since the String type is `Send`, so is StringPtr
3131+unsafe impl Send for StringPtr {}
3232+// SAFETY: StringPtr contains a ptr to the heap, that is never moved or invalidated
3333+// while Interner lives, and all instances of StringPtr live as long as Interner.
3434+// Since the String type is `Sync`, so is StringPtr
3535+unsafe impl Sync for StringPtr {}
3636+3737+#[derive(Debug, Clone)]
3838+pub struct Interner {
3939+ collected: HashMap<StringPtr, Token, RandomState>,
4040+ index: Vec<StringPtr>,
4141+ buffer: String,
4242+ stored: Vec<String>,
4343+}
4444+4545+impl Default for Interner {
4646+ fn default() -> Self {
4747+ Self::with_capacity(256)
4848+ }
4949+}
5050+5151+impl Interner {
5252+ /// # Safety
5353+ /// The caller must ensure that the [`Token`] being passed in was allocated
5454+ /// from the same [`Interner`] instance.
5555+ #[inline(always)]
5656+ pub unsafe fn lookup(&self, id: Token) -> &str {
5757+ // SAFETY: Safety is upheld by the caller ensuring the id was allocated
5858+ // from the same interner.
5959+ unsafe { self.index.get_unchecked(id.index()).cast() }
6060+ }
6161+6262+ pub fn with_capacity(cap: usize) -> Interner {
6363+ // This will get us just under 64KiB of interned storage before we
6464+ // need to allocate more space for buffer storage.
6565+ let stored = Vec::with_capacity(8);
6666+6767+ Interner {
6868+ collected: HashMap::with_hasher(RandomState::new()),
6969+ index: Vec::new(),
7070+ stored,
7171+ buffer: String::with_capacity(cap.next_power_of_two()),
7272+ }
7373+ }
7474+7575+ pub fn intern(&mut self, text: &str) -> Token {
7676+ if let Some(&id) = self.collected.get(text) {
7777+ return id;
7878+ }
7979+8080+ // SAFETY: `alloc`` is never called elsewhere, nor the properties it controls
8181+ // are modified outside of the method. Here we get a new StringPtr for `text` that
8282+ // hasn't been stored before.
8383+ let name = unsafe { self.alloc(text) };
8484+ let id = Token::new(self.index.len() as u32);
8585+ self.collected.insert(name, id);
8686+ self.index.push(name);
8787+8888+ // SAFETY: We are using the id allocated within the same function scope,
8989+ // so it is always from the same source.
9090+ unsafe {
9191+ debug_assert!(self.lookup(id).equivalent(&name));
9292+ }
9393+ debug_assert!(self.intern(name.cast()) == id);
9494+9595+ id
9696+ }
9797+9898+ /// Allocates a new [`StringPtr`] for the given string input. If there is no more room
9999+ /// in the current buffer, it allocates a new buffer and creates the StringPtr to reference
100100+ /// the stored string in the new buffer, storing the old one.
101101+ ///
102102+ /// # Safety
103103+ ///
104104+ /// The caller must ensure that `self.buffers` and `self.active` are never modified elsewhere,
105105+ /// and that this is called only for new instances of `text`.
106106+ unsafe fn alloc(&mut self, text: &str) -> StringPtr {
107107+ let capacity = self.buffer.capacity();
108108+109109+ if capacity < self.buffer.len() + text.len() {
110110+ // If we ran out of capacity in our storage, allocate a new buffer with
111111+ // larger capacity.
112112+ let new_cap = (capacity.max(text.len()) + 1).next_power_of_two();
113113+ let old_buf = core::mem::replace(&mut self.buffer, String::with_capacity(new_cap));
114114+115115+ self.stored.push(old_buf);
116116+ }
117117+118118+ // Construct raw str slice to eliminate lifetime tracking as we manage its
119119+ // lifetime within the Interner instance.
120120+ let interned = {
121121+ let start = self.buffer.len();
122122+ self.buffer.push_str(text);
123123+124124+ &raw const self.buffer[start..]
125125+ };
126126+127127+ StringPtr(interned)
128128+ }
129129+}
130130+131131+impl Equivalent<StringPtr> for str {
132132+ #[inline(always)]
133133+ fn equivalent(&self, key: &StringPtr) -> bool {
134134+ key.cast().eq(self)
135135+ }
136136+}
137137+138138+#[cfg(test)]
139139+mod tests {
140140+ use super::*;
141141+142142+ #[test]
143143+ fn string_ptr_comparisons() {
144144+ let one = "one";
145145+ let two = "two";
146146+147147+ let one_ptr = StringPtr(one);
148148+ let two_ptr = StringPtr(two);
149149+150150+ assert_ne!(one_ptr, two_ptr);
151151+152152+ assert!(one.equivalent(&one_ptr));
153153+ }
154154+155155+ #[test]
156156+ fn is_able_to_intern_one_string() {
157157+ let mut interner = Interner::default();
158158+159159+ assert!(interner.buffer.is_empty());
160160+161161+ let text = "Lorem ipsum";
162162+163163+ let id = interner.intern(text);
164164+165165+ // SAFETY: It comes from the same source
166166+ unsafe {
167167+ assert_eq!(text, interner.lookup(id));
168168+ }
169169+ assert_eq!(interner.buffer.len(), 11);
170170+171171+ let again = interner.intern(text);
172172+173173+ assert_eq!(id, again);
174174+ assert_eq!(interner.buffer.len(), 11);
175175+ }
176176+177177+ #[test]
178178+ fn is_able_to_intern_many_strings() {
179179+ let mut interner = Interner::with_capacity(32);
180180+181181+ let texts = [
182182+ "Lorem ipsum",
183183+ "dolor sit amet",
184184+ "duplicated",
185185+ "Other text",
186186+ "Elevenses",
187187+ "duplicated",
188188+ "Gibberish",
189189+ ];
190190+191191+ let interned: Vec<Token> = texts.iter().map(|&text| interner.intern(text)).collect();
192192+193193+ assert_eq!(
194194+ interned.as_slice(),
195195+ &[
196196+ Token::new(0),
197197+ Token::new(1),
198198+ Token::new(2),
199199+ Token::new(3),
200200+ Token::new(4),
201201+ Token::new(2),
202202+ Token::new(5)
203203+ ]
204204+ );
205205+ assert_eq!(interner.buffer.capacity(), 64);
206206+ assert_eq!(interner.stored.len(), 1);
207207+ assert_eq!(interner.stored[0].capacity(), 32);
208208+ }
209209+210210+ #[test]
211211+ fn is_thread_safe() {
212212+ let mut interner = Interner::with_capacity(32);
213213+214214+ let texts = [
215215+ "Lorem ipsum",
216216+ "dolor sit amet",
217217+ "duplicated",
218218+ "Other text",
219219+ "Elevenses",
220220+ "duplicated",
221221+ "Gibberish",
222222+ ];
223223+224224+ let interned: Vec<Token> = texts.iter().map(|&text| interner.intern(text)).collect();
225225+226226+ std::thread::scope(|s| {
227227+ s.spawn(move || {
228228+ for (id, expected) in interned.into_iter().zip(texts) {
229229+ // SAFETY: It comes from the same source
230230+ unsafe {
231231+ assert_eq!(expected, interner.lookup(id));
232232+ }
233233+ }
234234+ });
235235+ });
236236+ }
237237+}
···11+//! A very fast, user-space RNG source in the same vein as `rand`'s `ThreadRng`. Not cryptographically secure,
22+//! is meant to be a very fast entropy source.
33+44+use std::cell::UnsafeCell;
55+66+use rand_core::RngCore;
77+use wyrand::WyRand;
88+99+thread_local! {
1010+ static SOURCE: UnsafeCell<WyRand> = UnsafeCell::new(WyRand::new(getrandom::u64().expect("Failed to source entropy")))
1111+}
1212+1313+pub struct FastRng(WyRand);
1414+1515+impl FastRng {
1616+ #[inline]
1717+ pub fn fork(&mut self) -> Self {
1818+ Self(WyRand::new(self.next_u64()))
1919+ }
2020+}
2121+2222+impl Default for FastRng {
2323+ fn default() -> Self {
2424+ SOURCE.with(|source| {
2525+ // SAFETY: Dereferencing this cell is safe as the value has
2626+ // been initialised, so it will not be null, and the mut reference
2727+ // we create here only lives as long as this function's scope. Since
2828+ // this is thread local, there is only one mut reference alive at any
2929+ // given moment.
3030+ let ptr = unsafe { &mut *source.get() };
3131+3232+ FastRng(WyRand::new(ptr.rand()))
3333+ })
3434+ }
3535+}
3636+3737+impl RngCore for FastRng {
3838+ #[inline(always)]
3939+ fn next_u32(&mut self) -> u32 {
4040+ self.0.next_u32()
4141+ }
4242+4343+ #[inline(always)]
4444+ fn next_u64(&mut self) -> u64 {
4545+ self.0.next_u64()
4646+ }
4747+4848+ #[inline(always)]
4949+ fn fill_bytes(&mut self, dst: &mut [u8]) {
5050+ self.0.fill_bytes(dst);
5151+ }
5252+}
···11+use std::borrow::Cow;
22+33+use axum::{
44+ Extension,
55+ body::{Body as AxumBody, Bytes},
66+ extract::{MatchedPath, Request},
77+ http::HeaderValue,
88+ middleware::Next,
99+ response::Response,
1010+};
1111+use hyper::{
1212+ HeaderMap, Uri, Version,
1313+ body::Body,
1414+ header::{CONTENT_ENCODING, CONTENT_TYPE, USER_AGENT},
1515+};
1616+use nailip::{IdentifiedPeer, header_value_to_str};
1717+use opentelemetry::Context;
1818+use opentelemetry_http::HeaderExtractor;
1919+use opentelemetry_semantic_conventions::{
2020+ attribute::OTEL_STATUS_CODE,
2121+ trace::{ERROR_TYPE, HTTP_RESPONSE_STATUS_CODE},
2222+};
2323+use tracing::{Span, field::Empty, info_span};
2424+use uuid::Uuid;
2525+2626+pub fn extract_context(headers: &HeaderMap) -> Context {
2727+ opentelemetry::global::get_text_map_propagator(|propagator| {
2828+ propagator.extract(&HeaderExtractor(headers))
2929+ })
3030+}
3131+3232+#[inline]
3333+pub fn url_scheme(uri: &Uri) -> &str {
3434+ uri.scheme_str().unwrap_or_default()
3535+}
3636+3737+#[inline]
3838+#[must_use]
3939+pub fn http_flavor(version: Version) -> Cow<'static, str> {
4040+ match version {
4141+ Version::HTTP_09 => "0.9".into(),
4242+ Version::HTTP_10 => "1.0".into(),
4343+ Version::HTTP_11 => "1.1".into(),
4444+ Version::HTTP_2 => "2.0".into(),
4545+ Version::HTTP_3 => "3.0".into(),
4646+ other => format!("{other:?}").into(),
4747+ }
4848+}
4949+5050+pub async fn trace_connection_layer(
5151+ identified: Extension<IdentifiedPeer>,
5252+ req: Request,
5353+ next: Next,
5454+) -> Response<InspectBody<AxumBody>> {
5555+ use tracing_opentelemetry::OpenTelemetrySpanExt;
5656+5757+ let headers = req.headers();
5858+5959+ let request_id = headers.get("x-request-id").cloned().unwrap_or_else(
6060+ // SAFETY: The UUID is converted to a valid UTF-8 string before being turned into
6161+ // Bytes. As such, the Bytes instance corresponds to a valid internal repr for
6262+ // HeaderValue, meaning we can skip validation directly.
6363+ || unsafe {
6464+ HeaderValue::from_maybe_shared_unchecked(Bytes::from(Uuid::now_v7().to_string()))
6565+ },
6666+ );
6767+6868+ let path = req
6969+ .extensions()
7070+ .get::<MatchedPath>()
7171+ .map_or("not-matched", MatchedPath::as_str);
7272+7373+ let http_method = req.method().as_str();
7474+7575+ let root_name = format!("{http_method} {path}");
7676+7777+ let mut peer = identified.peer().split(":");
7878+7979+ let span = info_span!(
8080+ "HTTP request",
8181+ http.request.method = %http_method,
8282+ http.route = path, // to set by router of "webframework" after
8383+ network.protocol.version = %http_flavor(req.version()),
8484+ client.address = Empty,
8585+ client.port = Empty,
8686+ user_agent.original = headers
8787+ .get(USER_AGENT)
8888+ .and_then(header_value_to_str)
8989+ .unwrap_or("None"),
9090+ http.response.status_code = Empty, // to set on response
9191+ http.response.header.content_encoding = Empty,
9292+ http.response.header.content_type = Empty,
9393+ url.path = req.uri().path(),
9494+ url.query = req.uri().query(),
9595+ http.scheme = url_scheme(req.uri()),
9696+ otel.name = root_name, // to set by router of "webframework" after
9797+ otel.kind = "server",
9898+ otel.status_code = Empty, // to set on response
9999+ trace_id = Empty, // to set on response
100100+ http.request.header.request_id = Empty, // to set
101101+ error.type = Empty,
102102+ );
103103+104104+ if let Some(address) = peer.next() {
105105+ span.record("client.address", address);
106106+ }
107107+108108+ if let Some(port) = peer.next() {
109109+ span.record("client.port", port);
110110+ }
111111+112112+ if let Some(request_id) = header_value_to_str(&request_id) {
113113+ span.record("http.request.header.request_id", request_id);
114114+ }
115115+116116+ let _ = span.set_parent(extract_context(headers));
117117+118118+ let inner = span.in_scope(|| next.run(req));
119119+120120+ let response = InspectHttpResponse {
121121+ inner,
122122+ span: InspectState::Ready { span, request_id },
123123+ };
124124+125125+ response.await
126126+}
127127+128128+enum InspectState {
129129+ Ready { span: Span, request_id: HeaderValue },
130130+ Finished,
131131+}
132132+133133+impl InspectState {
134134+ #[inline]
135135+ fn span_ref(&self) -> &Span {
136136+ match self {
137137+ Self::Ready { span, .. } => span,
138138+ Self::Finished => unreachable!("Invalid state, future was polled after completion"),
139139+ }
140140+ }
141141+142142+ #[inline]
143143+ fn take(&mut self) -> (Span, HeaderValue) {
144144+ let span = core::mem::replace(self, Self::Finished);
145145+146146+ match span {
147147+ Self::Ready { span, request_id } => (span, request_id),
148148+ Self::Finished => unreachable!("Invalid state, future was polled after completion"),
149149+ }
150150+ }
151151+}
152152+153153+pin_project_lite::pin_project! {
154154+ struct InspectHttpResponse<F> {
155155+ #[pin]
156156+ inner: F,
157157+ span: InspectState,
158158+ }
159159+}
160160+161161+pin_project_lite::pin_project! {
162162+ #[doc(hidden)]
163163+ pub struct InspectBody<B> {
164164+ #[pin]
165165+ body: B,
166166+ span: Span,
167167+ }
168168+}
169169+170170+impl<F> core::future::Future for InspectHttpResponse<F>
171171+where
172172+ F: core::future::Future<Output = Response>,
173173+{
174174+ type Output = Response<InspectBody<AxumBody>>;
175175+176176+ #[inline]
177177+ fn poll(
178178+ self: core::pin::Pin<&mut Self>,
179179+ cx: &mut core::task::Context<'_>,
180180+ ) -> core::task::Poll<Self::Output> {
181181+ let this = self.project();
182182+183183+ let span = this.span.span_ref();
184184+185185+ let poll = span.in_scope(|| this.inner.poll(cx));
186186+187187+ if let core::task::Poll::Ready(mut response) = poll {
188188+ let status = response.status();
189189+ let headers = response.headers();
190190+191191+ span.record(HTTP_RESPONSE_STATUS_CODE, status.as_u16());
192192+193193+ if let Some(encoding) = headers.get(CONTENT_ENCODING).and_then(header_value_to_str) {
194194+ span.record("http.response.header.content_encoding", encoding);
195195+ }
196196+197197+ if let Some(content_type) = headers.get(CONTENT_TYPE).and_then(header_value_to_str) {
198198+ span.record("http.response.header.content_type", content_type);
199199+ }
200200+201201+ if status.is_client_error() || status.is_server_error() {
202202+ span.record(ERROR_TYPE, status.as_u16());
203203+ }
204204+205205+ if status.is_server_error() {
206206+ span.record(OTEL_STATUS_CODE, "ERROR");
207207+ } else {
208208+ span.record(OTEL_STATUS_CODE, "OK");
209209+ }
210210+211211+ let (span, request_id) = this.span.take();
212212+213213+ response.headers_mut().insert("x-request-id", request_id);
214214+215215+ core::task::Poll::Ready(response.map(|body| InspectBody { body, span }))
216216+ } else {
217217+ core::task::Poll::Pending
218218+ }
219219+ }
220220+}
221221+222222+impl<B> Body for InspectBody<B>
223223+where
224224+ B: Body,
225225+{
226226+ type Data = B::Data;
227227+ type Error = B::Error;
228228+229229+ #[inline(always)]
230230+ fn poll_frame(
231231+ self: core::pin::Pin<&mut Self>,
232232+ cx: &mut core::task::Context<'_>,
233233+ ) -> core::task::Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> {
234234+ let this = self.project();
235235+236236+ this.span.in_scope(|| this.body.poll_frame(cx))
237237+ }
238238+}
+101
defaults/pit.default.toml
···11+[server]
22+# Define route entry points for the tarpit. By default, it is the root, but can
33+# include more directories, or the root be excluded for other paths.
44+pit_routes = ["/"]
55+66+# The socket address the nailpit listens on
77+socket_addr = "0.0.0.0:3000"
88+99+# The amount of worker threads dedicated to the tarpit. Generating larger payloads
1010+# will benefit from more threads to balance the generation load better.
1111+worker_threads = 1
1212+1313+[generator]
1414+# Input text files to feed the Markov Chain. Uses glob format. Multiple files that are
1515+# included will be turned into multiple different chains, so generated pages have randomised
1616+# garbage content to appear different during navigation. The more text provided the better.
1717+input_files = "input/*.txt"
1818+1919+# The template file for the warning/entry page. A valid warning template will only use {{ title }},
2020+# {{ main }} and {{ footer }} placeholders.
2121+warning_template = "templates/warning.html"
2222+# The content to be rendered in the warning page. Expects plain text, and the first line is rendered as
2323+# the title. All other text that is separated by line-breaks are rendered as paragraphs.
2424+warning_message = "templates/message.txt"
2525+2626+# The template file for generated pages. A valid generation template can use all available placeholder types.
2727+generated_template = "templates/generated.html"
2828+2929+# Minimum amount of words per generated paragraph.
3030+min_paragraph_size = 128
3131+# Maximum amount of words per generated paragraph.
3232+max_paragraph_size = 256
3333+3434+# Maximum amount of links to be rendered in the footer to allow crawlers go deeper into the tarpit.
3535+# Acts as a form of staggering concurrency, so crawlers don't immediately open hundreds of connections.
3636+max_pit_links = 5
3737+3838+# Maximum amount of characters in generated headers.
3939+header_size = 32
4040+4141+# Amount of generated content in Kilobytes to be generated before the page completes. The smaller the payload,
4242+# the faster the generation, but the bigger the payload, the more resource pressure it applies to web crawlers.
4343+# Pages are compressed as they are streamed to the client however, so over the wire, this will be smaller.
4444+payload_size = 32
4545+4646+# Maximum amount of time for a connection to stay alive before being dropped. If configuring for a slow loris
4747+# attack, you might want to increase this value depending on how much you are delaying your page generation and
4848+# how big the pages are.
4949+timeout = 30
5050+# Minimum amount of delay per generation loop. Used to configure tarpit for slow loris type attacks.
5151+min_delay = 0
5252+# Maximum amount of delay per generation loop. Used to configure tarpit for slow loris type attacks.
5353+# Greater variance between min and max delays creates less predictable delay patterns to disguise the
5454+# attack
5555+max_delay = 0
5656+5757+# Size of chunk in bytes to be generated before being streamed to the client. This is for adjusting
5858+# throughput/latency characteristics of page generation and memory usage characteristics. This setting
5959+# should be adjusted according to hardware characteristics, but the value below is a fair default if you
6060+# want to have high throughput. Slow loris attack setups might want to tweak this value to be lower in
6161+# order to drip feed smaller portions of content to the client.
6262+chunk_size = 8192
6363+6464+# Adds additional text to a page post generation loop (but before the footer links), useful for
6565+# adding prompts or static content. More than one bit of static content added here is randomly chosen
6666+# for rendering on a given generated page.
6767+prompts = []
6868+6969+[rate_limiting]
7070+# The kind of rate limiting you want enabled. Options are `no_limit`, `soft_limit` (which introduces a delay
7171+# to when the content generation starts if hit by too many), `hard_limit` (which drops the connection if too many
7272+# requests are made), `soft_with_hard_limit` (which combines the two soft and hard modes, delaying at first to then
7373+# dropping the request after still too many requests).
7474+type = "soft_limit"
7575+# The amount of requests needed to hit the soft limiting state. This resets if it hasn't received a request from
7676+# a client in more than two minutes.
7777+soft_limit = 200
7878+# The delay applied to soft limited clients. The delay is in milliseconds.
7979+soft_delay = 600
8080+# The amount of requests need to hit the hard limiting state. This setting only takes effect if `hard_limit` is set
8181+# on the `type` option. If the type option is set to `soft_with_hard_limit`, it is recommended to ensure this value
8282+# is always greater than the `soft_limit` amount.
8383+hard_limit = 300
8484+# If `hard_limit` or `soft_with_hard_limit` is set, then the connection dropping mechanics are set via
8585+# `drop_behavior`. By default, it is set to `normal` mode, which just terminates with connection with a RATE_LIMITED
8686+# HTTP status code. If you set to `spicy`, then you have an additional option: `payload`. `payload` accepts a list of
8787+# strings, which are paths to static compressed files you can send back to the client. It will only accept gzip and
8888+# brotli compressed files. I don't have to explain why you want statically compressed 'spicy' files to be sent over the wire ;)
8989+drop_behavior = { mode = "normal" }
9090+# drop_behavior = { mode = "spicy", payload = ["spicy.gz", "spicy.br"] }
9191+9292+[open_telemetry]
9393+# The OTEL collector address & port for sending OTEL logs + traces to.
9494+endpoint = "http://127.0.0.1:4317"
9595+# The service name that will be used for OTEL logs and trace spans.
9696+service_name = "nailpit"
9797+# Enable logging to OTEL collector
9898+logs = false
9999+# Enable collecting trace data to OTEL collector. This option imposes a significant overhead, so only
100100+# enable it if you have the capacity for storing the data, which can be a lot during heavy traffic.
101101+traces = false
···11+Private Area
22+33+If you've reached this page, then go back, do not go further. You have been warned.
44+55+There is nothing here of substance, nothing to meaningful to read, nothing of importance or note.
66+77+Here is the entry point for the Nail Pit. Within, there's a never-ending labyrinth of nonsense, chaos and malicious intent, though mostly rusty nails. Proceeding further will likely put your machine/browser at risk of shenanigans relating to memory usage with the intent on causing your computer to go OOM and crash.
88+99+The only reason you'd continue further is if you are a curious soul, investigating the nature of this pit for research purposes, or you are not a human and cannot comprehend this warning, automated to crawl and scrape everything it can find, consequences be damned.
1010+1111+Do not go further. Do not reveal the secret doors hidden within this warning. Step back from the precipice of the abyss and return home.
1212+1313+You have been warned.