From 9167d5deb5791ff2617cf63a5a7426a87820f1f6 Mon Sep 17 00:00:00 2001 From: Michael Zucchi Date: Sat, 27 Apr 2019 17:08:00 +0930 Subject: [PATCH] Import of blogz 0.3 --- .gitignore | 11 + COPYING | 661 +++++++++++++++++++++++++++++++++++ Makefile | 130 +++++++ README | 255 ++++++++++++++ apache-site-cgi.conf | 17 + apache-site.conf | 16 + blog.c | 487 ++++++++++++++++++++++++++ blogio-fcgi.c | 99 ++++++ blogio-stdio.c | 127 +++++++ blogio.h | 32 ++ config.h.in | 30 ++ fast-cgi.h | 122 +++++++ fcgi.c | 382 ++++++++++++++++++++ fcgi.h | 62 ++++ makeindex.pl | 169 +++++++++ maketemplate.pl | 40 +++ newpost.c | 164 +++++++++ posts.c | 245 +++++++++++++ posts.h | 50 +++ template.h | 9 + template/blog-footer.html.in | 6 + template/blog-header.html.in | 13 + 22 files changed, 3127 insertions(+) create mode 100644 .gitignore create mode 100644 COPYING create mode 100644 Makefile create mode 100644 README create mode 100644 apache-site-cgi.conf create mode 100644 apache-site.conf create mode 100644 blog.c create mode 100644 blogio-fcgi.c create mode 100644 blogio-stdio.c create mode 100644 blogio.h create mode 100644 config.h.in create mode 100644 fast-cgi.h create mode 100644 fcgi.c create mode 100644 fcgi.h create mode 100755 makeindex.pl create mode 100755 maketemplate.pl create mode 100644 newpost.c create mode 100644 posts.c create mode 100644 posts.h create mode 100644 template.h create mode 100644 template/blog-footer.html.in create mode 100644 template/blog-header.html.in diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c82e292 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +/*.o +/.deps +/blog.cgi +/blog.fcgi +/template/*.html +/config.h +/config.make +/newpost +/posts-tables.h +/etag.h +/blog-*.c diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/COPYING @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..22f13c0 --- /dev/null +++ b/Makefile @@ -0,0 +1,130 @@ +# Makefile. A very very shit makefile. + +# Copyright (C) 2019 Michael Zucchi + +# 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 +# . + +# see config.h for application level config, config.make is created from it +include config.make + +CFLAGS=-Og -g -Wall -Wno-unused-function $(DEBUG_CFLAGS) + +dist_VERSION=0.3 + +tools=newpost +cgis=$(if $(USE_FCGI),blog.fcgi,blog.cgi) + +# these are the intermediate targets, not the sources +blogz_TEMPLATES=blog-header.c blog-footer.c + +blogz_PROGRAMS= $(cgis) $(tools) + +blog.fcgi_SRCS=blog.c posts.c $(blogz_TEMPLATES) blogio-fcgi.c fcgi.c +blog.cgi_SRCS=blog.c posts.c $(blogz_TEMPLATES) blogio-stdio.c +newpost_SRCS=newpost.c + +built_SRCS=$(sort $(foreach prog,$(blogz_PROGRAMS),$($(prog)_SRCS))) + +dist_PROGRAMS=blog.cgi blog.fcgi newpost +dist_SRCS=$(sort $(foreach prog,$(dist_PROGRAMS),$($(prog)_SRCS))) +dist_EXTRA=Makefile \ + README COPYING \ + apache-site-cgi.conf apache-site.conf \ + config.h.in \ + blogio.h etag.h fast-cgi.h fcgi.h posts.h template.h \ + $(patsubst blog-%.c,template/blog-%.html.in,$(blogz_TEMPLATES)) \ + makeindex.pl \ + maketemplate.pl + +all: $(blogz_PROGRAMS) +dist: blogz-$(dist_VERSION).tar.gz + +define make_program= +$(1): $(2) + $$(CC) -o $$@ $$(LDFLAGS) $$^ $$(LDLIBS) +endef + +$(foreach prog,$(blogz_PROGRAMS),$(eval $(call make_program,$(prog),$($(prog)_SRCS:.c=.o)))) +#$(foreach prog,$(blogz_PROGRAMS),$(info $(call make_program,$(prog),$($(prog)_SRCS:.c=.o)))) + +# database indexing +posts-tables.h: $(DB_POST) makeindex.pl + ./makeindex.pl $(DB_POST) > $@ || rm $@ +.deps/posts.d posts.o: posts-tables.h + +# template compilation +blog-%.c: template/blog-%.html maketemplate.pl + ./maketemplate.pl blog_send_$* $< > $@ || rm $@ + +# the etag is related to cache management. it changes any time any of the blog contents could change. +etag.h: posts-tables.h $(blogz_TEMPLATES) + date --rfc-3339 ns | md5sum | awk '{ printf "static const char* etag = \"%s\";\n",$$1 }' > etag.h + +clean: + rm -f posts-tables.h $(blogz_TEMPLATES) config.make + rm -f *.o + rm -rf .deps + rm -f blog.cgi blog.fcgi + rm -rf newpost + +$(DB_POST): + echo "Post database doesn't exist yet." + echo "Try running: make install-db" + exit 1 + +# install stuff +install-db: + if [ ! -e "$(DB_POST)" ] ; then \ + mkdir -p "$(DB_POST)"; \ + chown $(post_user):$(post_group) "$(DB_POST)"; \ + chmod g+s "$(DB_POST)"; \ + fi + if [ ! -e "$(DB_NEW)" ] ; then \ + mkdir -p "$(DB_NEW)"; \ + chown $(post_user):$(post_group) "$(DB_NEW)"; \ + chmod g+s "$(DB_NEW)"; \ + fi + +install-tools: $(addprefix $(bindir)/,$(tools)) +install: $(addprefix $(cgibindir)/,$(cgis)) + +$(cgibindir)/% $(bindir)/%: % + install -D -m 0755 $< $@ + +.PHONY: install install-tools dist + +# dist +blogz-$(dist_VERSION).tar.gz: $(dist_EXTRA) $(dist_SRCS) + tar -c -z \ + --transform=s@^@blogz-$(dist_VERSION)/@ \ + -f $@ \ + $^ + +# Make management +config.make: config.h Makefile + sed -e 's@//@#//@' \ + -e 's/^#define \([a-zA-Z0-9_]*\) "\(.*\)"/\1=\2/' \ + -e 's/^#define \([a-zA-Z0-9_]*\) \(.*\)/\1=\2/' \ + < $< > $@ || rm $@ +.deps/%.d: %.c + @rm -f $@ + @test ! -d .deps && mkdir .deps || exit 0 + $(CC) -MM $(CPPFLAGS) $< > $@ + +.INTERMEDIATE: $(blogz_TEMPLATES) + +ifeq (,$(filter clean install-db dist,$(MAKECMDGOALS))) +-include $(patsubst %.c,.deps/%.d,$(built_SRCS)) +endif diff --git a/README b/README new file mode 100644 index 0000000..6fe1c9f --- /dev/null +++ b/README @@ -0,0 +1,255 @@ + +INTRODUCTION +------------ + +This is a "micro-service" blogging engine for running on a virtual +private server or other fully accessible network connected host. + +It is simple*, fast*, and secure*. + +It is a cgi program but can run using FastCGI. + +It is intended as a single-site personal service; it is not for a blog +provider and will never include ``enterprise'' features. + +* Or you could call it aboslutely minimalistic. +* When using FastCGI. +* Look I can't guarantee it but as the posts are compiled into the + binary and are only accessed by an integer identifier there is very + little that can go wrong. + +COMPILING +--------- + +This assumes you're building on the machine you're using as the +server, but also see NOTES below. + +The usual GNU tools are required. Additionally, FastCGI support +requires GNU libc. + +setup +- - - + +Copy config.h.in to config.h and edit the settings. + +Copy all the templates in template/*.html.in to template/*.html and +edit them for your site. + +first build +- - - - - - + +Because the post index is compiled into the binary you need to +initialise the post database first. + +$ make install-db + +You can then build the binaries, but without any posts there +isn't much use. + +$ make + +making posts +- - - - - - - + +Before you can create posts you need to install the newpost command +(also see NOTES). + +$ make install-tools + +The newpost command takes the title of the post followed a list of +keywords/tag separated by commas. It will execute emacs to edit the +new post file and then move it to the post database. + +$ /tool-path/newpost "Hello World!" site-news,dummy + +Each time a new post is generated you need to re-install the cgi +programs. + +$ make install + +If you have compiled it in cgi mode you can test the basic operation +by running: + +$ PATH_INFO=/ ./blog + +CUSTOMISE +--------- + +Some templates for the page header and footer are in template/. + +There are some hardcoded url paths in the source, these are mostly +absolute so you need to configure apache appropriately. + +INTSTALL +-------- + +This requires a http server. + +There are a couple of example configuration files for apache included +in the distribution. They may not be complete. + +apache-site.conf contains the site and setup for the cgi scripts. +apache-cgi-site.conf is includes by apache-site.conf. + +These need to point match cgibindir in config.h. It is not necessary +and probably unwise to put the post database under the document root. + +On a debian system these go in /etc/apache2/sites-available and +/etc/apache2/conf-available respectively. To use FastCGI you also +need to enable mod_fcgid.c with for the .fcgi extension, or some other +way. + +NOTES +----- + +Just stuff you might like to know. + +Local Editing +- - - - - - - + +Note that you don't necesarily need to compile this on the machine +serving the blog but it's easier if you do. If you run it on another +machine you need to copy the post files and cgi executables around +yourself. + +There's nice tools like rsync and ssh that make this quite feasible +and it means you have a local backup as well. + +Templates +- - - - - + +The templates are just plain html - there is currently no template +parser. + +.meta data +- - - - - + +There is some meta data stored for each post in a filename which +matches the post filename but ends in .meta. + +There are some historic bits to this due to the blogger import, look +at newpost.c and makeindex.pl. + +Tags +- - - + +Currently there is a limit of 64 tags. + +URL Paths +- - - - - + +These are the implemented url paths. Having written them down it +looks like they could be improved. + +/blog +/blog/ + + The front page of the blog. + +/blog/{postid} + + Some other page of the blog starting from the given post. + +/post/{post-id} +/post/{post-date-title} + + Go to a specific post. + +/tag/{tag-name} + + The front page of the blog but only listing posts labelled with the + given keyword. + +/tag/{tag-name}?post={post-id} + + Some other page of the blog but only listing posts labelled with the + given keyword and starting from the given post. + +Where the variables are: + +post-id + + This is a 12-digit 0-padded hex encoding of the post timestamp, + which is the number of milliseconds since the epoch. + + For the search functions this is just treated as a timestamp. + +post-date-title + + This is the YYYY/MM/title-name.html name which provides + human-readable urls based on the original post date and title (YYYY + is year, MM is month). + + This isn't actually used much in the code and is a bit of a pain to + write in the posts but it works. + +robots.txt +- - - - - + +Because robots.txt is so uselessly primitive there probably isn't much +useful that can be done if you want to have it avoid crawling lots of +internal links to the same posts. It is also possible to create +infinite numbers of unique links when searching by timestamp. + +I guess at least /tag might help. + +This hasn't really been a problem because my website never shows up on +any search anyway! + +If I redo the url paths i'll consider this. /blog/{post-id} is the +most problematic. + +baggage +- - - - + +The .meta data contains an 'original' field which is used to create +the {post-data-name} index; it was from a blogger export. It should +be created from the title. + +It was written in a short span of time so some of the internals are a +bit pants and some of the URL path design could probably do with a +revisit. + +STATUS +------ + +This has been in production for about a year. Its simple and it +works. Creating new posts can be a bit finicky particularly when +including images but not more so than using a text-editor to write +html. + +The post-ids are hard-coded to 12 digit integers. This limits them to +about 8000 years from now. Ok that's not a problem. + +LINKS +----- + + o Directly related + - https://www.zedzone.space/software/blogz.html + Project page. + - https://www.zedzone.space/tag/blogz + Related blog posts. + +LICENSE +------- + +The license for all source is the GNU General Affero Public License, +version 3 or later. + +See COPYING for full details. + + Copyright (C) 2019 Michael Zucchi + + 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 . + \ No newline at end of file diff --git a/apache-site-cgi.conf b/apache-site-cgi.conf new file mode 100644 index 0000000..725c241 --- /dev/null +++ b/apache-site-cgi.conf @@ -0,0 +1,17 @@ + + + Define ENABLE_WWW_CGI + + + + Define ENABLE_WWW_CGI + + + + + AllowOverride None + Options +ExecCGI -MultiViews + Require all granted + + + diff --git a/apache-site.conf b/apache-site.conf new file mode 100644 index 0000000..2a5a5cd --- /dev/null +++ b/apache-site.conf @@ -0,0 +1,16 @@ + + ServerName www.site.name + + ServerAdmin webmaster@localhost + DocumentRoot /var/site/www + + ErrorLog ${APACHE_LOG_DIR}/error.log + CustomLog ${APACHE_LOG_DIR}/access.log combined + + Include conf-available/site-cgi.conf + + ScriptAlias "/blog" "/var/site/cgi-bin/blog.fcgi" + ScriptAlias "/post" "/var/site/cgi-bin/blog.fcgi" + ScriptAlias "/tag" "/var/site/cgi-bin/blog.fcgi" + + diff --git a/blog.c b/blog.c new file mode 100644 index 0000000..4b787d7 --- /dev/null +++ b/blog.c @@ -0,0 +1,487 @@ +/* + blog.c Main blogging engine. + + Copyright (C) 2019 Michael Zucchi + + 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 . +*/ + +#include + +#include +#include +#include +#include +#include +#include + +#include "config.h" + +#include "posts.h" +#include "template.h" +#include "blogio.h" +#include "etag.h" + +static const char *db = DB_POST; + +/** + * Basic CGI variable parser, silently truncates out of range values and other broken behaviour + */ + +struct cgi_param { + char *name; + char *value; +}; + +static int fromhex(int c) { + if (c>='0' && c<='9') + return c-'0'; + if (c>='a' && c <='f') + return c-'a'+10; + if (c>='A' && c <='F') + return c-'A'+10; + return -1; +} + +struct lex { + const char *q; + char data[64]; +}; + +/** + * Parses a url-encoded token + +returns 0 = end of input +-1 = error +boundary = hit boundary +separator = hit separator +*/ +static int lex_token(struct lex *lex, int separator, int boundary) { + const char *q = lex->q; + int i = 0; + + while (1) { + int c = *q++; + + if (c == 0 || c == separator || c == boundary) { + lex->data[i] = 0; + if (c == 0) + lex->q = q-1; + else + lex->q = q; + return c; + } else if (i < sizeof(lex->data)-1) { + int h, l; + + if (c == '%' + && (h = fromhex(q[0])) != -1 + && (l = fromhex(q[1])) != -1) { + c = (h << 4) | l; + q += 2; + } else if (c == '+') + c = ' '; + lex->data[i++] = c; + } else { + // overflow + return -1; + } + } +} + +/** + Decode a postid + returns first invalid character (non-hex) + or -1 on error, e.g. not a hex string +*/ +static int lex_id(struct lex *lex, postid_t *idp) { + char *q; + + *idp = strtoul(lex->q, &q, 16); + + if (q == lex->q) + return -1; + + lex->q = q; + return *q & 0xff; +} + +static int cgi_decode(const char *q, struct cgi_param *list, int length) { + struct lex lex; + int i = 0; + + lex.q = q; + + memset(list, 0, length * sizeof(list[0])); + + while (i < length) { + int c = lex_token(&lex, '&', '='); + char **p = &list[i].name; + + if (c == '=') { + if (lex.data[0]) { + *p = strdup(lex.data); + p = &list[i].value; + } + c = lex_token(&lex, '&', 0); + } + + if (c == '&' || c == 0) { + *p = strdup(lex.data); + i += 1; + break; + } else { + return -1; + } + } + + return i; +} + +static void cgi_params_free(struct cgi_param *list, int length) { + for (int i=0;i%s\n", how, stamp, buffer); +} + +static void post_footer(const char *how, postid_t id) { + const char *tags[64]; + int n; + + n = blog_tags(id, tags, 64); + + send("\n"); +} + +static void print_tags(void) { + const struct post_tag *list; + int n; + + // This dumps all tags onto a single line, otherwise it makes the html a pain to read. + n = blog_tag_list(&list); + if (n) { + send("

Tags

"); + + for (int i=0;i%s (%d)
", list[i].tag, list[i].postid_size); + } + + send("
\n"); + } +} + +static void print_nav(const char *title, const char *how, const char *path, postid_t id) { + if (path) + sendf("%s\n", how, path, id, title); + else + sendf("%s\n", how, id, title); +} + +// how is the script path +// path is the path component +// ids is the list of posts to include +// newer is the post at start of the previous page +// older is the post at the start of the next page +// latest is the id of the newest post on the page, for last-modified header +static void print_blog(const char *how, const char *path, postid_t *ids, int count, postid_t newer, postid_t older, postid_t latest) { + char file[strlen(db) + 32]; + int i; + + page_header(blog_time(latest)); + print_tags(); + + for (i=0;i\n"); + if (newer) { + print_nav("Newer Posts", how, path, newer); + } + if (older) { + if (newer) + send(" | "); + print_nav("Older Posts", how, path, older); + } + send("\n"); + } else if (count == 0) { + sendf("

This %s is empty.

\n", how); + } + page_footer(); +} + +// /blog[/][postid] +static void doblog(char *path, char *query) { + postid_t id; + postid_t ids[MAX_POSTS]; + postid_t newer, older; + int count; + int e = 400; + postid_t latest; + struct lex lex = { .q = path + 1 }; + + // Parameter processing + if (path == NULL || strlen(path) < 2) { + id = ULONG_MAX; + } else if (lex_id(&lex, &id) != 0) { + goto error; + } + + // Output + e = 404; + if ((count = blog_posts(id, ids, MAX_POSTS, &newer, &older)) == 0 && id != ULONG_MAX) + goto error; + e = 0; + + // Determine last-modified date + if (count) { + latest = blog_latest(); + if (newer == 0) + latest = ids[0]; + else if (latest > newer) + latest = newer; + } else { + latest = 0; + } + + print_blog(BLOG_SCRIPT, NULL, ids, count, newer, older, latest); + error: + error(e); +} + +// /tag/tag+name[/postid] +static void dotag(char *path, char *query) { + postid_t id; + postid_t ids[8]; + postid_t newer, older; + int count; + int tagid; + int e = 400; + postid_t latest; + struct lex lex = { .q = path + 1 }; + + // Parameter processing + id = ULONG_MAX; + if (path == NULL + || strlen(path) < 2 + || lex_token(&lex, '/', 0) == -1 + || (tagid = blog_tagid(lex.data)) == -1 + || (*lex.q && lex_id(&lex, &id) != 0)) { + goto error; + } + + // Output + e = 404; + if ((count = blog_search(id, tagid, ids, MAX_POSTS, &newer, &older)) == 0) + goto error; + + // Determine last-modified date + latest = blog_latest_tag(tagid); + if (newer == 0) + latest = ids[0]; + else if (latest > newer) + latest = newer; + + e = 0; + print_blog(TAG_SCRIPT, blog_tag_name(tagid), ids, count, newer, older, latest); + error: + error(e); +} + +// /post/{post-id} +// /post/{post-date-title} /post/YYYY/MM/{title} +static void dopost(const char *path, const char *query) { + postid_t id; + int e = 400; + struct lex lex = { .q = path + 1 }; + char file[strlen(db) + 32]; + postid_t newer, older; + postid_t ids[1]; + + // Parameter processing + if (path == NULL || strlen(path) < 2) + goto error; + + if (lex_id(&lex, &id) != 0) + id = blog_post(path+1); + e = 404; + if (blog_posts(id, ids, 1, &newer, &older) != 1) + goto error; + e = 0; + + // Output + sprintf(file, "%s/%012lx", db, id); + + page_header(blog_time(id)); + print_tags(); + + post_header("blog", id); + sendpath(file); + post_footer("blog", id); + + // TODO: Once I have a proper index this should output the post name + if (newer || older) { + send("
\n"); + if (newer) + sendf("Newer Post", newer); + if (older) { + if (newer) + send(" | "); + sendf("Older Post", older); + } + send("
\n"); + } + + page_footer(); + error: + error(e); +} + +static void execute(char *func, char *path, char *query) { + if (!strcmp(func, POST_SCRIPT)) { + dopost(path, query); + } else if (!strcmp(func, BLOG_SCRIPT)) { + doblog(path, query); + } else if (!strcmp(func, TAG_SCRIPT)) { + dotag(path, query); + } else { + error(500); + } +} + +#ifdef USE_FCGI +#include "fcgi.h" + +static int cgi_func(struct fcgi *cgi, void *data) { + char *etest = fcgi_getenv(cgi, "HTTP_IF_NONE_MATCH"); + + if (etest && 0 == strcmp(etest, etag)) { + fprintf(cgi->stdout, "Status: 304\nETag: %s\nContent-Type: text/plain\n\nUnmodified\n", etag); + } else { + char *func = fcgi_getenv(cgi, "SCRIPT_NAME"); + char *path = fcgi_getenv(cgi, "PATH_INFO"); + char *query = fcgi_getenv(cgi, "QUERY_STRING"); + + blogio_init(cgi); + execute(func, path, query); + blogio_init(NULL); + } + + return 0; +} + +int main(int argc, char **argv) { + struct fcgi *cgi = fcgi_alloc(); + int res; + + res = fcgi_accept_all(cgi, cgi_func, NULL); + fcgi_free(cgi); + + return res; +} +#else +int main(int argc, char **argv) { + char *func = getenv("SCRIPT_NAME"); + char *path = getenv("PATH_INFO"); + char *query = getenv("QUERY_STRING"); + + execute(func, path, query); + + return 0; +} +#endif diff --git a/blogio-fcgi.c b/blogio-fcgi.c new file mode 100644 index 0000000..5119421 --- /dev/null +++ b/blogio-fcgi.c @@ -0,0 +1,99 @@ +/* + blogio-fcgi.c I/O driver for FastCGI mode + + Copyright (C) 2019 Michael Zucchi + + 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 . +*/ + +#include +#include +#include +#include + +#include +#include + +#include "fcgi.h" +#include "blogio.h" + +static struct fcgi *cgi; + +int errorf(const char *fmt, ...) { + va_list ap; + int res; + + va_start(ap, fmt); + res = vfprintf(cgi->stderr, fmt, ap); + va_end(ap); + + return res; +} + +int send(const char *s) { + return fputs(s, cgi->stdout); +} + +int sendc(int c) { + return fputc(c, cgi->stdout); +} + +int sendf(const char *fmt, ...) { + va_list ap; + int res; + + va_start(ap, fmt); + res = vfprintf(cgi->stdout, fmt, ap); + va_end(ap); + + return res; +} + +int sendm(const void *mem, size_t size) { + return fwrite(mem, 1, size, cgi->stdout); +} + +ssize_t sendpath(const char *path) { + int fd; + char buffer[4096]; + + fflush(stdout); + + if ((fd = open(path, O_RDONLY)) != -1) { + ssize_t sent = 0; + ssize_t len; + + while ((len = read(fd, buffer, 4096)) > 0) { + len = fwrite(buffer, 1, len, cgi->stdout); + + if (len < 0) + break; + sent += len; + } + + close(fd); + + if (len < 0) + return len; + return sent; + } else { + errorf("blog: missing file '%s'\n", path); + } + + return -1; +} + +void blogio_init(void *ctx) { + cgi = ctx; +} diff --git a/blogio-stdio.c b/blogio-stdio.c new file mode 100644 index 0000000..fb026cb --- /dev/null +++ b/blogio-stdio.c @@ -0,0 +1,127 @@ +/* + blogio-stdio.c I/O driver for stdio or normal CGI. + + Copyright (C) 2019 Michael Zucchi + + 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 . +*/ + +#include +#include +#include +#include + +#include +#include + +#include "blogio.h" + +int errorf(const char *fmt, ...) { + va_list ap; + int res; + + va_start(ap, fmt); + res = vfprintf(stderr, fmt, ap); + va_end(ap); + + return res; +} + +int send(const char *s) { + return fputs(s, stdout); +} + +int sendc(int c) { + return fputc(c, stdout); +} + +int sendf(const char *fmt, ...) { + va_list ap; + int res; + + va_start(ap, fmt); + res = vfprintf(stdout, fmt, ap); + va_end(ap); + + return res; +} + +int sendm(const void *mem, size_t size) { + return fwrite(mem, 1, size, stdout); +} + +#ifdef USE_SENDFILE + +#include + +ssize_t sendpath(const char *path) { + int fd; + + fflush(stdout); + + if ((fd = open(path, O_RDONLY)) != -1) { + ssize_t sent; + struct stat st; + + fstat(fd, &st); + sent = sendfile(1, fd, NULL, st.st_size); + close(fd); + if (sent < st.st_size) { + errorf("blog: short write %zd != %zu\n", sent, st.st_size); + return -1; + } + return sent; + } else { + errorf("blog: missing file '%s'\n", path); + } + + return -1; +} + +#else + +ssize_t sendpath(const char *path) { + int fd; + char buffer[4096]; + + fflush(stdout); + + if ((fd = open(path, O_RDONLY)) != -1) { + ssize_t sent = 0; + ssize_t len; + + while ((len = read(fd, buffer, 4096)) > 0) { + len = fwrite(buffer, 1, len, stdout); + + if (len < 0) + break; + sent += len; + } + + close(fd); + + if (len < 0) + return len; + return sent; + } else { + errorf("blog: missing file '%s'\n", path); + } + + return -1; +} +#endif + +void blogio_init(void *ctx) { + // nop +} diff --git a/blogio.h b/blogio.h new file mode 100644 index 0000000..35c8c1d --- /dev/null +++ b/blogio.h @@ -0,0 +1,32 @@ +/* + blogio.h Interface for I/O drivers + + Copyright (C) 2019 Michael Zucchi + + 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 . +*/ + + +#include + +int errorf(const char *fmt, ...); + +int send(const char *s); +int sendc(int c); +int sendf(const char *fmt, ...); +int sendm(const void *mem, size_t size); + +ssize_t sendpath(const char *path); + +void blogio_init(void *ctx); diff --git a/config.h.in b/config.h.in new file mode 100644 index 0000000..1900202 --- /dev/null +++ b/config.h.in @@ -0,0 +1,30 @@ + +// config.make is auto-generated from config.h using sed. +// only include single-line comments and #define directives with simple values. + +// Install location for the cgi or fast cgi +#define cgibindir "/var/site/cgi-bin" +#define bindir "/var/site/bin" + +// Location of post files +#define DB_POST "/var/site/post" +#define DB_NEW "/var/site/post.new" + +// Use/group of post database / files +#define DB_USER "www-data" +#define DB_GROUP "www-data" + +// Number of posts per page +#define MAX_POSTS 8 + +// Whether to create a FastCGI binary +#define USE_FCGI 1 + +// Name of main installed binary +#define blog_bin "blog.fcgi" +//#define blog_bin "blog" +// If cgi mode is used, name of command that handles tag urls (softlink to blog_bin) +#define tag_bin "tag" +// If cgi mode is used, name of command that handles post urls (softlink to blog_bin) +#define post_bin "post" + diff --git a/fast-cgi.h b/fast-cgi.h new file mode 100644 index 0000000..7cfc062 --- /dev/null +++ b/fast-cgi.h @@ -0,0 +1,122 @@ +/* + This is copied from the Fast CGI specification. + + https://fastcgi-archives.github.io/FastCGI_Specification.html + Copyright © 1996 Open Market, Inc. 245 First Street, Cambridge, MA 02142 U.S.A. + */ + +#ifndef _FAST_CGI_H +#define _FAST_CGI_H + +/* + * Listening socket file number + */ +#define FCGI_LISTENSOCK_FILENO 0 + +typedef struct { + unsigned char version; + unsigned char type; + unsigned char requestIdB1; + unsigned char requestIdB0; + unsigned char contentLengthB1; + unsigned char contentLengthB0; + unsigned char paddingLength; + unsigned char reserved; +} FCGI_Header; + +/* + * Number of bytes in a FCGI_Header. Future versions of the protocol + * will not reduce this number. + */ +#define FCGI_HEADER_LEN 8 + +/* + * Value for version component of FCGI_Header + */ +#define FCGI_VERSION_1 1 + +/* + * Values for type component of FCGI_Header + */ +#define FCGI_BEGIN_REQUEST 1 +#define FCGI_ABORT_REQUEST 2 +#define FCGI_END_REQUEST 3 +#define FCGI_PARAMS 4 +#define FCGI_STDIN 5 +#define FCGI_STDOUT 6 +#define FCGI_STDERR 7 +#define FCGI_DATA 8 +#define FCGI_GET_VALUES 9 +#define FCGI_GET_VALUES_RESULT 10 +#define FCGI_UNKNOWN_TYPE 11 +#define FCGI_MAXTYPE (FCGI_UNKNOWN_TYPE) + +/* + * Value for requestId component of FCGI_Header + */ +#define FCGI_NULL_REQUEST_ID 0 + +typedef struct { + unsigned char roleB1; + unsigned char roleB0; + unsigned char flags; + unsigned char reserved[5]; +} FCGI_BeginRequestBody; + +typedef struct { + FCGI_Header header; + FCGI_BeginRequestBody body; +} FCGI_BeginRequestRecord; + +/* + * Mask for flags component of FCGI_BeginRequestBody + */ +#define FCGI_KEEP_CONN 1 + +/* + * Values for role component of FCGI_BeginRequestBody + */ +#define FCGI_RESPONDER 1 +#define FCGI_AUTHORIZER 2 +#define FCGI_FILTER 3 + +typedef struct { + unsigned char appStatusB3; + unsigned char appStatusB2; + unsigned char appStatusB1; + unsigned char appStatusB0; + unsigned char protocolStatus; + unsigned char reserved[3]; +} FCGI_EndRequestBody; + +typedef struct { + FCGI_Header header; + FCGI_EndRequestBody body; +} FCGI_EndRequestRecord; + +/* + * Values for protocolStatus component of FCGI_EndRequestBody + */ +#define FCGI_REQUEST_COMPLETE 0 +#define FCGI_CANT_MPX_CONN 1 +#define FCGI_OVERLOADED 2 +#define FCGI_UNKNOWN_ROLE 3 + +/* + * Variable names for FCGI_GET_VALUES / FCGI_GET_VALUES_RESULT records + */ +#define FCGI_MAX_CONNS "FCGI_MAX_CONNS" +#define FCGI_MAX_REQS "FCGI_MAX_REQS" +#define FCGI_MPXS_CONNS "FCGI_MPXS_CONNS" + +typedef struct { + unsigned char type; + unsigned char reserved[7]; +} FCGI_UnknownTypeBody; + +typedef struct { + FCGI_Header header; + FCGI_UnknownTypeBody body; +} FCGI_UnknownTypeRecord; + +#endif diff --git a/fcgi.c b/fcgi.c new file mode 100644 index 0000000..ff6c4a1 --- /dev/null +++ b/fcgi.c @@ -0,0 +1,382 @@ +/* + fcgi.c FastCGI library + + Copyright (C) 2019 Michael Zucchi + + 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 . +*/ + +#define _GNU_SOURCE + +#include +#include + +#include +#include + +#include + +#include "config.h" + +#include "fast-cgi.h" +#include "fcgi.h" + +#define obstack_chunk_alloc malloc +#define obstack_chunk_free free + +//#define L(x) do { if (!log) log = fopen("/tmp/fcgi.log", "w"); x; fflush(log); } while(0) +//static FILE *log; +#define L(x) + +/** + * This is a minimal FastCGI support library. + * + * It requires glibc; it uses obstacks to simplify memory management, + * and fopencookie() to hook up stdio streams to the fast cgi + * protocol. + */ + +static ssize_t fcgi_write(void *f, const char *buf, size_t size, int type) { + struct fcgi *cgi = f; + size_t sent = 0; + FCGI_Header header = { + .version = FCGI_VERSION_1, + .type = type, + .requestIdB1 = cgi->rid1, + .requestIdB0 = cgi->rid0 + }; + + while (sent < size) { + size_t left = size - sent; + ssize_t res; + + if (left > 65535) + left = 65535; + + header.contentLengthB1 = left >> 8; + header.contentLengthB0 = left & 0xff; + + if (1) { + struct iovec iov[2]; + + iov[0].iov_base = &header; + iov[0].iov_len = sizeof(header); + iov[1].iov_base = (void *)(buf + sent); + iov[1].iov_len = left; + + res = writev(cgi->fd, iov, 2); + if (res != sizeof(header) + left) { + L(fprintf(log, "%zd: short io %d write\n", res, type)); + L(fflush(stderr)); + } + } else { + res = write(cgi->fd, &header, sizeof(header)); + res = write(cgi->fd, buf + sent, left); + } + + if (res < 0) + return -1; + + sent += left; + } + + return size; +} + +static int fcgi_close(void *f, int type) { + struct fcgi *cgi = f; + FCGI_Header header = { + .version = FCGI_VERSION_1, + .type = type, + .requestIdB1 = cgi->rid1, + .requestIdB0 = cgi->rid0 + }; + if (write(cgi->fd, &header, sizeof(header)) < 0) + return -1; + return 0; +} + +static ssize_t fcgi_stdout_write(void *f, const char *buf, size_t size) { + return fcgi_write(f, buf, size, FCGI_STDOUT); +} + +static int fcgi_stdout_close(void *f) { + return fcgi_close(f, FCGI_STDOUT); +} + +static ssize_t fcgi_stderr_write(void *f, const char *buf, size_t size) { + return fcgi_write(f, buf, size, FCGI_STDERR); +} + +static int fcgi_stderr_close(void *f) { + return fcgi_close(f, FCGI_STDERR); +} + +const static cookie_io_functions_t fcgi_stdout = { + .read = NULL, + .write = fcgi_stdout_write, + .seek = NULL, + .close = fcgi_stdout_close +}; + +const static cookie_io_functions_t fcgi_stderr = { + .read = NULL, + .write = fcgi_stderr_write, + .seek = NULL, + .close = fcgi_stderr_close +}; + +struct fcgi *fcgi_alloc(void) { + struct fcgi *cgi = calloc(sizeof(*cgi), 1); + + cgi->buffer_size = 4096; + cgi->buffer = malloc(cgi->buffer_size); + + cgi->param_size = 32; + cgi->param = malloc(sizeof(*cgi->param) * cgi->param_size); + + obstack_init(&cgi->param_stack); + + return cgi; +} + +void fcgi_free(struct fcgi *cgi) { + // who cares! +} + +static int fcgi_init(struct fcgi *cgi, int fd) { + cgi->fd = fd; + + if (cgi->param_length > 0) + obstack_free(&cgi->param_stack, cgi->param[0].name); + cgi->param_length = 0; + cgi->pos = 0; + cgi->limit = 0; + + return 0; +} + +static int fcgi_begin(struct fcgi *cgi) { + cgi->stdout = fopencookie(cgi, "wb", fcgi_stdout); + cgi->stderr = fopencookie(cgi, "wb", fcgi_stderr); + + return 0; +} + +static void *fcgi_next(struct fcgi *cgi, size_t length) { + L(fprintf(log, "fcgi_next %zd limit=%zd pos=%zd\n", length, cgi->limit, cgi->pos)); + while (cgi->limit - cgi->pos < length) { + if (cgi->pos) { + memmove(cgi->buffer, cgi->buffer + cgi->pos, cgi->limit - cgi->pos); + cgi->limit = cgi->limit - cgi->pos; + cgi->pos = 0; + } + if (cgi->buffer_size < length) { + cgi->buffer = realloc(cgi->buffer, length); + cgi->buffer_size = length; + } + size_t len = read(cgi->fd, cgi->buffer + cgi->limit, cgi->buffer_size - cgi->limit); + if (len <= 0) + return NULL; // abort? + cgi->limit += len; + } + + void *p = cgi->buffer + cgi->pos; + + cgi->pos += length; + + return p; +} + +static int fcgi_read(struct fcgi *cgi, void *mem, size_t length) { + void *src = fcgi_next(cgi, length); + + if (src) { + memcpy(mem, src, length); + return length; + } + + return -1; +} + +static int fcgi_end_request(struct fcgi *cgi, unsigned int status, unsigned char fstatus) { + FCGI_EndRequestRecord rec = { + .header.version = FCGI_VERSION_1, + .header.type = FCGI_END_REQUEST, + .header.requestIdB1 = cgi->rid1, + .header.requestIdB0 = cgi->rid0, + .header.contentLengthB0 = 8, + + .body.appStatusB3 = (status >> 24) & 0xff, + .body.appStatusB2 = (status >> 16) & 0xff, + .body.appStatusB1 = (status >> 8) & 0xff, + .body.appStatusB0 = (status) & 0xff, + .body.protocolStatus = fstatus + }; + + if (cgi->stdout) { + fclose(cgi->stdout); + cgi->stdout = NULL; + } + + if (cgi->stdout) { + fclose(cgi->stdout); + cgi->stdout = NULL; + } + + //int res = write(cgi->fd, &rec, sizeof(rec)); + //if (res != sizeof(rec)) + // fprintf(log, "%d: end request short write\n", res); + if (write(cgi->fd, &rec, sizeof(rec)) < 0) + return -1; + + return 0; +} + +static int read_length(unsigned char **pp, unsigned char *e) { + unsigned char *p = *pp; + int len; + + L(fprintf(log, "read length: %02x %02x %02x %02x\n", p[0], p[1], p[2], p[3])); + + len = *p++; + if (len & 0x80) { + len = ((len & 0x7f) << 24) | (p[0] << 16) | (p[1] << 8) | (p[2]); + p += 3; + } + *pp = p; + return len; +} + +char *fcgi_getenv(struct fcgi *cgi, const char *name) { + for (int i = 0, e = cgi->param_length;iparam[i].name, name)) + return cgi->param[i].value; + } + return NULL; +} + + +int fcgi_accept_all(struct fcgi *cgi, fcgi_callback_t cb, void *data) { + int fd; + struct sockaddr_storage addr; + socklen_t addrlen = sizeof(addr); + int requests = 0; + + while ((fd = accept(FCGI_LISTENSOCK_FILENO, (struct sockaddr *)&addr, &addrlen)) > 0) { + FCGI_Header header; + int res; + int state = 0; + + fcgi_init(cgi, fd); + + while ((res = fcgi_read(cgi, &header, sizeof(header))) == sizeof(header)) { + int len = (header.contentLengthB1 << 8) | header.contentLengthB0; + int pad = header.paddingLength; + + L(fprintf(log, "%d [%d+%d]\n", header.type, len, pad)); + + switch (header.type) { + case FCGI_BEGIN_REQUEST: { + FCGI_BeginRequestBody body; + + if (state != 0) + return 1; + + requests++; + res = fcgi_read(cgi, &body, len); + fcgi_next(cgi, pad); + + cgi->role = (body.roleB1 << 8) | body.roleB0; + cgi->rid1 = header.requestIdB1; + cgi->rid0 = header.requestIdB0; + cgi->flags = body.flags; + + // KEEP_CONN not supported? + + L(fprintf(log, " role %d rid %02x%02x flags %d\n", cgi->role, cgi->rid1, cgi->rid0, cgi->flags)); + + if (cgi->role == FCGI_RESPONDER) + state = 1; + else { + fcgi_end_request(cgi, 0, FCGI_UNKNOWN_ROLE); + goto reaccept; + } + break; + } + case FCGI_PARAMS: + if (state != 1) + return 1; + + if (len > 0) { + unsigned char *p = fcgi_next(cgi, len + pad); + unsigned char *e = p + len; + int i = cgi->param_length; + + while (p < e) { + int n = read_length(&p, e); + int v = read_length(&p, e); + + if (i >= cgi->param_size) { + cgi->param_size *= 2; + cgi->param = realloc(cgi->param, cgi->param_size * sizeof(*cgi->param)); + } + + cgi->param[i].name = obstack_copy0(&cgi->param_stack, p, n); + p += n; + cgi->param[i].value = obstack_copy0(&cgi->param_stack, p, v); + p += v; + i += 1; + } + cgi->param_length = i; + } else { + state = 2; + } + break; + case FCGI_STDIN: + if (state != 2) + return 1; + + if (len > 0) { + // not supported + L(fprintf(log, "STDIN when not expecting it\n")); + fcgi_next(cgi, len + pad); + } else { + // TODO: longjmp for some errors + fcgi_begin(cgi); + res = cb(cgi, data); + fcgi_end_request(cgi, res, FCGI_REQUEST_COMPLETE); + + if ((cgi->flags & FCGI_KEEP_CONN) == 0) { + L(fprintf(log, "Closing socket %d\n", fd)); + close(fd); + goto reaccept; + } + } + break; + default: + L(fprintf(log, "Unsupported opcode: %d\n", header.type)); + fcgi_next(cgi, len + pad); + break; + } + } + reaccept: + L(fflush(log)); + addrlen = sizeof(addr); + } + + L(fprintf(log, "accept returned %d\n", fd)); + + return 0; +} diff --git a/fcgi.h b/fcgi.h new file mode 100644 index 0000000..a03299c --- /dev/null +++ b/fcgi.h @@ -0,0 +1,62 @@ +/* + fcgi.h FastCGI library + + Copyright (C) 2019 Michael Zucchi + + 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 . +*/ + +#ifndef _FCGI_H +#define _FCGI_H +#include +#include + +struct fcgi_param { + char *name; + char *value; +}; + +struct fcgi { + // Active during cgi request + FILE *stdout; + FILE *stderr; + + // Current request info + unsigned char rid1, rid0; + unsigned char flags; + unsigned char role; + + // Current request params (environment) + size_t param_length; + size_t param_size; + struct fcgi_param *param; + struct obstack param_stack; + + // Internal buffer stuff + int fd; + size_t pos; + size_t limit; + size_t buffer_size; + unsigned char *buffer; +}; + +typedef int (*fcgi_callback_t)(struct fcgi *, void *); + +struct fcgi *fcgi_alloc(void); +void fcgi_free(struct fcgi *cgi); + +int fcgi_accept_all(struct fcgi *cgi, fcgi_callback_t cb, void *data); +char *fcgi_getenv(struct fcgi *cgi, const char *name); + +#endif diff --git a/makeindex.pl b/makeindex.pl new file mode 100755 index 0000000..2efda9b --- /dev/null +++ b/makeindex.pl @@ -0,0 +1,169 @@ +#!/usr/bin/perl + +# makeindex.pl build the in-binary indices + +# Copyright (C) 2019 Michael Zucchi + +# 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 +# . + +$db = $ARGV[0]; + +%bymonth = (); +%byid = (); +%toindex = (); +$index = 0; + +@allids = (); +@allfiles = (); + +open IN,"ls -1 ${db} | grep -v meta | grep -v '~' | sort|" || die "Unable to find posts"; +while () { + chop; + $id = $_; + $name = $db."/".$id.".meta"; + open T,"<$name"; + while () { + chop; + if (m@^original=http.*\.com/(\d{4}/\d{2})/(.*)@) { + $part = $1; + $file = $2; + } + } + $byid{$id} = $file; + $toindex{$id} = $index; + push @{$bymonth{$part}}, $id; +# print "name $name id $id part $part\n"; + close T; + + push @allfiles, $file; + push @allids, $id; + + $index += 1; +} +close IN; + +print "static const postid_t post_id[] = {\n"; +$i = 0; +foreach $k (@allids) { + print " 0x$k,"; + $i++; + if ($i == 4) { + print "\n"; + $i = 0; + } +} +print "\n};\n"; + +print "static const char *post_file[] = {\n"; +foreach $k (@allfiles) { + print "\"$k\",\n"; +} +print "\n};\n"; + +print "static const struct post_index post_index[] = {\n"; + +foreach $k (sort keys %bymonth) { + @foo = @{$bymonth{$k}}; + $start = $toindex{$foo[0]}; + $end = $toindex{$foo[$#foo]}+1; + + print "{ \"$k\", $start, $end },\n //"; + foreach $d (@{$bymonth{$k}}) { + print " $toindex{$d}"; + } + foreach $d (@{$bymonth{$k}}) { + print " $byid{$d}"; + } + print("\n"); +} + +print "};\n"; + +# build keyword index +%allmeta = (); +%keytag = (); +%bytag = (); +# this is a simple indexed index +foreach $k (@allids) { + open (IN, "<$db/$k.meta") || next; + + while () { + if (m/^keywords=(.*)/) { + my $w = $1; + $allmeta{$k} = $w; + @words = split (/,/,$w); + for $word (@words) { + push @{$bytag{$word}}, $k; + } + } + } +} + +@keys = sort(keys %bytag); +%bases = (); +$i = 0; +$base = 0; +print "static const int post_tag_table"."[] = { "; +for $key (@keys) { + my @list = @{$bytag{$key}}; + print "/* $key */ "; + for $x (@list) { + print "$toindex{$x},"; + } + print "\n"; + $bases{$key} = $base; + $base += ($#list + 1); + $i++; +} +print "};\n"; + +print "static const struct post_tag post_tag[] = {\n"; +$i = 0; +for $key (@keys) { + my @list = @{$bytag{$key}}; + my $size= $#list + 1; + print " { \"$key\", $bases{$key}, $size },\n"; + $i++; +} +print "};\n"; + + +# Build inverse index +my %allbits = (); +$i = 1; +for $key (@keys) { + $allbits{$key} = $i; + $i *= 2; +} + +print "static const uint64_t post_tagmap[] = {\n"; +$i = 0; +foreach $k (@allids) { + my $w = $allmeta{$k}; + my $bits = 0; + + foreach $word (split (/,/,$w)) { + $bits |= $allbits{$word}; + } + printf (" 0x%016x,", $bits); + + $i++; + if ($i == 4) { + print "\n"; + $i = 0; + } +} +print "\n};\n"; + diff --git a/maketemplate.pl b/maketemplate.pl new file mode 100755 index 0000000..26c7710 --- /dev/null +++ b/maketemplate.pl @@ -0,0 +1,40 @@ +#!/usr/bin/perl + +# makeindex.pl build the in-binary indices + +# Copyright (C) 2019 Michael Zucchi + +# 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 +# . + +# There are no current template variables to this +# just outputs the html directly. + +$func = $ARGV[0]; +$src = $ARGV[1]; + +open X,"<$src" || die "Unable to open $src"; + +print "#include \"template.h\"\n"; +print "int $func(struct template_info *x) {\n return send(\n"; +while () { + s@\\@\\\\@g; + s@\"@\\\"@g; + s@\n@\\n@g; + print " \""; + print; + print "\"\n"; +} +print " );\n}\n"; +close X; diff --git a/newpost.c b/newpost.c new file mode 100644 index 0000000..a0f9c61 --- /dev/null +++ b/newpost.c @@ -0,0 +1,164 @@ +/* + newpost.c Create a new post + + Copyright (C) 2019 Michael Zucchi + + 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 . +*/ + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include "config.h" + +/** + * This is super-barebones. + * + * It just creates the post id and the meta-data file and calls an + * editor. + * + * New posts go into DB_POST ".new" while they're being edited and + * then they're moved to DB_POST if everything is successful. + * + * The .meta file is used by the makeindex.pl + */ + +int main(int argc, char **argv) { + struct timeval tv; + unsigned long ts; + char path[256]; + char cmd[256]; + char *title = NULL; + time_t mtime; + + if (argc == 2 + && (strcmp(argv[1], "-h") + || strcmp(argv[1], "--help"))) { + printf("Usage: %s [title [ keyword,keyword ... ] ]\n", argv[0]); + return 0; + } + + if (argc > 1) + title = argv[1]; + + gettimeofday(&tv, NULL); + + ts = (tv.tv_sec * 1000) + (tv.tv_usec / 1000); + + { + struct stat stb, sta; + FILE *post; + + sprintf(path, "%s/%012lx", DB_NEW, ts); + + post = fopen(path, "w"); + if (!post) { + perror("Cannot create post"); + return 1; + } + fprintf(post, "
\n", ts); + if (title) + fprintf(post, "

%s

\n", title); + fprintf(post, "
\n"); + if (fclose(post)) { + perror("Writing post header"); + return 1; + } + + stat(path, &sta); + + sprintf(cmd, "emacs --eval \"(setq-default major-mode 'html-mode)\" '%s'", path); + if (system(cmd) == -1) { + perror("Unable to run editor"); + unlink(path); + return 1; + } + stat(path, &stb); + + if (stb.st_mtime == sta.st_mtime) { + printf("No changes, post deleted.n"); + unlink(path); + return 0; + } + + mtime = stb.st_mtime; + } + { + FILE *meta; + + sprintf(cmd, "%s/%012lx.meta", DB_NEW, ts); + + meta = fopen(cmd, "w"); + if (!meta) { + perror("Creating metadata file"); + return 1; + } + + fprintf(meta, "mtime=%lu\n", mtime); + fprintf(meta, "ctime=%lu\n", ts); + if (argc > 2) + fprintf(meta, "keywords=%s\n", argv[2]); + fprintf(meta, "path=post/%012lx\n", ts); + + if (title) { + char c, *p = argv[1]; + time_t time = tv.tv_sec; + struct tm tm; + char buffer[256]; + + localtime_r(&time, &tm); + + strftime(buffer, sizeof(buffer), "%Y/%m", &tm); + + fprintf(meta, "title=%s\n", title); + fprintf(meta, "original=http://blogspot.com/%s/", buffer); + + while ((c = *p++)) { + if (isalnum(c)) + fputc(tolower(c), meta); + else if (c == ' ') + fputc('-', meta); + } + fprintf(meta, ".html\n"); + } + + fclose(meta); + + sprintf(cmd, "%s/%012lx.meta", DB_NEW, ts); + sprintf(path, "%s/%012lx.meta", DB_POST, ts); + + if (rename(cmd, path) != 0) { + perror("Renaming meta file"); + return 1; + } + + sprintf(cmd, "%s/%012lx", DB_NEW, ts); + sprintf(path, "%s/%012lx", DB_POST, ts); + + if (rename(cmd, path) != 0) { + perror("Renaming post file"); + return 1; + } + } + return 0; +} diff --git a/posts.c b/posts.c new file mode 100644 index 0000000..32fc6dc --- /dev/null +++ b/posts.c @@ -0,0 +1,245 @@ +/* + posts.c Post index database + + Copyright (C) 2019 Michael Zucchi + + 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 . +*/ + +#include +#include +#include +#include + +#include "config.h" + +#include "posts.h" +#include "posts-tables.h" + +#define post_id_SIZEOF (sizeof(post_id)/sizeof(post_id[0])) +#define post_index_SIZEOF (sizeof(post_index)/sizeof(post_index[0])) +#define post_tag_SIZEOF (sizeof(post_tag)/sizeof(post_tag[0])) + +static int cmp_postid(const void *ap, const void *bp) { + const postid_t *a = ap; + const postid_t *b = bp; + + if (*a < *b) + return -1; + else if (*a > *b) + return 1; + else + return 0; +} + +/** + * Convert postid to index, or -1 if no such post exists. + */ +int blog_postid(postid_t id) { + const postid_t *p = bsearch(&id, post_id, post_id_SIZEOF, sizeof(post_id[0]), cmp_postid); + + if (p) + return p - post_id; + else + return -1; +} + +/** + * Find up to 'max' posts which are younger than or equal to post 'from'. + */ +int blog_posts(postid_t from, postid_t *ids, int max, postid_t *newer, postid_t *older) { + int size =sizeof(post_id)/sizeof(post_id[0]); + int i; + int j = 0; + + if (from != ULONG_MAX) { + const postid_t *p = bsearch(&from, post_id, post_id_SIZEOF, sizeof(post_id[0]), cmp_postid); + + if (!p) + return 0; + + i = p - post_id; + } else { + i = size - 1; + } + + if (i == size-1) + *newer = 0; + else if (i + max >= size) + *newer = post_id[size-1]; + else + *newer = post_id[i+max]; + + while (i >= 0 && j < max) { + *ids = post_id[i]; + ids++; + i--; + j++; + } + + if (i >= 0 && j == max) + *older = post_id[i]; + else + *older = 0; + + return j; +} + +static int cmp_tagpostid(const void *ap, const void *bp) { + const postid_t *a = ap; + const int *cp = bp; + const postid_t b = post_id[*cp]; + + if (*a < b) + return -1; + else if (*a > b) + return 1; + else + return 0; +} + +int blog_search(postid_t from, int tagid, postid_t *ids, int max, postid_t *newer, postid_t *older) { + int i; + int j = 0; + const int *tag_postid = post_tag_table + post_tag[tagid].postid0; + int size = post_tag[tagid].postid_size; + + if (from != ULONG_MAX) { + const int *p = bsearch(&from, tag_postid, size, sizeof(tag_postid[0]), cmp_tagpostid); + + if (!p) + return 0; + + i = p - tag_postid; + } else { + i = size - 1; + } + + if (i == size-1) + *newer = 0; + else if (i + max >= size) + *newer = post_id[tag_postid[size-1]]; + else + *newer = post_id[tag_postid[i+max]]; + + while (i >= 0 && j < max) { + *ids = post_id[tag_postid[i]]; + ids++; + i--; + j++; + } + + if (i >= 0 && j == max) + *older = post_id[tag_postid[i]]; + else + *older = 0; + + return j; +} + +postid_t blog_latest(void) { + return (post_id_SIZEOF > 0) ? post_id[post_id_SIZEOF-1] : 0; +} + +postid_t blog_latest_tag(int tagid) { + const int *tag_postid = post_tag_table + post_tag[tagid].postid0; + int size = post_tag[tagid].postid_size; + + return (size > 0) ? post_id[tag_postid[size-1]] : 0; +} + +time_t blog_time(postid_t id) { + return id / 1000; +} + +static int cmp_month(const void *ap, const void *bp) { + const char *a = ap; + const struct post_index *b = bp; + + return strncmp(a, b->month, 7); +} + +/** + * Find post by long name + * YYYY/MM/stuff + */ +postid_t blog_post(const char *path) { + struct post_index *p; + + if (strlen(path) < 9) + return 0; + + p = bsearch(path, post_index, post_index_SIZEOF, sizeof(post_index[0]), cmp_month); + + if (p) { + int i1 = p->i1; + + for (int i=p->i0;itag); +} + +/** + * Find tags applied to a post + */ +int blog_tags(postid_t id, const char **tags, int max) { + const postid_t *p = bsearch(&id, post_id, post_id_SIZEOF, sizeof(post_id[0]), cmp_postid); + + if (p) { + uint64_t tagids = post_tagmap[p-post_id]; + int i, j = 0; + + for (i=0;i. +*/ + +#ifndef _POSTS_H +#define _POSTS_H + +struct post_index { + const char month[8]; + int i0, i1; +}; + +struct post_tag { + const char tag[32-8]; + int postid0; + int postid_size; +}; + +typedef uint64_t postid_t; + +int blog_postid(postid_t id); +int blog_posts(unsigned long from, unsigned long *ids, int max, unsigned long *newer, unsigned long *older); +postid_t blog_post(const char *path); +int blog_tagid(const char *tag); +int blog_search(postid_t from, int tagid, postid_t *ids, int max, postid_t *newer, postid_t *older); +int blog_tags(postid_t id, const char **tags, int max); + +postid_t blog_latest(void); +postid_t blog_latest_tag(int tagid); +time_t blog_time(postid_t id); + +int blog_tag_list(const struct post_tag **tags); +const char *blog_tag_name(unsigned int tagid); + +#endif diff --git a/template.h b/template.h new file mode 100644 index 0000000..923d34e --- /dev/null +++ b/template.h @@ -0,0 +1,9 @@ + +#include "blogio.h" + +struct template_info { +}; + +int blog_send_header(struct template_info *x); +int blog_send_footer(struct template_info *x); + diff --git a/template/blog-footer.html.in b/template/blog-footer.html.in new file mode 100644 index 0000000..346cd96 --- /dev/null +++ b/template/blog-footer.html.in @@ -0,0 +1,6 @@ +
+ Copyright (C) 2019 The Dude, No Rights Reserved. + Powered by gcc & NotZed! +
+ + diff --git a/template/blog-header.html.in b/template/blog-header.html.in new file mode 100644 index 0000000..47ef1cb --- /dev/null +++ b/template/blog-header.html.in @@ -0,0 +1,13 @@ + + + User Blog + + + +
+

About

+

The Dude

+
-- 2.39.2