PNG  IHDR!@ PLTE>O`jqv JtEXtPage
First - metalympiada
git clone git://metalympiada.org/
Log | Files | README | LICENSE

commit 5f07bdfa4b4814acce4a06f7689601d6c859421c
Author: Metalympiáda <metalympiada@matfyz.cz>
Date:   Mon, 24 Oct 2022 10:35:44 +0200

First

Diffstat:
A.gitignore | 5+++++
ALICENSE | 661+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AMakefile | 14++++++++++++++
AREADME | 19+++++++++++++++++++
Aassets.scm | 91+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acookie.scm | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adb.scm | 110+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Adb.sql | 15+++++++++++++++
Amain.scm | 4++++
Apngenerator.c | 97+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Apngenerator.scm | 15+++++++++++++++
Aroutes.scm | 222+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asodium.scm | 137+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Asqlite3.scm | 565+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Astagit.c | 1297+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Astyle.scm | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Atexts/problems | 27+++++++++++++++++++++++++++
Atexts/rules | 17+++++++++++++++++
18 files changed, 3583 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,5 @@ +pngenerator.so +meta.sqlite +.SECRET +stagit +.stagit diff --git a/LICENSE b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + Metalympiáda + Copyright (C) 2022 + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>. diff --git a/Makefile b/Makefile @@ -0,0 +1,14 @@ +export GUILE_LOAD_PATH = . +export LTDL_LIBRARY_PATH = . + +run: pngenerator.so meta.sqlite stagit + guile main.scm + +pngenerator.so: pngenerator.c + ${CC} $^ -fPIC -lpng -shared -Ofast -ffast-math -march=native -Wpedantic -Wall -Wextra -o $@ + +meta.sqlite: db.sql + sqlite3 $@ < $^ + +stagit: stagit.c + ${CC} $^ -lgit2 -Ofast -flto -march=native -Wpedantic -Wall -Wextra -o $@ diff --git a/README b/README @@ -0,0 +1,19 @@ +Dependecies +----------- +- GNU Guile +- C compiler +- libc +- libpng +- libsodium +- sqlite3 +- libgit2 + +Build and run +------------- +$ make + +Contribute +---------- +Submit issues to metalympiada@matfyz.cz +Also, if you make a patch, you can send it there +via git send-email: https://git-send-email.io diff --git a/assets.scm b/assets.scm @@ -0,0 +1,91 @@ +(define-module (assets) + #:export (text-logo logo style problems rules-text stagit-sources)) +(use-modules (srfi srfi-1) + (style) + (sxml simple) + (ice-9 textual-ports) + (ice-9 ftw)) + +(define text-logo " + __ ___ __ __ _ __ __ + / |/ /__ / /_____ / /_ ______ ___ ____ (_)_/_/ ____/ /___ + / /|_/ / _ \\/ __/ __ `/ / / / / __ `__ \\/ __ \\/ / __ `/ __ / __ `/ + / / / / __/ /_/ /_/ / / /_/ / / / / / / /_/ / / /_/ / /_/ / /_/ / +/_/ /_/\\___/\\__/\\__,_/_/\\__, /_/ /_/ /_/ ,___/_/\\__,_/\\__,_/\\__,_/ + /____/ /_/ + OLYMPIÁDA O METALYMPIÁDE" +) + +(define (list->css lst delimiter) + (let ((to-string (lambda (v) (cond ((string? v) v) + ((number? v) (number->string v)) + ((list? v) (list->css v delimiter))))) + (first (car lst))) + (if (symbol? first) + (string-append (symbol->string first) + "(" + (if (null? (cdr lst)) "" (list->css (cdr lst) ",")) + ")") + (fold (lambda (n so-far) (string-append so-far delimiter (to-string n))) + (to-string first) + (cdr lst))))) + +(define (prop->css prop so-far) + (string-append so-far (symbol->string (car prop)) ":" (list->css (cdr prop) " ") ";")) + +(define (sexp->css style) + (let* ((style-rule + (lambda (source so-far) + (let* ((name (car source)) + (rest (cdr source)) + (first-name (caar rest)) + (first-prop (cdar rest))) + (if (eq? name '@) + (string-append so-far "@" (symbol->string first-name) + " " (list->css first-prop " ") "{" + (sexp->css (cdr rest)) "}") + (if (eq? first-name ':) + (string-append so-far (symbol->string name) + ":" (list->css first-prop " ") "{" + (fold prop->css "" (cdr rest)) "}") + (string-append so-far (symbol->string name) "{" + (fold prop->css "" rest) "}"))))))) + (fold style-rule "" style))) + +(define style (sexp->css stylesheet)) + +(define (logo-generator height ratio iterations) + (let ((width (* height ratio))) + `(svg (@ (class "logo") (aria-hidden "true") + (viewBox ,(list->css `(0 0 ,width ,height) " "))) + ,@(map (lambda (i) (let* ((r (expt ratio i)) + (w (* width r)) + (h (* height r)) + (x (/ (- width w) 2))) + `(rect (@ (x ,x) (y ,x) (width ,w) (height ,h))))) + (iota iterations))))) + +(define logo (logo-generator 500 logo-ratio 11)) + +(define problems (string-split (call-with-input-file "texts/problems" get-string-all) + #\~)) + +(define rules-text (call-with-input-file "texts/rules" get-string-all)) + +(define stagit-dir ".stagit") + +(define stagit-sources (make-hash-table)) + +(begin (if (not (file-exists? stagit-dir)) + (mkdir stagit-dir)) + (chdir stagit-dir) + (system "../stagit ..") + (chdir "..")) + +(ftw stagit-dir + (lambda (name statinfo flag) + (if (equal? flag 'regular) + (hash-set! stagit-sources + (substring name (+ (string-length stagit-dir) 1)) + (cdr (xml->sxml (call-with-input-file name get-string-all))))) + #t)) diff --git a/cookie.scm b/cookie.scm @@ -0,0 +1,126 @@ +;;; guile-webutils -- Web application utilities for Guile +;;; Copyright © 2016 Christopher Allan Webber <cwebber@dustycloud.org> +(define-module (cookie) + #:export (set-cookie delete-cookie)) +(use-modules (srfi srfi-1) + (srfi srfi-19) + (srfi srfi-26) + (ice-9 control) + (ice-9 match) + (web http)) + +(define cookie-val-char-set + (char-set-difference (char-set-delete char-set:ascii #\, #\;) + char-set:iso-control)) + +(define cookie-name-char-set + (char-set-delete cookie-val-char-set #\=)) + +(define (parse-cookie cookie-text) + (let ((parts (string-split cookie-text #\;))) + (define (split-cookie-pair cookie-pair) + (let* ((trimmed (string-trim cookie-pair)) + (delim (string-index trimmed #\=)) + (attrib (if delim + (substring trimmed 0 delim) + trimmed)) + (val (if delim + (substring trimmed (+ delim 1)) + #t))) + (cons attrib val))) + (map split-cookie-pair parts))) + +(define (date->http-date-string date) + (call-with-output-string (cut (@@ (web http) write-date) date <>))) + +(define (write-cookie cookie-alist port) + (let ((cookie-str + (string-join + (map (match-lambda + ((name . (? string? val)) + (string-append name "=" val)) + ((name . (? date? val)) + (string-append name "=" (date->http-date-string val))) + ((name . #t) + name)) + cookie-alist) + "; "))) + (display cookie-str port))) + +(define (valid-cookie-name? str) + (and (string? str) + (string-every cookie-name-char-set str))) + +(define (valid-cookie-val? str) + (or (eq? str #t) + (and (string? str) + (string-every cookie-val-char-set str)) + (date? str))) + +(define (validate-cookie cookie-alist) + (match cookie-alist + ((((? valid-cookie-name? name) . (or #t (? valid-cookie-val? _))) ...) + #t) + (_ #f))) + +(declare-header! "Cookie" + parse-cookie validate-cookie write-cookie) + +(define (parse-set-cookie str) + (match (parse-cookie str) + (((name . val) attrs ...) + (list name val attrs)))) + +(define (validate-set-cookie obj) + (match obj + ((name val (attrs ...)) + (validate-cookie + (cons (cons name val) + attrs))) + (_ #f))) + +(define (write-set-cookie obj port) + (match obj + ((name val (attrs ...)) + (write-cookie + (cons (cons name val) + attrs) + port)))) + +(declare-header! "Set-Cookie" + parse-set-cookie validate-set-cookie write-set-cookie + #:multiple? #t) + +(define* (set-cookie name #:optional (val "") + #:key expires max-age domain + path secure http-only + (extensions '())) + (define (maybe-append name val) + (lambda (prev) + (if val + (cons (cons name val) + prev) + prev))) + (define basic-prop-alist + ((compose + (maybe-append "Expires" expires) + (maybe-append "Max-Age" max-age) + (maybe-append "Domain" domain) + (maybe-append "Path" path) + (maybe-append "Secure" secure) + (maybe-append "HttpOnly" http-only)) + '())) + (define prop-alist + (append basic-prop-alist + extensions)) + (cons 'set-cookie (list name val prop-alist))) + +(define %the-epoch + (time-monotonic->date (make-time 'time-monotonic 0 0) 0)) + +(define (delete-cookie name) + (set-cookie name + #:expires %the-epoch + #:path "/" + #:secure #t + #:http-only #t)) diff --git a/db.scm b/db.scm @@ -0,0 +1,110 @@ +(define-module (db) + #:export (decrypt-user + select-user + insert-user + login-user + select-answers + insert-answers)) +(use-modules (ice-9 binary-ports) + (rnrs bytevectors) + (srfi srfi-1) + (srfi srfi-9) + (srfi srfi-26) + (sodium) + (sqlite3)) + +(define keyfile ".SECRET") +(define SECRET_KEY + (catch #t + (lambda () (call-with-input-file keyfile get-bytevector-all)) + (lambda (key . args) (generate-key)))) +;(call-with-output-file keyfile (cut put-bytevector <> SECRET_KEY)) + +(define db (sqlite-open "meta.sqlite")) + +(define-record-type <user> + (make-user name email password) + user? + (name user-name) + (email user-email) + (password user-password)) + +(define (err->msg key who code errmsg) + (list #f (case code + ((1299) "Niektoré povinné polia chýbajú") + ((2067) "Užívateľ s týmito údajmi už existuje") + (else (begin (display code) + (display errmsg) + "Niečo sa pokazilo v útrobách metaserveru! Skúste znovu"))))) + +(define (select-user name) + (let* ((stmt (sqlite-prepare db "select * from users where 'name' = ?")) + (result (sqlite-map make-user stmt))) + (sqlite-bind stmt 1 name) + (sqlite-finalize stmt) + result)) + +(define (encrypt-user user) + (base64-encode (encrypt (string->utf8 user) SECRET_KEY))) + +(define (decrypt-user user) + (let ((decrypted (decrypt (base64-decode user) SECRET_KEY))) + (if decrypted (utf8->string decrypted) #f))) + +(define (insert-user name email password) + (catch 'sqlite-error + (lambda () + (let ((stmt (sqlite-prepare db "insert into users values(?, ?, ?)"))) + (sqlite-bind stmt 1 name) + (sqlite-bind stmt 2 email) + (sqlite-bind stmt 3 (if (string? password) + (hash-password password) + #f)) + (sqlite-step stmt) + (sqlite-finalize stmt) + (list #t (encrypt-user name)))) + err->msg)) + +(define (login-user name password) + (catch 'sqlite-error + (lambda () + (let ((stmt (sqlite-prepare db "select password from users where name = ?"))) + (sqlite-bind stmt 1 name) + (let ((row (sqlite-step stmt))) + (sqlite-finalize stmt) + (if (and row (verify-password password (vector-ref row 0))) + (list #t (encrypt-user name)) + (list #f "Meno alebo heslo nie je správne"))))) + err->msg)) + +(define (insert-answers answers user round) + (catch 'sqlite-error + (lambda () + (let* ((stmt-text (string-append (fold (lambda (i so-far) + (string-append so-far ",(?,?,?,?)")) + "insert into answers (name, round, problem, content) values(?,?,?,?)" + (iota (- (length answers) 1))) + " on conflict do update set content=excluded.content")) + (stmt (sqlite-prepare db stmt-text))) + (for-each (lambda (a i) (begin (sqlite-bind stmt (+ (* i 4) 1) user) + (sqlite-bind stmt (+ (* i 4) 2) round) + (sqlite-bind stmt (+ (* i 4) 3) (+ i 1)) + (sqlite-bind stmt (+ (* i 4) 4) a))) + answers + (iota (length answers))) + (sqlite-step stmt) + (sqlite-finalize stmt) + (list #t))) + err->msg)) + +(define (select-answers user round) + (catch 'sqlite-error + (lambda () + (let* ((stmt-text "select problem, content from answers where name=? and round=? order by problem") + (stmt (sqlite-prepare db stmt-text))) + (sqlite-bind stmt 1 user) + (sqlite-bind stmt 2 round) + (let ((res (sqlite-map (cut vector-ref <> 1) stmt))) + (sqlite-finalize stmt) + (if (null? res) #f res)))) + (lambda (key who code msg) (begin (display msg) #f)))) diff --git a/db.sql b/db.sql @@ -0,0 +1,15 @@ +create table if not exists users ( + name text not null unique, + email text not null unique, + password text not null +); + +create table if not exists answers ( + name text not null, + round integer not null, + problem integer not null, + content text, + correct real default 0.0, + unique(name, round, problem), + foreign key (name) references users(name) on delete cascade on update cascade +); diff --git a/main.scm b/main.scm @@ -0,0 +1,4 @@ +(use-modules (web server) + (routes)) + +(run-server router 'http '(#:host "0.0.0.0" #:port 8011)) diff --git a/pngenerator.c b/pngenerator.c @@ -0,0 +1,97 @@ +#include <png.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +const uint16_t WIDTH = 256; +const uint16_t HEIGHT = 222; +const uint16_t ITERATIONS = 5020; +const size_t CAPACITY = 16384; + +typedef struct slice { + char* buffer; + size_t len; + size_t cap; +} slice; + +static void +png_write_slice(png_structp png_ptr, const png_bytep data, const png_size_t size) +{ + slice* p = png_get_io_ptr(png_ptr); + if ((p->len + size) > p->cap) { + size_t newcap = 2*p->cap + size; + p->buffer = realloc(p->buffer, newcap); + p->cap = newcap; + } + memcpy(p->buffer + p->len, data, size); + p->len += size; +} + +static png_color +num2col(const uint32_t num) +{ + png_color col = {(num >> 16) & 0xff, (num >> 8) & 0xff, num & 0xff}; + return col; +} + +extern slice +pngenerate(char * const text, const uint32_t background, const uint32_t foreground) +{ + slice state = { + .buffer = malloc(CAPACITY), + .len = 0, + .cap = CAPACITY + }; + + png_structp png_ptr = + png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); + png_set_write_fn(png_ptr, &state, png_write_slice, NULL); + png_infop info_ptr = png_create_info_struct(png_ptr); + png_set_compression_level(png_ptr, 9); + + const png_color palette[2] = {num2col(background), num2col(foreground)}; + png_set_IHDR(png_ptr, info_ptr, WIDTH, HEIGHT, 1, PNG_COLOR_TYPE_PALETTE, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, + PNG_FILTER_TYPE_DEFAULT); + png_set_PLTE(png_ptr, info_ptr, palette, 2); + + const png_text page = { + .compression = PNG_TEXT_COMPRESSION_NONE, + .key = "Page", + .text = text + }; + png_set_text(png_ptr, info_ptr, &page, 1); + + png_bytep buffer = calloc(WIDTH * HEIGHT / 8, sizeof(png_byte)); + png_bytep rows[HEIGHT]; + for (size_t i = 0; i < HEIGHT; i++) + rows[i] = buffer + i * WIDTH / 8; + + time_t t; + srand((unsigned) time(&t)); + + size_t x = rand() % WIDTH, y = rand() % HEIGHT; + for (int i = 0; i < ITERATIONS; i++) { + size_t r = rand() % 3; + x = (x + r*(WIDTH >> 1)) >> 1; + y = (y + ((r&1)^1)*HEIGHT) >> 1; + rows[y][x >> 3] |= 1 << ((x & 7) ^ 7); + } + png_set_rows(png_ptr, info_ptr, rows); + + png_write_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL); + png_destroy_write_struct(&png_ptr, &info_ptr); + + return state; +} + +int +main() +{ + FILE* fp = fopen("test.png", "wb"); + const slice s = pngenerate("Hello!!<img src=\"#\">", 0x002a1c, 0x143e30); + fwrite(s.buffer, 1, s.len, fp); + fclose(fp); + return 0; +} diff --git a/pngenerator.scm b/pngenerator.scm @@ -0,0 +1,15 @@ +(define-module (pngenerator) + #:export (pngenerate)) +(use-modules (system foreign)) + +(define pngenerator (dynamic-link "pngenerator")) + +(define (pngenerate text background-color foreground-color) + (let* ((slice-type (list '* size_t size_t)) + (f (pointer->procedure slice-type + (dynamic-func "pngenerate" pngenerator) + (list '* uint32 uint32))) + (ret (parse-c-struct (f (string->pointer text) background-color foreground-color) + slice-type))) + (pointer->bytevector (car ret) (cadr ret))) +) diff --git a/routes.scm b/routes.scm @@ -0,0 +1,222 @@ +(define-module (routes) + #:export (router)) +(use-modules (ice-9 match) + (rnrs bytevectors) + (srfi srfi-1) + (srfi srfi-26) + (sxml simple) + (web http) + (web request) + (web response) + (web uri) + (assets) + (cookie) + (db) + (style) + (pngenerator)) + +(define user-cookie "_Host-user") + +(define site-name "Metalympiáda") +(define round-name "Domáce kolo 2022/23") +(define deadline "narodenín Isaaca Newtona v roku 2022") + +(define current-round 0) + +(define footer + `(footer "Stránka Metalympiády je slobodný softvér pod licenciou AGPL: " + (a (@ (href "/git/index.png")) "zdrojový kód"))) + +(define (main-template body) + `((style ,style) + (meta (@ (name "viewport") (content "width=device-width, initial-scale=1"))) + (img (@ (class "meta") (src "#"))) + (main (header (a (@ (href "/")) ,logo) + (figure (pre (@ (class "textlogo") (role "img") + (aria-label "ASCII logo Metalympiády")) + ,text-logo))) + (nav (@ (id "mainav")) + (a (@ (href "/pravidla.png")) "Pravidlá")) + ,@body + ,footer))) + +(define (title-template title body) + `((title ,(string-append title " | " site-name)) + ,(main-template body))) + +(define login-form + `(form (@ (class "login") (action "#") (method "POST")) + (label "Meno:" (input (@ (class "short") (name "name") (required)))) + (label "Heslo:" + (input (@ (class "short") (name "password") (type "password") (required)))) + (input (@ (class "button") (type "submit") (value "Prihlásiť"))) + (a (@ (href "/register.png")) "Registrovať"))) + +(define (greeting user) + `((p "Prihlásený ako " + (strong ,user) + "! " + (a (@ (href "/logout.png")) "Odhlásiť sa")))) + +(define* (text-page title text #:optional (user #f)) + (values + title + `(,(if user (greeting user) login-form) + (p (@ (class "text")) ,text)))) + +(define* (problem-page #:optional (err #f) (user #f)) + (let ((answers (if user (select-answers user current-round) #f))) + (values + "Zadania" + `(,(if err `(span (@ (class "error")) ,err) '()) + ,(if user (greeting user) `(,login-form (p "Pre odoslanie riešení sa prihláste"))) + (h1 ,round-name) + (p "Riešenia je možné posielať do " + (strong ,deadline)) + (form (@ (action "#") (method "POST")) + ,@(map (lambda (text index) + (let ((i (number->string (+ index 1)))) + `((p (@ (class "text")) + (span (@ (class "problem-num")) ,i ".") + ,text) + ,(if user + `(input (@ (name ,i) + (class "block") + ,(if answers + `(value ,(list-ref answers index)) + `(placeholder "Odpoveď " ,i)))) + '()) + (hr)))) + problems (iota (length problems))) + ,(if user + `(input (@ (class "button block") + (type "submit") + (value "Uložiť riešenia"))) + '())))))) + +(define* (register-page #:optional (err #f)) + (values + "Registracia" + `(,(if err `(span (@ (class "error")) ,err) '()) + (form (@ (action "#") (method "POST")) + (label (@ (class "block")) + "Meno, pod ktorým chcete byť uvedení:" + (input (@ (name "name") (required)))) + (label (@ (class "block")) + "Heslo:" + (input (@ (name "password") (type "password") (required)))) + (label (@ (class "block")) + "Email (na potvrdenie a zaslanie výsledkov):" + (input (@ (name "email") (type "email") (required)))) + (label (@ (class "block small")) + "Súhlasím, aby moje odpovede na úlohy Metalympiády boli použité pri overovaní správnosti mojich riešení Metalympiády" + (input (@ (name "approval") (type "checkbox") (required)))) + (label (@ (class "block ghost")) + (input (@ (name "address")))) + (input (@ (class "button") (type "submit") (value "Registrovať"))))))) + +(define (login-response user) + (values (build-response #:code 301 + #:headers `((Location . "/index.png") + ,(set-cookie user-cookie + user + #:path "/" + #:secure #t + #:http-only #t))) + "")) + +(define (logout-response) + (values (build-response #:code 301 + #:headers `((Cache-Control . "no-cache") + (Location . "/index.png") + ,(delete-cookie user-cookie))) + "")) + +(define (register-check fields) + (if (and (equal? (assoc-ref fields "approval") "on") + (equal? (assoc-ref fields "address") "")) + (register-handler fields) + (render (lambda () (register-page "Musíte súhlasiť!"))))) + +(define (register-handler fields) + (let* ((maybe-user (insert-user (assoc-ref fields "name") + (assoc-ref fields "email") + (assoc-ref fields "password")))) + (if (car maybe-user) + (login-response (cadr maybe-user)) + (render (lambda () (register-page (cadr maybe-user))))))) + +(define (login-handler fields) + (let* ((maybe-user (login-user (assoc-ref fields "name") + (assoc-ref fields "password")))) + (if (car maybe-user) + (login-response (cadr maybe-user)) + (render (lambda () (problem-page (cadr maybe-user))))))) + +(define (submit-handler fields user round) + (let* ((answers (fold (lambda (i so-far) + (let ((a (assoc-ref fields (number->string (+ i 1))))) + (if (and so-far a) (append so-far (list a)) #f))) + '() + (iota (length problems)))) + (submitted (if answers + (insert-answers answers user round) `(#f "Neplatné odpovede")))) + (render (lambda () + (problem-page (if (car submitted) #f (cadr submitted)) user))))) + +(define* (render page #:optional (template title-template)) + (let ((rendered (call-with-output-string (cut + sxml->xml + (call-with-values page template) + <>)))) + (values (build-response + #:headers `((content-type text/html (charset . "utf-8")))) + (pngenerate rendered background-color foreground-color)))) + +(define (redirect location) + (values (build-response #:code 301 #:headers `((Location . ,location))) "")) + +(define (request-path-components request) + (split-and-decode-uri-path (uri-path (request-uri request)))) + +(define (query->alist q) + (fold (lambda (pair so-far) + (match pair ((key value) (acons (uri-decode key) (uri-decode value) so-far)) + (_ so-far))) + '() + (map (cut string-split <> #\=) + (string-split (utf8->string q) (char-set #\& #\;))))) + +(define (router request body) + (let* ((method (request-method request)) + (path (request-path-components request)) + (fields (if body + (catch #t + (lambda () (query->alist body)) + (lambda () '())) + '())) + (cookie (assoc-ref (request-headers request) 'cookie)) + (encrypted-user (if cookie (assoc-ref cookie user-cookie) #f)) + (user (if encrypted-user (decrypt-user encrypted-user) #f))) + (match method + ('POST (match path + (("register.png") (register-check fields)) + (_ (if user + (submit-handler fields user current-round) + (login-handler fields))))) + ('GET (match path + (() (redirect "index.png")) + (("index.png") (render (lambda () (problem-page #f user)))) + (("pravidla.png") (render (lambda () (text-page "Pravidlá" + rules-text + user)))) + (("register.png") (render register-page)) + (("logout.png") (logout-response)) + (("git") (redirect "/git/index.png")) + (("git" . rest) (let ((s (hash-ref stagit-sources (string-join rest "/")))) + (if s + (render (lambda () s) main-template) + (values (build-response #:code 404) "404")))) + (("favicon.ico") (values (build-response #:code 410) "")) + (_ (values (build-response #:code 404) "404")))) + (_ (values (build-response #:code 402) ""))))) diff --git a/sodium.scm b/sodium.scm @@ -0,0 +1,137 @@ +(define-module (sodium) + #:export (generate-key + encrypt + decrypt + hash-password + verify-password + base64-encode + base64-decode)) +(use-modules (rnrs bytevectors) + (system foreign)) + +(define libsodium (dynamic-link "libsodium")) + +(define sodium-init (pointer->procedure int + (dynamic-func "sodium_init" libsodium) + '())) +(if (equal? (sodium-init) -1) (begin + (display "Not enough entropy to be secure") + (quit))) + +(define KEYBYTES + ((pointer->procedure size_t (dynamic-func "crypto_secretbox_keybytes" libsodium) '()))) + +(define NONCEBYTES + ((pointer->procedure size_t (dynamic-func "crypto_secretbox_noncebytes" libsodium) '()))) + +(define MACBYTES + ((pointer->procedure size_t (dynamic-func "crypto_secretbox_macbytes" libsodium) '()))) + +(define SALTBYTES + ((pointer->procedure size_t (dynamic-func "crypto_pwhash_saltbytes" libsodium) '()))) + +(define STRBYTES + ((pointer->procedure size_t (dynamic-func "crypto_pwhash_strbytes" libsodium) '()))) + +(define OPSLIMIT + ((pointer->procedure size_t (dynamic-func "crypto_pwhash_opslimit_interactive" libsodium) '()))) + +(define MEMLIMIT + ((pointer->procedure size_t (dynamic-func "crypto_pwhash_memlimit_interactive" libsodium) '()))) + +(define (random-buffer size) + (let ((buffer (make-bytevector size)) + (f (pointer->procedure void + (dynamic-func "randombytes_buf" libsodium) + (list '* size_t)))) + (f (bytevector->pointer buffer) size) + buffer)) + +(define (generate-key) + (random-buffer KEYBYTES)) + +(define (pointer-add pointer offset) + (make-pointer (+ (pointer-address pointer) offset))) + +(define (encrypt message key) + (let ((buffer (random-buffer (+ (bytevector-length message) NONCEBYTES MACBYTES))) + (f (pointer->procedure int + (dynamic-func "crypto_secretbox_easy" libsodium) + (list '* '* size_t '* '*)))) + (f (pointer-add (bytevector->pointer buffer) NONCEBYTES) + (bytevector->pointer message) + (bytevector-length message) + (bytevector->pointer buffer) + (bytevector->pointer key)) + buffer)) + +(define (decrypt message key) + (let* ((buffer (make-bytevector (- (bytevector-length message) NONCEBYTES MACBYTES))) + (f (pointer->procedure int + (dynamic-func "crypto_secretbox_open_easy" libsodium) + (list '* '* size_t '* '*))) + (res (f (bytevector->pointer buffer) + (pointer-add (bytevector->pointer message) NONCEBYTES) + (- (bytevector-length message) NONCEBYTES) + (bytevector->pointer message) + (bytevector->pointer key)))) + (if (equal? res 0) buffer #f))) + +(define (hash-password password) + (let ((buffer (make-bytevector STRBYTES)) + (f (pointer->procedure int + (dynamic-func "crypto_pwhash_str" libsodium) + (list '* '* size_t size_t size_t)))) + (f (bytevector->pointer buffer) + (string->pointer password) + (string-length password) + OPSLIMIT + MEMLIMIT) + (pointer->string (bytevector->pointer buffer)))) + +(define (verify-password password hash) + (let* ((f (pointer->procedure int + (dynamic-func "crypto_pwhash_str_verify" libsodium) + (list '* '* size_t))) + (res (f (string->pointer hash) + (string->pointer password) + (string-length password)))) + (equal? res 0))) + +(define B64_VARIANT 7) + +(define (base64-encode data) + (let* ((el (pointer->procedure size_t + (dynamic-func "sodium_base64_encoded_len" libsodium) + (list size_t int))) + (len (el (bytevector-length data) B64_VARIANT)) + (buffer (make-bytevector len)) + (f (pointer->procedure '* + (dynamic-func "sodium_bin2base64" libsodium) + (list '* size_t '* size_t int)))) + (f (bytevector->pointer buffer) + len + (bytevector->pointer data) + (bytevector-length data) + B64_VARIANT) + (pointer->string (bytevector->pointer buffer)))) + +(define (base64-decode str) + (let* ((len (make-c-struct (list size_t) (list 0))) + (maxlen (ceiling (* (/ (string-length str) 4) 3))) + (buffer (make-bytevector maxlen)) + (f (pointer->procedure int + (dynamic-func "sodium_base642bin" libsodium) + (list '* size_t '* size_t '* '* '* int)))) + (f (bytevector->pointer buffer) + maxlen + (string->pointer str) + (string-length str) + %null-pointer + len + %null-pointer + B64_VARIANT) + (let ((outlen (car (parse-c-struct len (list size_t))))) + (if (> outlen 0) + (pointer->bytevector (bytevector->pointer buffer) outlen) + buffer)))) diff --git a/sqlite3.scm b/sqlite3.scm @@ -0,0 +1,565 @@ +;; Guile-SQLite3 +;; Copyright (C) 2010, 2014 Andy Wingo <wingo at pobox dot com> +;; Copyright (C) 2018 Ludovic Courtès <ludo@gnu.org> +(define-module (sqlite3) + #:export (sqlite-open + sqlite-db? + sqlite-close + + sqlite-enable-load-extension + sqlite-exec + sqlite-prepare + sqlite-bind + sqlite-bind-arguments + sqlite-column-names + sqlite-step + sqlite-fold + sqlite-fold-right + sqlite-map + sqlite-reset + sqlite-finalize + sqlite-bind-parameter-index + sqlite-busy-timeout + sqlite-expanded-sql + sqlite-trace + + SQLITE_OPEN_READONLY + SQLITE_OPEN_READWRITE + SQLITE_OPEN_CREATE + SQLITE_OPEN_DELETEONCLOSE + SQLITE_OPEN_EXCLUSIVE + SQLITE_OPEN_MAIN_DB + SQLITE_OPEN_TEMP_DB + SQLITE_OPEN_TRANSIENT_DB + SQLITE_OPEN_MAIN_JOURNAL + SQLITE_OPEN_TEMP_JOURNAL + SQLITE_OPEN_SUBJOURNAL + SQLITE_OPEN_MASTER_JOURNAL + SQLITE_OPEN_NOMUTEX + SQLITE_OPEN_FULLMUTEX + SQLITE_OPEN_SHAREDCACHE + SQLITE_OPEN_PRIVATECACHE + SQLITE_OPEN_URI + + SQLITE_TRACE_STMT + SQLITE_TRACE_PROFILE + SQLITE_TRACE_ROW + SQLITE_TRACE_CLOSE + + SQLITE_CONSTRAINT + SQLITE_CONSTRAINT_PRIMARYKEY + SQLITE_CONSTRAINT_UNIQUE)) +(use-modules + (system foreign) + (rnrs bytevectors) + (ice-9 match) + (srfi srfi-1) + (srfi srfi-9) + (srfi srfi-19)) + +(define (string->utf8-pointer s) + (string->pointer s "utf-8")) + +(define (utf8-pointer->string p) + (pointer->string p -1 "utf-8")) + +(define SQLITE_OPEN_READONLY #x00000001) +(define SQLITE_OPEN_READWRITE #x00000002) +(define SQLITE_OPEN_CREATE #x00000004) +(define SQLITE_OPEN_DELETEONCLOSE #x00000008) +(define SQLITE_OPEN_EXCLUSIVE #x00000010) +(define SQLITE_OPEN_MAIN_DB #x00000100) +(define SQLITE_OPEN_TEMP_DB #x00000200) +(define SQLITE_OPEN_TRANSIENT_DB #x00000400) +(define SQLITE_OPEN_MAIN_JOURNAL #x00000800) +(define SQLITE_OPEN_TEMP_JOURNAL #x00001000) +(define SQLITE_OPEN_SUBJOURNAL #x00002000) +(define SQLITE_OPEN_MASTER_JOURNAL #x00004000) +(define SQLITE_OPEN_NOMUTEX #x00008000) +(define SQLITE_OPEN_FULLMUTEX #x00010000) +(define SQLITE_OPEN_SHAREDCACHE #x00020000) +(define SQLITE_OPEN_PRIVATECACHE #x00040000) +(define SQLITE_OPEN_URI #x00000040) + +(define SQLITE_TRACE_STMT #x00000001) +(define SQLITE_TRACE_PROFILE #x00000002) +(define SQLITE_TRACE_ROW #x00000004) +(define SQLITE_TRACE_CLOSE #x00000008) + +(define SQLITE_CONSTRAINT 19) +(define SQLITE_CONSTRAINT_PRIMARYKEY + (logior SQLITE_CONSTRAINT (ash 6 8))) +(define SQLITE_CONSTRAINT_UNIQUE + (logior SQLITE_CONSTRAINT (ash 8 8))) + +(define libsqlite3 (dynamic-link "libsqlite3")) + +(define-record-type <sqlite-db> + (make-db pointer open? stmts) + db? + (pointer db-pointer) + (open? db-open? set-db-open?!) + (stmts db-stmts)) + +(define-syntax sqlite-db? + (identifier-syntax db?)) + +(define-record-type <sqlite-stmt> + (make-stmt pointer live? reset? cached?) + stmt? + (pointer stmt-pointer) + (live? stmt-live? set-stmt-live?!) + (reset? stmt-reset? set-stmt-reset?!) + (cached? stmt-cached? set-stmt-cached?!)) + +(define sqlite-errmsg + (let ((f (pointer->procedure + '* + (dynamic-func "sqlite3_errmsg" libsqlite3) + (list '*)))) + (lambda (db) + (utf8-pointer->string (f (db-pointer db)))))) + +(define sqlite-errcode + (let ((f (pointer->procedure + int + (dynamic-func "sqlite3_extended_errcode" libsqlite3) + (list '*)))) + (lambda (db) + (f (db-pointer db))))) + +(define* (sqlite-error db who #:optional code + (errmsg (and db (sqlite-errmsg db)))) + (throw 'sqlite-error who code errmsg)) + +(define* (check-error db #:optional who) + (let ((code (sqlite-errcode db))) + (if (not (zero? code)) + (sqlite-error db who code)))) + +(define sqlite-close + (let ((f (pointer->procedure + int + (dynamic-func "sqlite3_close" libsqlite3) + (list '*)))) + (lambda (db) + (when (db-open? db) + (hash-for-each (lambda (sql stmt) + (set-stmt-cached?! stmt #f) + (sqlite-finalize stmt)) + (db-stmts db)) + (hash-clear! (db-stmts db)) + + (let ((p (db-pointer db))) + (set-db-open?! db #f) + (f p)))))) + +(define db-guardian (make-guardian)) +(define (pump-db-guardian) + (let ((db (db-guardian))) + (if db + (begin + (sqlite-close db) + (pump-db-guardian))))) +(add-hook! after-gc-hook pump-db-guardian) + +(define (static-errcode->errmsg code) + (case code + ((1) "SQL error or missing database") + ((2) "Internal logic error in SQLite") + ((3) "Access permission denied") + ((5) "The database file is locked") + ((6) "A table in the database is locked") + ((7) "A malloc() failed") + ((8) "Attempt to write a readonly database") + ((10) "Some kind of disk I/O error occurred") + ((11) "The database disk image is malformed") + ((14) "Unable to open the database file") + ((21) "Library used incorrectly") + ((22) "Uses OS features not supported on host") + ((23) "Authorization denied") + ((24) "Auxiliary database format error") + ((26) "File opened that is not a database file") + (else "Unknown error"))) + +(define sqlite-open + (let ((f (pointer->procedure + int + (dynamic-func "sqlite3_open_v2" libsqlite3) + (list '* '* int '*)))) + (lambda* (filename #:optional + (flags (logior SQLITE_OPEN_READWRITE + SQLITE_OPEN_CREATE + SQLITE_OPEN_URI)) + (vfs #f)) + (let* ((out-db (bytevector->pointer (make-bytevector (sizeof '*) 0))) + (ret (f (string->utf8-pointer filename) + out-db + flags + (if vfs (string->utf8-pointer vfs) %null-pointer)))) + (if (zero? ret) + (let ((db (make-db (dereference-pointer out-db) #t + (make-hash-table)))) + (db-guardian db) + db) + (sqlite-error #f 'sqlite-open ret (static-errcode->errmsg ret))))))) + +(define sqlite-exec + (let ((exec (pointer->procedure + int + (dynamic-func "sqlite3_exec" (@@ (sqlite3) libsqlite3)) + '(* * * * *)))) + (lambda* (db sql) + "Evaluate the string SQL, which may contain one or several SQL +statements, into DB. The result is unspecified." + (assert-live-db! db) + (unless (zero? (exec (db-pointer db) (string->pointer sql) + %null-pointer %null-pointer %null-pointer)) + (check-error db 'sqlite-exec))))) + +(define sqlite-remove-statement! + (lambda (db stmt) + (when (stmt-cached? stmt) + (let* ((stmts (db-stmts db)) + (key (catch 'value + (lambda () + (hash-for-each (lambda (key value) + (when (eq? value stmt) + (throw 'value key))) + stmts) + #f) + (lambda (_ key) key)))) + (hash-remove! stmts key))))) + +(define sqlite-finalize + (let ((f (pointer->procedure + int + (dynamic-func "sqlite3_finalize" libsqlite3) + (list '*)))) + (lambda (stmt) + (when (stmt-live? stmt) + (if (stmt-cached? stmt) + (sqlite-reset stmt) + (let ((p (stmt-pointer stmt))) + (sqlite-remove-statement! (stmt->db stmt) stmt) + (set-stmt-live?! stmt #f) + (f p))))))) + +(define *stmt-map* (make-weak-key-hash-table)) +(define (stmt->db stmt) + (hashq-ref *stmt-map* stmt)) + +(define stmt-guardian (make-guardian)) +(define (pump-stmt-guardian) + (let ((stmt (stmt-guardian))) + (if stmt + (begin + (sqlite-finalize stmt) + (pump-stmt-guardian))))) +(add-hook! after-gc-hook pump-stmt-guardian) + +(define sqlite-reset + (let ((reset (pointer->procedure + int + (dynamic-func "sqlite3_reset" libsqlite3) + (list '*)))) + (lambda (stmt) + (if (stmt-live? stmt) + (let ((p (stmt-pointer stmt))) + (set-stmt-reset?! stmt #t) + (reset p)) + (error "statement already finalized" stmt))))) + +(define (assert-live-stmt! stmt) + (if (not (stmt-live? stmt)) + (error "statement already finalized" stmt))) + +(define (assert-live-db! db) + (if (not (db-open? db)) + (error "database already closed" db))) + +(define %sqlite-prepare + (let ((prepare (pointer->procedure + int + (dynamic-func "sqlite3_prepare_v2" libsqlite3) + (list '* '* int '* '*)))) + (lambda* (db sql #:key cache?) + (assert-live-db! db) + (let* ((out-stmt (bytevector->pointer (make-bytevector (sizeof '*) 0))) + (out-tail (bytevector->pointer (make-bytevector (sizeof '*) 0))) + (bv (string->utf8 sql)) + (bvp (bytevector->pointer bv)) + (ret (prepare (db-pointer db) + bvp + (bytevector-length bv) + out-stmt + out-tail))) + (if (zero? ret) + (if (= (bytevector-length bv) + (- (pointer-address (dereference-pointer out-tail)) + (pointer-address bvp))) + (let ((stmt (make-stmt (dereference-pointer out-stmt) #t #t + cache?))) + (stmt-guardian stmt) + (hashq-set! *stmt-map* stmt db) + stmt) + (error "input sql has useless tail" + (utf8-pointer->string + (dereference-pointer out-tail)))) + (check-error db 'sqlite-prepare)))))) + +(define* (sqlite-prepare db sql #:key cache?) + (if cache? + (match (hash-ref (db-stmts db) sql) + (#f + (let ((stmt (%sqlite-prepare db sql #:cache? #t))) + (hash-set! (db-stmts db) sql stmt) + stmt)) + (stmt + (sqlite-reset stmt) + stmt)) + (%sqlite-prepare db sql))) + +(define sqlite-bind-parameter-index + (let ((bind-parameter-index (pointer->procedure + int + (dynamic-func "sqlite3_bind_parameter_index" libsqlite3) + (list '* '*)))) + (lambda (stmt name) + (assert-live-stmt! stmt) + (let* ((ret (bind-parameter-index (stmt-pointer stmt) + (string->utf8-pointer name)))) + (if (> ret 0) + ret + (begin + (check-error (stmt->db stmt) 'sqlite-bind-parameter-index) + (write ret) + (newline) + (error "No such parameter" name))))))) + +(define key->index + (lambda (stmt key) + (cond + ((string? key) (sqlite-bind-parameter-index stmt key)) + ((symbol? key) (sqlite-bind-parameter-index stmt + (string-append ":" (symbol->string key)))) + (else key)))) + +(define sqlite-bind + (let ((bind-blob (pointer->procedure + int + (dynamic-func "sqlite3_bind_blob" libsqlite3) + (list '* int '* int '*))) + (bind-text (pointer->procedure + int + (dynamic-func "sqlite3_bind_text" libsqlite3) + (list '* int '* int '*))) + (bind-int64 (pointer->procedure + int + (dynamic-func "sqlite3_bind_int64" libsqlite3) + (list '* int int64))) + (bind-double (pointer->procedure + int + (dynamic-func "sqlite3_bind_double" libsqlite3) + (list '* int double))) + (bind-null (pointer->procedure + int + (dynamic-func "sqlite3_bind_null" libsqlite3) + (list '* int))) + (sqlite-transient (make-pointer + (bit-extract (lognot 0) 0 (* 8 (sizeof '*)))))) + (lambda (stmt key val) + (assert-live-stmt! stmt) + (let ((idx (key->index stmt key)) + (p (stmt-pointer stmt))) + (cond + ((bytevector? val) + (bind-blob p idx (bytevector->pointer val) (bytevector-length val) + sqlite-transient)) + ((string? val) + (let ((bv (string->utf8 val))) + (bind-text p idx (bytevector->pointer bv) (bytevector-length bv) + sqlite-transient))) + ((and (integer? val) (exact? val)) + (bind-int64 p idx val)) + ((number? val) + (bind-double p idx (exact->inexact val))) + ((not val) + (bind-null p idx)) + (else + (error "unexpected value" val))) + (check-error (stmt->db stmt)))))) + +(define (sqlite-bind-arguments stmt . args) + (let loop ((i 1) + (args args)) + (match args + (() + #f) + (((? keyword? kw) value . rest) + (sqlite-bind stmt (keyword->symbol kw) value) + (loop i rest)) + ((arg . rest) + (sqlite-bind stmt i arg) + (loop (+ 1 i) rest))))) + +(define sqlite-column-count + (let ((column-count + (pointer->procedure + int + (dynamic-pointer "sqlite3_column_count" libsqlite3) + (list '*)))) + (lambda (stmt) + (assert-live-stmt! stmt) + (column-count (stmt-pointer stmt))))) + +(define sqlite-column-name + (let ((column-name + (pointer->procedure + '* + (dynamic-pointer "sqlite3_column_name" libsqlite3) + (list '* int)))) + (lambda (stmt i) + (assert-live-stmt! stmt) + (utf8-pointer->string (column-name (stmt-pointer stmt) i))))) + +(define sqlite-column-value + (let ((value-type + (pointer->procedure + int + (dynamic-pointer "sqlite3_column_type" libsqlite3) + (list '* int))) + (value-int + (pointer->procedure + int64 + (dynamic-pointer "sqlite3_column_int64" libsqlite3) + (list '* int))) + (value-double + (pointer->procedure + double + (dynamic-pointer "sqlite3_column_double" libsqlite3) + (list '* int))) + (value-text + (pointer->procedure + '* + (dynamic-pointer "sqlite3_column_text" libsqlite3) + (list '* int))) + (value-blob + (pointer->procedure + '* + (dynamic-pointer "sqlite3_column_blob" libsqlite3) + (list '* int))) + (value-bytes + (pointer->procedure + int + (dynamic-pointer "sqlite3_column_bytes" libsqlite3) + (list '* int)))) + (lambda (stmt i) + (assert-live-stmt! stmt) + (let ((nbytes (value-bytes (stmt-pointer stmt) i))) + (case (value-type (stmt-pointer stmt) i) + ((1) (value-int (stmt-pointer stmt) i)) + ((2) (value-double (stmt-pointer stmt) i)) + ((3) (let ((p (value-blob (stmt-pointer stmt) i))) + (if (null-pointer? p) + "" + (utf8->string (pointer->bytevector p nbytes))))) + ((4) (let ((p (value-blob (stmt-pointer stmt) i))) + (if (null-pointer? p) + (make-bytevector 0) + (bytevector-copy (pointer->bytevector p nbytes))))) + ((5) #f)))))) + +(define (sqlite-column-names stmt) + (let ((v (make-vector (sqlite-column-count stmt)))) + (let lp ((i 0)) + (if (< i (vector-length v)) + (begin + (vector-set! v i (sqlite-column-name stmt i)) + (lp (1+ i))) + v)))) + +(define (sqlite-row stmt) + (let ((v (make-vector (sqlite-column-count stmt)))) + (let lp ((i 0)) + (if (< i (vector-length v)) + (begin + (vector-set! v i (sqlite-column-value stmt i)) + (lp (1+ i))) + v)))) + +(define sqlite-busy-timeout + (let ((f (pointer->procedure + int + (dynamic-func "sqlite3_busy_timeout" libsqlite3) + (list '* int)))) + (lambda (db value) + (assert-live-db! db) + (let ((ret (f (db-pointer db) value))) + (when (not (zero? ret)) + (check-error db 'sqlite-busy-timeout)))))) + +(define trace-callback + (lambda (callback) + (procedure->pointer + int + (lambda (trace context p x) + (callback trace p x) + 0) + (list unsigned-int '* '* '*)))) + +(define sqlite-expanded-sql + (let ((proc (pointer->procedure + '* + (dynamic-func "sqlite3_expanded_sql" libsqlite3) + (list '*)))) + (lambda (stmt-pointer) + (proc stmt-pointer)))) + +(define sqlite-trace + (let ((proc (pointer->procedure + int + (dynamic-func "sqlite3_trace_v2" libsqlite3) + (list '* unsigned-int '* '*)))) + (lambda (db mask callback) + (proc (db-pointer db) + mask + (trace-callback callback) + %null-pointer)))) + +(define sqlite-step + (let ((step (pointer->procedure + int + (dynamic-pointer "sqlite3_step" libsqlite3) + (list '*)))) + (lambda (stmt) + (assert-live-stmt! stmt) + (let ((ret (step (stmt-pointer stmt)))) + (case ret + ((100) ; SQLITE_ROW + (sqlite-row stmt)) + ((101) ; SQLITE_DONE + #f) + (else + (check-error (stmt->db stmt)) + (error "shouldn't get here"))))))) + +(define (sqlite-fold kons knil stmt) + (assert-live-stmt! stmt) + (let lp ((seed knil)) + (let ((row (sqlite-step stmt))) + (if row + (lp (kons row seed)) + seed)))) + +(define (sqlite-fold-right kons knil stmt) + (assert-live-stmt! stmt) + (let lp () + (let ((row (sqlite-step stmt))) + (if row + (kons row (lp)) + knil)))) + +(define (sqlite-map proc stmt) + (map proc + (reverse! (sqlite-fold cons '() stmt)))) diff --git a/stagit.c b/stagit.c @@ -0,0 +1,1297 @@ +/* +MIT/X Consortium License + +stagit (c) 2015-2022 Hiltjo Posthuma <hiltjo@codemadness.org> + +$OpenBSD: strlcpy.c,v 1.12 2015/01/15 03:54:12 millert Exp$ +$OpenBSD: strlcat.c,v 1.15 2015/03/02 21:41:08 millert Exp$ +(c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com> + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL +THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. +*/ +#include <sys/stat.h> +#include <sys/types.h> + +#include <err.h> +#include <errno.h> +#include <libgen.h> +#include <limits.h> +#include <stdint.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <time.h> +#include <unistd.h> + +#include <git2.h> + +#define LEN(s) (sizeof(s)/sizeof(*s)) + +struct deltainfo { + git_patch *patch; + + size_t addcount; + size_t delcount; +}; + +struct commitinfo { + const git_oid *id; + + char oid[GIT_OID_HEXSZ + 1]; + char parentoid[GIT_OID_HEXSZ + 1]; + + const git_signature *author; + const git_signature *committer; + const char *summary; + const char *msg; + + git_diff *diff; + git_commit *commit; + git_commit *parent; + git_tree *commit_tree; + git_tree *parent_tree; + + size_t addcount; + size_t delcount; + size_t filecount; + + struct deltainfo **deltas; + size_t ndeltas; +}; + +/* reference and associated data for sorting */ +struct referenceinfo { + struct git_reference *ref; + struct commitinfo *ci; +}; + +static git_repository *repo; + +static const char *baseurl = ""; /* base URL to make absolute RSS/Atom URI */ +static const char *relpath = ""; +static const char *repodir; + +static char *name = ""; +static char *strippedname = ""; +static char description[255]; +static char cloneurl[1024]; +static char *submodules; +static char *licensefiles[] = { "HEAD:LICENSE", "HEAD:LICENSE.md", "HEAD:COPYING" }; +static char *license; +static char *readmefiles[] = { "HEAD:README", "HEAD:README.md" }; +static char *readme; +static long long nlogcommits = -1; /* -1 indicates not used */ + +/* cache */ +static git_oid lastoid; +static char lastoidstr[GIT_OID_HEXSZ + 2]; /* id + newline + NUL byte */ +static FILE *rcachefp, *wcachefp; +static const char *cachefile; + +/* + * Copy string src to buffer dst of size dsize. At most dsize-1 + * chars will be copied. Always NUL terminates (unless dsize == 0). + * Returns strlen(src); if retval >= dsize, truncation occurred. + */ +size_t +strlcpy(char *dst, const char *src, size_t dsize) +{ + const char *osrc = src; + size_t nleft = dsize; + + /* Copy as many bytes as will fit. */ + if (nleft != 0) { + while (--nleft != 0) { + if ((*dst++ = *src++) == '\0') + break; + } + } + + /* Not enough room in dst, add NUL and traverse rest of src. */ + if (nleft == 0) { + if (dsize != 0) + *dst = '\0'; /* NUL-terminate dst */ + while (*src++) + ; + } + + return(src - osrc - 1); /* count does not include NUL */ +} + +/* + * Appends src to string dst of size dsize (unlike strncat, dsize is the + * full size of dst, not space left). At most dsize-1 characters + * will be copied. Always NUL terminates (unless dsize <= strlen(dst)). + * Returns strlen(src) + MIN(dsize, strlen(initial dst)). + * If retval >= dsize, truncation occurred. + */ +size_t +strlcat(char *dst, const char *src, size_t dsize) +{ + const char *odst = dst; + const char *osrc = src; + size_t n = dsize; + size_t dlen; + + /* Find the end of dst and adjust bytes left but don't go past end. */ + while (n-- != 0 && *dst != '\0') + dst++; + dlen = dst - odst; + n = dsize - dlen; + + if (n-- == 0) + return(dlen + strlen(src)); + while (*src != '\0') { + if (n != 0) { + *dst++ = *src; + n--; + } + src++; + } + *dst = '\0'; + + return(dlen + (src - osrc)); /* count does not include NUL */ +} + +/* Handle read or write errors for a FILE * stream */ +void +checkfileerror(FILE *fp, const char *name, int mode) +{ + if (mode == 'r' && ferror(fp)) + errx(1, "read error: %s", name); + else if (mode == 'w' && (fflush(fp) || ferror(fp))) + errx(1, "write error: %s", name); +} + +void +joinpath(char *buf, size_t bufsiz, const char *path, const char *path2) +{ + int r; + + r = snprintf(buf, bufsiz, "%s%s%s", + path, path[0] && path[strlen(path) - 1] != '/' ? "/" : "", path2); + if (r < 0 || (size_t)r >= bufsiz) + errx(1, "path truncated: '%s%s%s'", + path, path[0] && path[strlen(path) - 1] != '/' ? "/" : "", path2); +} + +void +deltainfo_free(struct deltainfo *di) +{ + if (!di) + return; + git_patch_free(di->patch); + memset(di, 0, sizeof(*di)); + free(di); +} + +int +commitinfo_getstats(struct commitinfo *ci) +{ + struct deltainfo *di; + git_diff_options opts; + git_diff_find_options fopts; + const git_diff_delta *delta; + const git_diff_hunk *hunk; + const git_diff_line *line; + git_patch *patch = NULL; + size_t ndeltas, nhunks, nhunklines; + size_t i, j, k; + + if (git_tree_lookup(&(ci->commit_tree), repo, git_commit_tree_id(ci->commit))) + goto err; + if (!git_commit_parent(&(ci->parent), ci->commit, 0)) { + if (git_tree_lookup(&(ci->parent_tree), repo, git_commit_tree_id(ci->parent))) { + ci->parent = NULL; + ci->parent_tree = NULL; + } + } + + git_diff_init_options(&opts, GIT_DIFF_OPTIONS_VERSION); + opts.flags |= GIT_DIFF_DISABLE_PATHSPEC_MATCH | + GIT_DIFF_IGNORE_SUBMODULES | + GIT_DIFF_INCLUDE_TYPECHANGE; + if (git_diff_tree_to_tree(&(ci->diff), repo, ci->parent_tree, ci->commit_tree, &opts)) + goto err; + + if (git_diff_find_init_options(&fopts, GIT_DIFF_FIND_OPTIONS_VERSION)) + goto err; + /* find renames and copies, exact matches (no heuristic) for renames. */ + fopts.flags |= GIT_DIFF_FIND_RENAMES | GIT_DIFF_FIND_COPIES | + GIT_DIFF_FIND_EXACT_MATCH_ONLY; + if (git_diff_find_similar(ci->diff, &fopts)) + goto err; + + ndeltas = git_diff_num_deltas(ci->diff); + if (ndeltas && !(ci->deltas = calloc(ndeltas, sizeof(struct deltainfo *)))) + err(1, "calloc"); + + for (i = 0; i < ndeltas; i++) { + if (git_patch_from_diff(&patch, ci->diff, i)) + goto err; + + if (!(di = calloc(1, sizeof(struct deltainfo)))) + err(1, "calloc"); + di->patch = patch; + ci->deltas[i] = di; + + delta = git_patch_get_delta(patch); + + /* skip stats for binary data */ + if (delta->flags & GIT_DIFF_FLAG_BINARY) + continue; + + nhunks = git_patch_num_hunks(patch); + for (j = 0; j < nhunks; j++) { + if (git_patch_get_hunk(&hunk, &nhunklines, patch, j)) + break; + for (k = 0; ; k++) { + if (git_patch_get_line_in_hunk(&line, patch, j, k)) + break; + if (line->old_lineno == -1) { + di->addcount++; + ci->addcount++; + } else if (line->new_lineno == -1) { + di->delcount++; + ci->delcount++; + } + } + } + } + ci->ndeltas = i; + ci->filecount = i; + + return 0; + +err: + git_diff_free(ci->diff); + ci->diff = NULL; + git_tree_free(ci->commit_tree); + ci->commit_tree = NULL; + git_tree_free(ci->parent_tree); + ci->parent_tree = NULL; + git_commit_free(ci->parent); + ci->parent = NULL; + + if (ci->deltas) + for (i = 0; i < ci->ndeltas; i++) + deltainfo_free(ci->deltas[i]); + free(ci->deltas); + ci->deltas = NULL; + ci->ndeltas = 0; + ci->addcount = 0; + ci->delcount = 0; + ci->filecount = 0; + + return -1; +} + +void +commitinfo_free(struct commitinfo *ci) +{ + size_t i; + + if (!ci) + return; + if (ci->deltas) + for (i = 0; i < ci->ndeltas; i++) + deltainfo_free(ci->deltas[i]); + + free(ci->deltas); + git_diff_free(ci->diff); + git_tree_free(ci->commit_tree); + git_tree_free(ci->parent_tree); + git_commit_free(ci->commit); + git_commit_free(ci->parent); + memset(ci, 0, sizeof(*ci)); + free(ci); +} + +struct commitinfo * +commitinfo_getbyoid(const git_oid *id) +{ + struct commitinfo *ci; + + if (!(ci = calloc(1, sizeof(struct commitinfo)))) + err(1, "calloc"); + + if (git_commit_lookup(&(ci->commit), repo, id)) + goto err; + ci->id = id; + + git_oid_tostr(ci->oid, sizeof(ci->oid), git_commit_id(ci->commit)); + git_oid_tostr(ci->parentoid, sizeof(ci->parentoid), git_commit_parent_id(ci->commit, 0)); + + ci->author = git_commit_author(ci->commit); + ci->committer = git_commit_committer(ci->commit); + ci->summary = git_commit_summary(ci->commit); + ci->msg = git_commit_message(ci->commit); + + return ci; + +err: + commitinfo_free(ci); + + return NULL; +} + +int +refs_cmp(const void *v1, const void *v2) +{ + const struct referenceinfo *r1 = v1, *r2 = v2; + time_t t1, t2; + int r; + + if ((r = git_reference_is_tag(r1->ref) - git_reference_is_tag(r2->ref))) + return r; + + t1 = r1->ci->author ? r1->ci->author->when.time : 0; + t2 = r2->ci->author ? r2->ci->author->when.time : 0; + if ((r = t1 > t2 ? -1 : (t1 == t2 ? 0 : 1))) + return r; + + return strcmp(git_reference_shorthand(r1->ref), + git_reference_shorthand(r2->ref)); +} + +int +getrefs(struct referenceinfo **pris, size_t *prefcount) +{ + struct referenceinfo *ris = NULL; + struct commitinfo *ci = NULL; + git_reference_iterator *it = NULL; + const git_oid *id = NULL; + git_object *obj = NULL; + git_reference *dref = NULL, *r, *ref = NULL; + size_t i, refcount; + + *pris = NULL; + *prefcount = 0; + + if (git_reference_iterator_new(&it, repo)) + return -1; + + for (refcount = 0; !git_reference_next(&ref, it); ) { + if (!git_reference_is_branch(ref) && !git_reference_is_tag(ref)) { + git_reference_free(ref); + ref = NULL; + continue; + } + + switch (git_reference_type(ref)) { + case GIT_REF_SYMBOLIC: + if (git_reference_resolve(&dref, ref)) + goto err; + r = dref; + break; + case GIT_REF_OID: + r = ref; + break; + default: + continue; + } + if (!git_reference_target(r) || + git_reference_peel(&obj, r, GIT_OBJ_ANY)) + goto err; + if (!(id = git_object_id(obj))) + goto err; + if (!(ci = commitinfo_getbyoid(id))) + break; + + if (!(ris = reallocarray(ris, refcount + 1, sizeof(*ris)))) + err(1, "realloc"); + ris[refcount].ci = ci; + ris[refcount].ref = r; + refcount++; + + git_object_free(obj); + obj = NULL; + git_reference_free(dref); + dref = NULL; + } + git_reference_iterator_free(it); + + /* sort by type, date then shorthand name */ + qsort(ris, refcount, sizeof(*ris), refs_cmp); + + *pris = ris; + *prefcount = refcount; + + return 0; + +err: + git_object_free(obj); + git_reference_free(dref); + commitinfo_free(ci); + for (i = 0; i < refcount; i++) { + commitinfo_free(ris[i].ci); + git_reference_free(ris[i].ref); + } + free(ris); + + return -1; +} + +FILE * +efopen(const char *filename, const char *flags) +{ + FILE *fp; + + if (!(fp = fopen(filename, flags))) + err(1, "fopen: '%s'", filename); + + return fp; +} + +/* Percent-encode, see RFC3986 section 2.1. */ +void +percentencode(FILE *fp, const char *s, size_t len) +{ + static char tab[] = "0123456789ABCDEF"; + unsigned char uc; + size_t i; + + for (i = 0; *s && i < len; s++, i++) { + uc = *s; + /* NOTE: do not encode '/' for paths or ",-." */ + if (uc < ',' || uc >= 127 || (uc >= ':' && uc <= '@') || + uc == '[' || uc == ']') { + putc('%', fp); + putc(tab[(uc >> 4) & 0x0f], fp); + putc(tab[uc & 0x0f], fp); + } else { + putc(uc, fp); + } + } +} + +/* Escape characters below as HTML 2.0 / XML 1.0. */ +void +xmlencode(FILE *fp, const char *s, size_t len) +{ + size_t i; + + for (i = 0; *s && i < len; s++, i++) { + switch(*s) { + case '<': fputs("&lt;", fp); break; + case '>': fputs("&gt;", fp); break; + case '\'': fputs("&#39;", fp); break; + case '&': fputs("&amp;", fp); break; + case '"': fputs("&quot;", fp); break; + default: putc(*s, fp); + } + } +} + +/* Escape characters below as HTML 2.0 / XML 1.0, ignore printing '\r', '\n' */ +void +xmlencodeline(FILE *fp, const char *s, size_t len) +{ + size_t i; + + for (i = 0; *s && i < len; s++, i++) { + switch(*s) { + case '<': fputs("&lt;", fp); break; + case '>': fputs("&gt;", fp); break; + case '\'': fputs("&#39;", fp); break; + case '&': fputs("&amp;", fp); break; + case '"': fputs("&quot;", fp); break; + case '\r': break; /* ignore CR */ + case '\n': break; /* ignore LF */ + default: putc(*s, fp); + } + } +} + +int +mkdirp(const char *path) +{ + char tmp[PATH_MAX], *p; + + if (strlcpy(tmp, path, sizeof(tmp)) >= sizeof(tmp)) + errx(1, "path truncated: '%s'", path); + for (p = tmp + (tmp[0] == '/'); *p; p++) { + if (*p != '/') + continue; + *p = '\0'; + if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) + return -1; + *p = '/'; + } + if (mkdir(tmp, S_IRWXU | S_IRWXG | S_IRWXO) < 0 && errno != EEXIST) + return -1; + return 0; +} + +void +printtimez(FILE *fp, const git_time *intime) +{ + struct tm *intm; + time_t t; + char out[32]; + + t = (time_t)intime->time; + if (!(intm = gmtime(&t))) + return; + strftime(out, sizeof(out), "%Y-%m-%dT%H:%M:%SZ", intm); + fputs(out, fp); +} + +void +printtime(FILE *fp, const git_time *intime) +{ + struct tm *intm; + time_t t; + char out[32]; + + t = (time_t)intime->time + (intime->offset * 60); + if (!(intm = gmtime(&t))) + return; + strftime(out, sizeof(out), "%a, %e %b %Y %H:%M:%S", intm); + if (intime->offset < 0) + fprintf(fp, "%s -%02d%02d", out, + -(intime->offset) / 60, -(intime->offset) % 60); + else + fprintf(fp, "%s +%02d%02d", out, + intime->offset / 60, intime->offset % 60); +} + +void +printtimeshort(FILE *fp, const git_time *intime) +{ + struct tm *intm; + time_t t; + char out[32]; + + t = (time_t)intime->time; + if (!(intm = gmtime(&t))) + return; + strftime(out, sizeof(out), "%Y-%m-%d %H:%M", intm); + fputs(out, fp); +} + +void +writeheader(FILE *fp, const char *title) +{ + fputs("<div class=\"stagit\"><title>", fp); + xmlencode(fp, title, strlen(title)); + if (title[0] && strippedname[0]) + fputs(" - ", fp); + xmlencode(fp, strippedname, strlen(strippedname)); + fputs("</title><table><tr><td>", fp); + fputs("</td><td>", fp); + fputs("<span class=\"desc\">", fp); + xmlencode(fp, description, strlen(description)); + fputs("</span></td></tr>", fp); + if (cloneurl[0]) { + fputs("<tr class=\"url\"><td></td><td>git clone <a href=\"", fp); + xmlencode(fp, cloneurl, strlen(cloneurl)); /* not percent-encoded */ + fputs("\">", fp); + xmlencode(fp, cloneurl, strlen(cloneurl)); + fputs("</a></td></tr>", fp); + } + fputs("<tr><td></td><td>\n", fp); + fprintf(fp, "<a href=\"%slog.png\">Log</a> | ", relpath); + fprintf(fp, "<a href=\"%sfiles.png\">Files</a>", relpath); + if (submodules) + fprintf(fp, " | <a href=\"%sfile/%s.png\">Submodules</a>", + relpath, submodules); + if (readme) + fprintf(fp, " | <a href=\"%sfile/%s.png\">README</a>", + relpath, readme); + if (license) + fprintf(fp, " | <a href=\"%sfile/%s.png\">LICENSE</a>", + relpath, license); + fputs("</td></tr></table>\n<hr/>\n<div class=\"content\">\n", fp); +} + +void +writefooter(FILE *fp) +{ + fputs("</div></div>", fp); +} + +size_t +writeblobpng(FILE *fp, const git_blob *blob) +{ + size_t n = 0, i, len, prev; + const char *nfmt = "<a href=\"#l%zu\" class=\"line\" id=\"l%zu\">%4zu</a> "; + const char *s = git_blob_rawcontent(blob); + + len = git_blob_rawsize(blob); + fputs("<pre class=\"blob\">\n", fp); + + if (len > 0) { + for (i = 0, prev = 0; i < len; i++) { + if (s[i] != '\n') + continue; + n++; + fprintf(fp, nfmt, n, n, n); + xmlencodeline(fp, &s[prev], i - prev + 1); + putc('\n', fp); + prev = i + 1; + } + /* trailing data */ + if ((len - prev) > 0) { + n++; + fprintf(fp, nfmt, n, n, n); + xmlencodeline(fp, &s[prev], len - prev); + } + } + + fputs("</pre>", fp); + + return n; +} + +void +printcommit(FILE *fp, struct commitinfo *ci) +{ + fprintf(fp, "<b>commit</b> <a href=\"%scommit/%s.png\">%s</a>\n", + relpath, ci->oid, ci->oid); + + if (ci->parentoid[0]) + fprintf(fp, "<b>parent</b> <a href=\"%scommit/%s.png\">%s</a>\n", + relpath, ci->parentoid, ci->parentoid); + + if (ci->author) { + fputs("<b>Author:</b> ", fp); + xmlencode(fp, ci->author->name, strlen(ci->author->name)); + fputs(" &lt;<a href=\"mailto:", fp); + xmlencode(fp, ci->author->email, strlen(ci->author->email)); /* not percent-encoded */ + fputs("\">", fp); + xmlencode(fp, ci->author->email, strlen(ci->author->email)); + fputs("</a>&gt;\n<b>Date:</b> ", fp); + printtime(fp, &(ci->author->when)); + putc('\n', fp); + } + if (ci->msg) { + putc('\n', fp); + xmlencode(fp, ci->msg, strlen(ci->msg)); + putc('\n', fp); + } +} + +void +printshowfile(FILE *fp, struct commitinfo *ci) +{ + const git_diff_delta *delta; + const git_diff_hunk *hunk; + const git_diff_line *line; + git_patch *patch; + size_t nhunks, nhunklines, changed, add, del, total, i, j, k; + char linestr[80]; + int c; + + printcommit(fp, ci); + + if (!ci->deltas) + return; + + if (ci->filecount > 1000 || + ci->ndeltas > 1000 || + ci->addcount > 100000 || + ci->delcount > 100000) { + fputs("Diff is too large, output suppressed.\n", fp); + return; + } + + /* diff stat */ + fputs("<b>Diffstat:</b>\n<table>", fp); + for (i = 0; i < ci->ndeltas; i++) { + delta = git_patch_get_delta(ci->deltas[i]->patch); + + switch (delta->status) { + case GIT_DELTA_ADDED: c = 'A'; break; + case GIT_DELTA_COPIED: c = 'C'; break; + case GIT_DELTA_DELETED: c = 'D'; break; + case GIT_DELTA_MODIFIED: c = 'M'; break; + case GIT_DELTA_RENAMED: c = 'R'; break; + case GIT_DELTA_TYPECHANGE: c = 'T'; break; + default: c = ' '; break; + } + if (c == ' ') + fprintf(fp, "<tr><td>%c", c); + else + fprintf(fp, "<tr><td class=\"%c\">%c", c, c); + + fprintf(fp, "</td><td><a href=\"#h%zu\">", i); + xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path)); + if (strcmp(delta->old_file.path, delta->new_file.path)) { + fputs(" -&gt; ", fp); + xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path)); + } + + add = ci->deltas[i]->addcount; + del = ci->deltas[i]->delcount; + changed = add + del; + total = sizeof(linestr) - 2; + if (changed > total) { + if (add) + add = ((float)total / changed * add) + 1; + if (del) + del = ((float)total / changed * del) + 1; + } + memset(&linestr, '+', add); + memset(&linestr[add], '-', del); + + fprintf(fp, "</a></td><td> | </td><td class=\"num\">%zu</td><td><span class=\"i\">", + ci->deltas[i]->addcount + ci->deltas[i]->delcount); + fwrite(&linestr, 1, add, fp); + fputs("</span><span class=\"d\">", fp); + fwrite(&linestr[add], 1, del, fp); + fputs("</span></td></tr>\n", fp); + } + fprintf(fp, "</table></pre><pre class=\"blob\">%zu file%s changed, %zu insertion%s(+), %zu deletion%s(-)\n", + ci->filecount, ci->filecount == 1 ? "" : "s", + ci->addcount, ci->addcount == 1 ? "" : "s", + ci->delcount, ci->delcount == 1 ? "" : "s"); + + fputs("<hr/>", fp); + + for (i = 0; i < ci->ndeltas; i++) { + patch = ci->deltas[i]->patch; + delta = git_patch_get_delta(patch); + fprintf(fp, "<b>diff --git a/<a id=\"h%zu\" href=\"%sfile/", i, relpath); + percentencode(fp, delta->old_file.path, strlen(delta->old_file.path)); + fputs(".png\">", fp); + xmlencode(fp, delta->old_file.path, strlen(delta->old_file.path)); + fprintf(fp, "</a> b/<a href=\"%sfile/", relpath); + percentencode(fp, delta->new_file.path, strlen(delta->new_file.path)); + fprintf(fp, ".png\">"); + xmlencode(fp, delta->new_file.path, strlen(delta->new_file.path)); + fprintf(fp, "</a></b>\n"); + + /* check binary data */ + if (delta->flags & GIT_DIFF_FLAG_BINARY) { + fputs("Binary files differ.\n", fp); + continue; + } + + nhunks = git_patch_num_hunks(patch); + for (j = 0; j < nhunks; j++) { + if (git_patch_get_hunk(&hunk, &nhunklines, patch, j)) + break; + + fprintf(fp, "<a href=\"#h%zu-%zu\" id=\"h%zu-%zu\" class=\"h\">", i, j, i, j); + xmlencode(fp, hunk->header, hunk->header_len); + fputs("</a>", fp); + + for (k = 0; ; k++) { + if (git_patch_get_line_in_hunk(&line, patch, j, k)) + break; + if (line->old_lineno == -1) + fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"i\">+", + i, j, k, i, j, k); + else if (line->new_lineno == -1) + fprintf(fp, "<a href=\"#h%zu-%zu-%zu\" id=\"h%zu-%zu-%zu\" class=\"d\">-", + i, j, k, i, j, k); + else + putc(' ', fp); + xmlencodeline(fp, line->content, line->content_len); + putc('\n', fp); + if (line->old_lineno == -1 || line->new_lineno == -1) + fputs("</a>", fp); + } + } + } +} + +void +writelogline(FILE *fp, struct commitinfo *ci) +{ + fputs("<tr><td>", fp); + if (ci->author) + printtimeshort(fp, &(ci->author->when)); + fputs("</td><td>", fp); + if (ci->summary) { + fprintf(fp, "<a href=\"%scommit/%s.png\">", relpath, ci->oid); + xmlencode(fp, ci->summary, strlen(ci->summary)); + fputs("</a>", fp); + } + fputs("</td><td>", fp); + if (ci->author) + xmlencode(fp, ci->author->name, strlen(ci->author->name)); + fputs("</td><td class=\"num\" align=\"right\">", fp); + fprintf(fp, "%zu", ci->filecount); + fputs("</td><td class=\"num\" align=\"right\">", fp); + fprintf(fp, "+%zu", ci->addcount); + fputs("</td><td class=\"num\" align=\"right\">", fp); + fprintf(fp, "-%zu", ci->delcount); + fputs("</td></tr>\n", fp); +} + +int +writelog(FILE *fp, const git_oid *oid) +{ + struct commitinfo *ci; + git_revwalk *w = NULL; + git_oid id; + char path[PATH_MAX], oidstr[GIT_OID_HEXSZ + 1]; + FILE *fpfile; + size_t remcommits = 0; + int r; + + git_revwalk_new(&w, repo); + git_revwalk_push(w, oid); + + while (!git_revwalk_next(&id, w)) { + relpath = ""; + + if (cachefile && !memcmp(&id, &lastoid, sizeof(id))) + break; + + git_oid_tostr(oidstr, sizeof(oidstr), &id); + r = snprintf(path, sizeof(path), "commit/%s.png", oidstr); + if (r < 0 || (size_t)r >= sizeof(path)) + errx(1, "path truncated: 'commit/%s.png'", oidstr); + r = access(path, F_OK); + + /* optimization: if there are no log lines to write and + the commit file already exists: skip the diffstat */ + if (!nlogcommits) { + remcommits++; + if (!r) + continue; + } + + if (!(ci = commitinfo_getbyoid(&id))) + break; + /* diffstat: for stagit HTML required for the log.png line */ + if (commitinfo_getstats(ci) == -1) + goto err; + + if (nlogcommits != 0) { + writelogline(fp, ci); + if (nlogcommits > 0) + nlogcommits--; + } + + if (cachefile) + writelogline(wcachefp, ci); + + /* check if file exists if so skip it */ + if (r) { + relpath = "../"; + fpfile = efopen(path, "w"); + writeheader(fpfile, ci->summary); + fputs("<pre>", fpfile); + printshowfile(fpfile, ci); + fputs("</pre>\n", fpfile); + writefooter(fpfile); + checkfileerror(fpfile, path, 'w'); + fclose(fpfile); + } +err: + commitinfo_free(ci); + } + git_revwalk_free(w); + + if (nlogcommits == 0 && remcommits != 0) { + fprintf(fp, "<tr><td></td><td colspan=\"5\">" + "%zu more commits remaining, fetch the repository" + "</td></tr>\n", remcommits); + } + + relpath = ""; + + return 0; +} + +size_t +writeblob(git_object *obj, const char *fpath, const char *filename, size_t filesize) +{ + char tmp[PATH_MAX] = "", *d; + const char *p; + size_t lc = 0; + FILE *fp; + + if (strlcpy(tmp, fpath, sizeof(tmp)) >= sizeof(tmp)) + errx(1, "path truncated: '%s'", fpath); + if (!(d = dirname(tmp))) + err(1, "dirname"); + if (mkdirp(d)) + return -1; + + for (p = fpath, tmp[0] = '\0'; *p; p++) { + if (*p == '/' && strlcat(tmp, "../", sizeof(tmp)) >= sizeof(tmp)) + errx(1, "path truncated: '../%s'", tmp); + } + relpath = tmp; + + fp = efopen(fpath, "w"); + writeheader(fp, filename); + fputs("<p> ", fp); + xmlencode(fp, filename, strlen(filename)); + fprintf(fp, " (%zuB)", filesize); + fputs("</p><hr/>", fp); + + if (git_blob_is_binary((git_blob *)obj)) + fputs("<p>Binary file.</p>\n", fp); + else + lc = writeblobpng(fp, (git_blob *)obj); + + writefooter(fp); + checkfileerror(fp, fpath, 'w'); + fclose(fp); + + relpath = ""; + + return lc; +} + +int +writefilestree(FILE *fp, git_tree *tree, const char *path) +{ + const git_tree_entry *entry = NULL; + git_object *obj = NULL; + const char *entryname; + char filepath[PATH_MAX], entrypath[PATH_MAX], oid[8]; + size_t count, i, lc, filesize; + int r, ret; + + count = git_tree_entrycount(tree); + for (i = 0; i < count; i++) { + if (!(entry = git_tree_entry_byindex(tree, i)) || + !(entryname = git_tree_entry_name(entry))) + return -1; + joinpath(entrypath, sizeof(entrypath), path, entryname); + + r = snprintf(filepath, sizeof(filepath), "file/%s.png", + entrypath); + if (r < 0 || (size_t)r >= sizeof(filepath)) + errx(1, "path truncated: 'file/%s.png'", entrypath); + + if (!git_tree_entry_to_object(&obj, repo, entry)) { + switch (git_object_type(obj)) { + case GIT_OBJ_BLOB: + break; + case GIT_OBJ_TREE: + /* NOTE: recurses */ + ret = writefilestree(fp, (git_tree *)obj, + entrypath); + git_object_free(obj); + if (ret) + return ret; + continue; + default: + git_object_free(obj); + continue; + } + + filesize = git_blob_rawsize((git_blob *)obj); + lc = writeblob(obj, filepath, entryname, filesize); + + fprintf(fp, "<tr><td><a href=\"%s", relpath); + percentencode(fp, filepath, strlen(filepath)); + fputs("\">", fp); + xmlencode(fp, entrypath, strlen(entrypath)); + fputs("</a></td><td class=\"num\" align=\"right\">", fp); + if (lc > 0) + fprintf(fp, "%zuL", lc); + else + fprintf(fp, "%zuB", filesize); + fputs("</td></tr>\n", fp); + git_object_free(obj); + } else if (git_tree_entry_type(entry) == GIT_OBJ_COMMIT) { + /* commit object in tree is a submodule */ + fprintf(fp, "<tr><td>m---------</td><td><a href=\"%sfile/.gitmodules.png\">", + relpath); + xmlencode(fp, entrypath, strlen(entrypath)); + fputs("</a> @ ", fp); + git_oid_tostr(oid, sizeof(oid), git_tree_entry_id(entry)); + xmlencode(fp, oid, strlen(oid)); + fputs("</td><td class=\"num\" align=\"right\"></td></tr>", fp); + } + } + + return 0; +} + +int +writefiles(FILE *fp, const git_oid *id) +{ + git_tree *tree = NULL; + git_commit *commit = NULL; + int ret = -1; + + fputs("<table id=\"files\"><thead>\n<tr>" + "<td><b>File name</b></td>" + "<td class=\"num\" align=\"right\"><b>Size</b></td>" + "</tr>\n</thead><tbody>\n", fp); + + if (!git_commit_lookup(&commit, repo, id) && + !git_commit_tree(&tree, commit)) + ret = writefilestree(fp, tree, ""); + + fputs("</tbody></table>", fp); + + git_commit_free(commit); + git_tree_free(tree); + + return ret; +} + +void +usage(char *argv0) +{ + fprintf(stderr, "usage: %s [-c cachefile | -l commits] " + "[-u baseurl] repodir\n", argv0); + exit(1); +} + +int +main(int argc, char *argv[]) +{ + git_object *obj = NULL, *readme_obj = NULL; + const git_oid *head = NULL; + mode_t mask; + FILE *fp, *fpread; + char path[PATH_MAX], repodirabs[PATH_MAX + 1], *p; + char tmppath[64] = "cache.XXXXXXXXXXXX", buf[BUFSIZ]; + size_t n; + int i, fd; + + for (i = 1; i < argc; i++) { + if (argv[i][0] != '-') { + if (repodir) + usage(argv[0]); + repodir = argv[i]; + } else if (argv[i][1] == 'c') { + if (nlogcommits > 0 || i + 1 >= argc) + usage(argv[0]); + cachefile = argv[++i]; + } else if (argv[i][1] == 'l') { + if (cachefile || i + 1 >= argc) + usage(argv[0]); + errno = 0; + nlogcommits = strtoll(argv[++i], &p, 10); + if (argv[i][0] == '\0' || *p != '\0' || + nlogcommits <= 0 || errno) + usage(argv[0]); + } else if (argv[i][1] == 'u') { + if (i + 1 >= argc) + usage(argv[0]); + baseurl = argv[++i]; + } + } + if (!repodir) + usage(argv[0]); + + if (!realpath(repodir, repodirabs)) + err(1, "realpath"); + + /* do not search outside the git repository: + GIT_CONFIG_LEVEL_APP is the highest level currently */ + git_libgit2_init(); + for (i = 1; i <= GIT_CONFIG_LEVEL_APP; i++) + git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, i, ""); + /* do not require the git repository to be owned by the current user */ + //git_libgit2_opts(GIT_OPT_SET_OWNER_VALIDATION, 0); + +#ifdef __OpenBSD__ + if (unveil(repodir, "r") == -1) + err(1, "unveil: %s", repodir); + if (unveil(".", "rwc") == -1) + err(1, "unveil: ."); + if (cachefile && unveil(cachefile, "rwc") == -1) + err(1, "unveil: %s", cachefile); + + if (cachefile) { + if (pledge("stdio rpath wpath cpath fattr", NULL) == -1) + err(1, "pledge"); + } else { + if (pledge("stdio rpath wpath cpath", NULL) == -1) + err(1, "pledge"); + } +#endif + + if (git_repository_open_ext(&repo, repodir, + GIT_REPOSITORY_OPEN_NO_SEARCH, NULL) < 0) { + fprintf(stderr, "%s: cannot open repository\n", argv[0]); + return 1; + } + + /* find HEAD */ + if (!git_revparse_single(&obj, repo, "HEAD")) + head = git_object_id(obj); + git_object_free(obj); + + /* use directory name as name */ + if ((name = strrchr(repodirabs, '/'))) + name++; + else + name = ""; + + /* strip .git suffix */ + if (!(strippedname = strdup(name))) + err(1, "strdup"); + if ((p = strrchr(strippedname, '.'))) + if (!strcmp(p, ".git")) + *p = '\0'; + + /* read description or .git/description */ + joinpath(path, sizeof(path), repodir, "description"); + if (!(fpread = fopen(path, "r"))) { + joinpath(path, sizeof(path), repodir, ".git/description"); + fpread = fopen(path, "r"); + } + if (fpread) { + if (!fgets(description, sizeof(description), fpread)) + description[0] = '\0'; + checkfileerror(fpread, path, 'r'); + fclose(fpread); + } + + /* read url or .git/url */ + joinpath(path, sizeof(path), repodir, "url"); + if (!(fpread = fopen(path, "r"))) { + joinpath(path, sizeof(path), repodir, ".git/url"); + fpread = fopen(path, "r"); + } + if (fpread) { + if (!fgets(cloneurl, sizeof(cloneurl), fpread)) + cloneurl[0] = '\0'; + checkfileerror(fpread, path, 'r'); + fclose(fpread); + cloneurl[strcspn(cloneurl, "\n")] = '\0'; + } + + /* check LICENSE */ + for (size_t i = 0; i < LEN(licensefiles) && !license; i++) { + if (!git_revparse_single(&obj, repo, licensefiles[i]) && + git_object_type(obj) == GIT_OBJ_BLOB) + license = licensefiles[i] + strlen("HEAD:"); + git_object_free(obj); + } + + /* check README */ + for (size_t i = 0; i < LEN(readmefiles) && !readme; i++) { + if (!git_revparse_single(&obj, repo, readmefiles[i]) && + git_object_type(obj) == GIT_OBJ_BLOB) { + readme = readmefiles[i] + strlen("HEAD:"); + readme_obj = obj; + } else { + git_object_free(obj); + } + } + + if (!git_revparse_single(&obj, repo, "HEAD:.gitmodules") && + git_object_type(obj) == GIT_OBJ_BLOB) + submodules = ".gitmodules"; + git_object_free(obj); + + /* log for HEAD */ + fp = efopen("log.png", "w"); + relpath = ""; + mkdir("commit", S_IRWXU | S_IRWXG | S_IRWXO); + writeheader(fp, "Log"); + fputs("<table class=\"log\"><thead>\n<tr><td><b>Date</b></td>" + "<td><b>Commit message</b></td>" + "<td><b>Author</b></td><td class=\"num\" align=\"right\"><b>Files</b></td>" + "<td class=\"num\" align=\"right\"><b>+</b></td>" + "<td class=\"num\" align=\"right\"><b>-</b></td></tr>\n</thead><tbody>\n", fp); + + if (cachefile && head) { + /* read from cache file (does not need to exist) */ + if ((rcachefp = fopen(cachefile, "r"))) { + if (!fgets(lastoidstr, sizeof(lastoidstr), rcachefp)) + errx(1, "%s: no object id", cachefile); + if (git_oid_fromstr(&lastoid, lastoidstr)) + errx(1, "%s: invalid object id", cachefile); + } + + /* write log to (temporary) cache */ + if ((fd = mkstemp(tmppath)) == -1) + err(1, "mkstemp"); + if (!(wcachefp = fdopen(fd, "w"))) + err(1, "fdopen: '%s'", tmppath); + /* write last commit id (HEAD) */ + git_oid_tostr(buf, sizeof(buf), head); + fprintf(wcachefp, "%s\n", buf); + + writelog(fp, head); + + if (rcachefp) { + /* append previous log to log.png and the new cache */ + while (!feof(rcachefp)) { + n = fread(buf, 1, sizeof(buf), rcachefp); + if (ferror(rcachefp)) + break; + if (fwrite(buf, 1, n, fp) != n || + fwrite(buf, 1, n, wcachefp) != n) + break; + } + checkfileerror(rcachefp, cachefile, 'r'); + fclose(rcachefp); + } + checkfileerror(wcachefp, tmppath, 'w'); + fclose(wcachefp); + } else { + if (head) + writelog(fp, head); + } + + fputs("</tbody></table>", fp); + writefooter(fp); + checkfileerror(fp, "log.png", 'w'); + fclose(fp); + + /* files for HEAD */ + fp = efopen("files.png", "w"); + writeheader(fp, "Files"); + if (head) + writefiles(fp, head); + writefooter(fp); + checkfileerror(fp, "files.png", 'w'); + fclose(fp); + + /* index = files + README */ + fp = efopen("index.png", "w"); + writeheader(fp, "Index"); + if (head) + writefiles(fp, head); + if (readme_obj) { + const char *s = git_blob_rawcontent((git_blob *)readme_obj); + size_t len = git_blob_rawsize((git_blob *)readme_obj); + fputs("<pre class=\"readme\">\n", fp); + xmlencode(fp, s, len); + fputs("</pre>", fp); + git_object_free(readme_obj); + } + writefooter(fp); + checkfileerror(fp, "index.png", 'w'); + fclose(fp); + + /* rename new cache file on success */ + if (cachefile && head) { + if (rename(tmppath, cachefile)) + err(1, "rename: '%s' to '%s'", tmppath, cachefile); + umask((mask = umask(0))); + if (chmod(cachefile, + (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) & ~mask)) + err(1, "chmod: '%s'", cachefile); + } + + /* cleanup */ + git_repository_free(repo); + git_libgit2_shutdown(); + + return 0; +} diff --git a/style.scm b/style.scm @@ -0,0 +1,161 @@ +(define-module (style) + #:export (stylesheet + background-color foreground-color + logo-ratio)) + +(define background-color #x153e4f) +(define foreground-color #x118282) +(define error-color #xcc2936) +(define peach-color #xf1bf98) +(define bright-color #xf9fbf2) +(define logo-ratio 0.618034) + +(define (color->string color) + (let ((str (number->string color 16))) + (string-append "#" (make-string (- 6 (string-length str)) #\0) str))) + +(define stylesheet `( + (body + (font-size 0) + (font-family "monospace") + (margin 0) + (visibility "hidden")) + + (rect + (transform-origin "50%" ,(string-append (number->string (* 50 logo-ratio)) "%")) + (animation "zoom 1.5s linear infinite")) + + (rect (: (nth-of-type "odd")) + (fill ,(color->string foreground-color))) + + (rect (: (nth-of-type "even")) + (fill ,(color->string bright-color))) + + (@ (keyframes "zoom") + (from (transform (scale ,(/ 1 logo-ratio)))) + (to (transform (scale ,logo-ratio)))) + + (.logo + (width "7rem")) + + (.meta + (position "fixed") + (visibility "visible") + (top 0) + (left 0) + (width "100vw") + (height "100vh") + (z-index 1) + (object-fit "fill")) + + (main + (visibility "visible") + (font-size "1.1rem") + (position "relative") + (padding "2rem") + (margin "1em auto") + (max-width "45rem") + (line-height "1.5") + (background ,(color->string bright-color)) + (z-index 2) + (overflow-x "hidden") + (mix-blend-mode "lighten")) + + (header + (display "flex") + (flex-wrap "wrap") + (justify-content "space-around") + (align-items "center")) + + (footer + (font-size "1rem") + (text-align "center")) + + (.textlogo + (font-size (min "2.2vw" "0.795rem"))) + + (nav + (margin "1rem 0")) + + (a + (color ,(color->string foreground-color))) + + (a (: "visited") + (color ,(color->string foreground-color))) + + (h1 + (margin "2rem 0 0.8rem")) + + (.text + (font-size "1rem") + (white-space "pre-wrap")) + + (.problem-num + (font-size "2.5rem") + (float "left") + (line-height 1.1)) + + (.button + (cursor "pointer") + (padding "0.5rem 0.7rem") + (margin "0.2rem 1rem 0.2rem 0.5rem") + (background ,(color->string foreground-color)) + (box-shadow ,(string-append (color->string foreground-color) "a0") "0.2rem" "0.2rem")) + + (.block + (display "block") + (margin "auto")) + + (.short + (width "9.5rem")) + + (.small + (margin "1rem 0") + (font-size "0.8rem")) + + (.error + (display "inline-block") + (color ,(color->string error-color)) + (border "0.1rem solid") + (padding "0 1rem") + (margin "1rem 0") + (line-height "3rem")) + + (.login + (display "flex") + (flex-wrap "wrap") + (align-items "center")) + + (input + (border "none") + (font "inherit") + (font-size "1.2rem") + (padding "0.2rem 0.5rem") + (margin "0.2rem 0.5rem") + (background "#000") + (color ,(color->string bright-color))) + + (.stagit + (margin-bottom "2rem")) + + (.line + (text-decoration "none")) + + (.blob + (overflow-x "scroll") + (font-size "0.81rem")) + + (.d + (color ,(color->string error-color)) + (text-decoration "none")) + + (.i + (color ,(color->string foreground-color)) + (text-decoration "none")) + + (.h + (color "#aaa") + (text-decoration "none")) + + (.ghost + (visibility "hidden")))) diff --git a/texts/problems b/texts/problems @@ -0,0 +1,27 @@ +Boris riešil prvú úlohu Metalympiády. Jej zadanie spomínalo Borisa, ako rieši prvú úlohu Metalympiády a pýtalo sa na odpoveď na ňu. Pomôžte mu. +~Ivan trpí me(n)tálnym problémom. Zakaždým, keď prečíta nejakú vetu, nahlas vysloví počet slov v nej. Ivan práve kontroloval svoje odpovede na Metalympiáde. Prečítal si odpoveď na šiestej úlohe a vyslovil číslo 1003. Následne si utrel okuliare a zahľadeľ sa znovu. +Ktoré číslo vyslovil po opakovanom prečítaní? +~Istému človeku sa nezdali úlohy Metalympiády dosť meta, a tak sa rozhodol, že si vymyslí vlastnú. Odpoveďou na jeho úlohu je číslo, ktoré sa spomína v zadaní úlohy Metalympiády s poradovým číslom takým, ktorého počet písmen v jeho slovenskom zápise je rovnaký ako samotná hodnota daného čísla. +Ktoré číslo je odpoveďou na úlohu v tejto úlohe? +~Vladislav riešil Metalympiádu, ale jej úlohy sa mu zdali príliš komplikované. Preto si ju svojím prazvláštnym spôsobom zjednodušil na nasledujúcu sadu výrokov. Keď vám ju predstavil, začudovali ste sa, ako súvisia s Metalympiádou, ale napriek tomu ste sa rozhodli, že mu pomôžete. +Rozhodnite, či je daný výrok pravdivý alebo nepravdivý. (Prípustné odpovede sú Áno, Nie; oddelené od seba medzerou.) + - Protagoras v eponymnom Platónovom diele navrhol hru, ktorá môže byť považovaná za prvú verziu Metalympiády. + - Na medzinárodnej vesmírnej stanici ISS sa nachádza 23 okien, cez ktoré bolo už aspoň raz možné vidiet budovu, v ktorej vznikla táto úloha Metalympiády. + - Mäkkýš rodu Helix bol spozorovaný autormi Metalympiády počas písania tejto úlohy. + - Tento výrok je tautológia. +~Boris cestoval vlakom. Vystrčil z okna svoju šesťdesiatmetrovú teleskopickú anténu. Vzápätí ju tým istým oknom vyhodil von, pretože si uvedomil, že tento kontext je pre súčasnú úlohu Metalympiády nepodstatný. Položil si len otázku:"Koľko odpovedí má táto otázka?" +Koľko odpovedí má otázka, ktorú si položil Boris? +~Ivan trpí obsesiou - počíta cifry každého čísla, ktoré vidí a v prípade, že je tento počet nepárny, prudko vynadá autorovi daného čísla. Keď si prečítal svoju odpoveď na druhú úlohu Metalympiády, udrel sa päsťou do čela, vytiahol z vrecka mobil, spustil aplikáciu "Fotoaparát", prepol si ju na prednú kameru a na svoj obraz z plných pľúc zakričal:"Ty korheľ jeden skazuvziaty!" +Koľkociferné číslo ho tak pobúrilo? +~Umelá Inteligencia Metatron 13 kontrolovala Vladislavove riešenia Metalympiády. V opdpovedi na Úlohu 7 mal napísane "Kôň", čo však Metatron 13 vyhodnotil za nesprávne, keďže táto úloha sa pýta na dvojnásobok súčtu všetkých číselných odpovedí na úlohy tohto kola Metalympiády. +~Ivan trpí predstavou, že dokáže komunikovať s bohom. Ivan nevedel vyriešiť prvú úlohu Metalympiády, a tak poprosil boha o pomoc. Boh sa nad ním zľutoval a prezradil mu tajomstvo vesmíru, v ktorom sa Ivan nachádza:"'Byť časťou niečoho' je tranzitívna, reflexívna a antisymetrická relácia." Ivan strávil nasledujúcich 1,38 stotín sekundy premýšlaním nad týmto tvrdením, než sa dovtípil, že mu s jeho problémom neveľmi pomôže. Odvrkol:"Vrelá vďaka, ty šumichrast!" +Boh nezniesol váhu vysloveného pomenovania a podal mu papierik s vaším riešením prvej úlohy. To však Ivanovi pripomenulo jeho poruchu zo šiestej úlohy. "Ty chňupák jeden dvojdvorský!" odkazuje vám. +Medzičasom začal Vladislav naliehať na Ivana. Tiež sa zaujímal o riešenie prvej úlohy, ale nezabúdajte, že má problém so spracovávaním čísel, ktoré si nedokáže ukázať na prstoch rúk. +Keďže Ivan sa na vaše riešenie nedokáže ani pozrieť, vyžaduje od vás ďaľšie číslo, ktoré môže odovzdať aj Vladislavovi. +~Ivan trpí depresiou spôsobenou jeho neschopnosťou systematizovať mereológiu. Autori metalympiády ho preto poslali na terapiu k tej úlohe Metalympiády, pri prečítaní názvu ktorej im nevynadá, keďže sa im nechcelo vymýsľať ďalšie slovenské pejoratíva. +"Čo trýzni tvoju skľúčenú dušu?" opýtala sa ho táto úloha. +"Moja neschopnosť systematizovať mereológiu," odvetil Ivan. +"Na cestu neľahkú si sa vydal, ale čímsi nenáročným započatá byť musí. Tvojim prvým schodíkom na zikkurate mereologickej gnózy nech je odpoveď na nasledujúcu otázku: Aká je mohutnosť množiny všetkých neprázdnych podmnožín množiny všetkých úloh tohto kola Metalympiády?" +Napíšte prvý schodík Ivanovho zikkuratu mereologickej gnózy. +~Vladislav pil toluén. Zrazu všade okolo seba uvidel Úlohu 9. Vladislav ju oslovil:"Hskjdlksjf!" +"Pomlč," odvetila mu, "nie si ty ten, ktorému prihováram sa, lež Metalympiády riešiteľ má si moje slová k srdcu vziať. Prijmi vrúcnu vďaku za tvoju snahu pri pokúšaní sa zistiť správne odpovede na úlohy Metalympiády. Pamätajte, život je krásny, hoci ste to azda pri riešení úloh Metalympiády (aspoň o nejakých jeho výtvoroch) spochybňovali. Tu mali nasledovať ďalšie vety na rozlúčenie sa s vami, ale neboli vymyslené." diff --git a/texts/rules b/texts/rules @@ -0,0 +1,17 @@ +Pravidlá Metalympiády +=== + +1. Pravidlá Metalympiády sú pravidlá uvedené v tomto texte. +2. Každý školský rok sa koná rádovo 10^0 kôl Metalympiády. +3. Riešiteľ Metalympiády (ďalej len riešiteľ) je každá fyzická osoba, ktorá odoslala svoje riešenia úloh Metalympiády na servery Metalypmiády v podobe, ktorú sú servery Metalympiády schopné spracovať ako jej riešenia úloh Metalympiády. +4. Každý riešiteľ Metalympiády sa musí riadiť pravidlami Metalympiády. +5. Za riešiteľovu odpoveď na určitú úlohu Metalympiády dostane daný riešiteľ body, ak je riešiteľova odpoveď správnou odpoveďou na danú úlohu Metalympiády. +6. Úlohy Metalympiády majú jednu alebo viac alebo menej správnych odpovedí. +7. Každá správna odpoveď je logicky konzistentná so všetkými zadaniami všetkých úloh Metalympiády a všetkými odpoveďami na ostatné úlohy Metalympiády, pokiaľ nie je v zadaní danej úlohy Metalympiády uvedené inak. +8. Riešiteľove odpovede na úlohy Metalympiády sú vyhodnocované programom Metratron 13, ktorý pozná správne odpovede prinajhoršom rovnako dobre ako riešiteľ. +9. Metatron 13 za každú odpoveď pridelí bodové ohodnotenie v intervale (-∞, ∞) (typicky však [0, 1]). +10. Za víťazov daného kola Metalympiády sú považovaní tí riešitelia, ktorých súčet bodových ohodnotení odpovedí na úlohy tohto kola Metalympiády je maximálny spomedzi všetkých riešiteľov. +11. Analogicky v prípade víťazov Metalympiády v danom školskom roku, pričom v prípade rovnosti majú body získané v neskorších kolách väčšiu váhu. +12. Víťazi Metalympiády v každom školskom roku obdržia bližšie nešpecifikované vecné ceny, pokiaľ budú ochotní poskytnúť poštovú adresu na doručenie týchto cien. +13. V prípade, že je riešiteľ presvedčený o správnosti jeho odpovede, ktorú Metatron 13 označil za nesprávnu, pravdepodobne sa pomýlil, ale má právo na vyhodnotenie svojej sťažnosti na správnosť hodnotenia Metatrona 13, ktorú odoslal na e-mailovú adresu metalympiada@matfyz.cz. +14. Každá postava v zadaniach úloh Metalympiády je považovaná za zdravého jedinca druhu Homo sapiens, ako ho opísal Linné v roku 1758, pokiaľ nie je uvedené inak.
I= IDATxOlW~gFKuQZmg .-GJC<Q|=6P+Ұ f̩hl9t@af$r)I:͐R2Hzތ_^)kS)ƴN 2-`JBuZ7 R}:?mP 0U$SERs!]Ŕ& ɟ %wé?MMg~8y hC8EM1&~D'I &eZ_GWxq⢆ī%ŀ"Y>9i|ܛ؏XLL Br+&Zl} I 0&F `0iMbĽr1L±> 8'h10#STU'd3LԜY`2@(jbm1Qs|j(]$ {cd#CEj|SeU=L @0iM\nT9Mzw66dwۏFSp9o?Iwc%z#> 6ȽkkܮJ@ /6߲N#Iܦ-cljIm(] ùjv°[\ƍ#TW0c(Ԟ9I1ZfҎhcߍ11wBal@ne _7J E2vzZG\;#4XNi%s@TI`\'q 3F Ec^lB%tlҰ`m`ַ#`G=MGX*Q;MǤCn,kN0" (ϛ|@@Yz`DAcF(e2i նG/#( ߿=b FDj$5p5]׳G C۾n2zEH; QFaOwd@쎪ݱ[L/x9JLiI6jK7$%IK Kfl(Q.TR Tw4$|6TKn).k@;ےmo4Pz)t@x6lاY{#8 xad"W4R1_`ġ@yl HL9 29ҢW ?ͮIo+``3+*ᥒ2OZ#jm;5*!^Jwp'wlcd3x#fН h!ib>:j{+{@66*W%̔hv;JUPs[ZhT@B#vd5!y5?] a,E.Xа>EGF <~Hۏ nې@`ף( (|ylX?UHXpѱ#ֳua p:7k+wԀqa g.h]e6uj2J\Qi8?2- # ^0/8Üм d`4ZfI9ZZsS)0!lpM" ?$gO{~] 3mvsow~+Y8D ?+@:*.E@0݊j"@:ż_[Kz_Ylȹ-5ë6T;6DP }c 9Z :ؔhC \PRu"p2M lY6d5p7zt C1vz7فֹNO#nkC[Vf<%)ʟ4 s櫅҉Pye@ 8ϳa>KU8W2b!vWR,̚|zA| U7tœ=(̇Mx<V|qG8eTq 4@Gz`0_7yWuyjٝ3%_/ŏ6:Gd{4,z<`$B->9 +]A@,wx,qBī5gzW!|PmtB끀(ou 9#J9[MCŪgjޜ7 mY*T>Mٓs*BP9Νº8d::`! q}>V=3_5ǸV^6 t[vҕXw$X׫"`Y}@QIT8B@+eËAU4Ҽ_vۖJ[=, !;p,er,É!Mg*]0wͶztw~նX 5T\\?m'u.0 ,& */&vm؞C>0Ujy s 8h<ˑѨ;Y އ!hR&^%37'e XC}N&uоuxk!pTOn[áHXQ1a*vE1nhA%snY I%>[wksJХ&M e.c#%I!t$-t[~ve3{Yؚ/_\ڌ~IlP(gDSҎAbFk1`VEɦ=±oP|xlȦ m"STC\ךͶPߕO;%ja;Fa=s¢C;xSajSb^rHB~kTԺt#]NM>#vv&46/y.=Pt?3 8`4! s&H>()̔f;8b"p1NM&C u"z@ =<**`3cR5@ƚ.`f+"3oDHl_@m*P4 mݍ9(#tBY <k/YX[K_gчo1IENDB`