packages feed

spacecookie (empty) → 0.2.0.1

raw patch · 16 files changed

+2471/−0 lines, 16 filesdep +aesondep +attoparsecdep +basesetup-changed

Dependencies added: aeson, attoparsec, base, bytestring, containers, directory, fast-logger, filepath, hxt-unicode, mtl, socket, spacecookie, transformers, unix

Files

+ CHANGELOG.md view
@@ -0,0 +1,8 @@+# Revision history for spacecookie++## 0.2.0.0 initial release++* First version. Released on an unsuspecting world. Includes:+  * Library for writing any gopher server / application.+  * File system based gopher server with support for gopher maps.+  * Supports logging, privilege dropping, the gopher protocol and common extensions.
+ LICENSE view
@@ -0,0 +1,674 @@+              GNU GENERAL PUBLIC LICENSE+                Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++                     Preamble++  The GNU General Public License is a free, copyleft license for+software and other kinds of works.++  The licenses for most software and other practical works are designed+to take away your freedom to share and change the works.  By contrast,+the GNU General Public License is 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.  We, the Free Software Foundation, use the+GNU General Public License for most of our software; it applies also to+any other work released this way by its authors.  You can apply it to+your programs, too.++  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.++  To protect your rights, we need to prevent others from denying you+these rights or asking you to surrender the rights.  Therefore, you have+certain responsibilities if you distribute copies of the software, or if+you modify it: responsibilities to respect the freedom of others.++  For example, if you distribute copies of such a program, whether+gratis or for a fee, you must pass on to the recipients the same+freedoms that you received.  You must make sure that they, too, receive+or can get the source code.  And you must show them these terms so they+know their rights.++  Developers that use the GNU GPL protect your rights with two steps:+(1) assert copyright on the software, and (2) offer you this License+giving you legal permission to copy, distribute and/or modify it.++  For the developers' and authors' protection, the GPL clearly explains+that there is no warranty for this free software.  For both users' and+authors' sake, the GPL requires that modified versions be marked as+changed, so that their problems will not be attributed erroneously to+authors of previous versions.++  Some devices are designed to deny users access to install or run+modified versions of the software inside them, although the manufacturer+can do so.  This is fundamentally incompatible with the aim of+protecting users' freedom to change the software.  The systematic+pattern of such abuse occurs in the area of products for individuals to+use, which is precisely where it is most unacceptable.  Therefore, we+have designed this version of the GPL to prohibit the practice for those+products.  If such problems arise substantially in other domains, we+stand ready to extend this provision to those domains in future versions+of the GPL, as needed to protect the freedom of users.++  Finally, every program is threatened constantly by software patents.+States should not allow patents to restrict development and use of+software on general-purpose computers, but in those that do, we wish to+avoid the special danger that patents applied to a free program could+make it effectively proprietary.  To prevent this, the GPL assures that+patents cannot be used to render the program non-free.++  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 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. Use with the GNU Affero General Public License.++  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 Affero 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 special requirements of the GNU Affero General Public License,+section 13, concerning interaction through a network will apply to the+combination as such.++  14. Revised Versions of this License.++  The Free Software Foundation may publish revised and/or new versions of+the GNU 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 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 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 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.++    <one line to give the program's name and a brief idea of what it does.>+    Copyright (C) <year>  <name of author>++    This program is free software: you can redistribute it and/or modify+    it under the terms of the GNU 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 General Public License for more details.++    You should have received a copy of the GNU General Public License+    along with this program.  If not, see <http://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++  If the program does terminal interaction, make it output a short+notice like this when it starts in an interactive mode:++    <program>  Copyright (C) <year>  <name of author>+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+    This is free software, and you are welcome to redistribute it+    under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License.  Of course, your program's commands+might be different; for a GUI interface, you would use an "about box".++  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 GPL, see+<http://www.gnu.org/licenses/>.++  The GNU General Public License does not permit incorporating your program+into proprietary programs.  If your program is a subroutine library, you+may consider it more useful to permit linking proprietary applications with+the library.  If this is what you want to do, use the GNU Lesser General+Public License instead of this License.  But first, please read+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+ README.md view
@@ -0,0 +1,75 @@+	 ____                                       _    _      +	/ ___| _ __   __ _  ___ ___  ___ ___   ___ | | _(_) ___ +	\___ \| '_ \ / _` |/ __/ _ \/ __/ _ \ / _ \| |/ / |/ _ \+	 ___) | |_) | (_| | (_|  __/ (_| (_) | (_) |   <| |  __/+	|____/| .__/ \__,_|\___\___|\___\___/ \___/|_|\_\_|\___|+	      |_|    – haskell gopher server++## What is Gopher?++> The Gopher protocol /ˈɡoʊfər/ is a TCP/IP application layer protocol designed for distributing, searching, and retrieving documents over the Internet. The Gopher protocol was strongly oriented towards a menu-document design and presented an alternative to the World Wide Web in its early stages, but ultimately HTTP became the dominant protocol. The Gopher ecosystem is often regarded as the effective predecessor of the World Wide Web.++– [WP](https://en.wikipedia.org/wiki/Gopher_(protocol))++## What is Spacecookie?++Spacecookie is a gopher server and…++* is RFC1436-compliant+* supports info-line in menus (compatible protocol extension)+* supports gophermaps (see below)+* includes a library for custom gopher applications++## Configuration++In order to run your new gopher server, you got to configure it first. The example configuration file is `./etc/spacecookie.json`.++Let's have a quick look at the options:++option     | meaning                                                 +-----------|--------------------------------------------------------------------------------------------------------+`hostname` | The hostname your spacecookie will be reachable through.+`user`     | The user that just run spacecookie. It is used to drop root priveleges after binding the server socket.+`port`     | The port spacecookie should listen on. The well-known port for gopher is 70.+`root`     | The directory which the files to serve via gopher are located in.++## Running++After you've created your config file just start spacecookie like this:++	spacecookie /path/to/spacecookie.json++Of course it is more convenient to run it as a system wide demon. For that reason a systemd `spacecookie.service` is provided. You can use it like this:++	systemctl enable spacecookie.service+	systemctl start  spacecookie.service++Please note that you have to move the necessary file in place manually at the moment.++## Adding Content++Spacecookie acts as a simple file server, only excluding files that start with a dot.+It generates gopher menus automatically; however you can use custom ones by adding a gophermap file.++Spacecookie checks for `.gophermap` in every directory it serves and, if present, uses the menu specified in there.++Such a file looks like this:++	You can just start writing text that+	will be displayed by the gopher client+	without a link to a file. Empty lines are+	also possible.++	1Menu Entry for a directory full of funny stuff	/funny+	iFunny Image	/funy.jpg+	gcat gif	/cat.gif+	0about me	/about.txt+	1Floodgap's gopher server	/	gopher.floodgap.com	70++So what does that all mean? These are the rules for a gophermap file:++* comment lines (called info lines in spacecookie's code) are just lines of text. They must not contain a tab! They will be displayed as lines of text by the gopher client.+* menu entries for files or directories start with a single char which specifies the file type, followed by the text for that file without a space or tab between them! Then the path is added after a tab.+* "Links" to other servers are like file/directory menu entries but the server's hostname and its port must be added (tab-separated).++The file type characters are defined in [RFC1436](https://tools.ietf.org/html/rfc1436#page-10). Detailed documentation on the gophermap format [can be found here](./docs/gophermap-pygopherd.txt).
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ docs/gophermap view
@@ -0,0 +1,14 @@+Welcome to Pygopherd!  You can place your documents+in /var/gopher for future use.  You can remove the gophermap+file there to get rid of this message, or you can edit it to+use other things.  (You'll need to do at least one of these+two things in order to get your own data to show up!)++Some links to get you started:++1Pygopherd Home	/devel/gopher/pygopherd	gopher.quux.org	70+1Quux.Org Mega Server	/	gopher.quux.org	70+1The Gopher Project	/Software/Gopher	gopher.quux.org	70+1Traditional UMN Home Gopher	/	gopher.tc.umn.edu	70++Welcome to the world of Gopher and enjoy!
+ docs/gophermap-pygopherd.txt view
@@ -0,0 +1,45 @@+GOPHERMAP FILE DOCUMENTATION FROM THE PYGOPHERD MAN PAGE++       The gophermap files contain two types of  lines,  which  are  described+       here  using  the  same  convention normally used for command line argu-+       ments.  In this section, the symbol \t will be used to indicate  a  tab+       character, Control-I.++        full line of informational text+++        gophertypeDESCRIPTION [ \tselector [ \thost [ \tport ] ] ]+++       Note:  spaces  shown above are for clarity only and should not actually+       be present in your file.++       The informational text must not contain any  tab  characters,  but  may+       contain  spaces.   Informational text will be rendered with gopher type+       i, which will cause it to be displayed on a client's screen at its par-+       ticular position in the file.++       The  second  type of line represents a link to a file or directory.  It+       begins with a single-character  Gopher  type  (see  Gopher  Item  Types+       below)  followed  immediately  by  a  description  and a tab character.+       There is no space or other separator between the gopher  type  and  the+       description.  The description may contain spaces but not tabs.++       The remaining arguments are optional, but only to the extent that argu-+       ments may be omitted only if all arguments after them are also omitted.+       These arguments are:++       selector+              The  selector  is  the  name  of  the file on the server.  If it+              begins with a slash, it is an absolute path;  otherwise,  it  is+              interpreted relative to the directory that the gophermap file is+              in.  If no selector is specified, the description is  also  used+              as the selector.++       host   The  host  specifies the host on which this resource is located.+              If not specified, defaults to the current server.++       port   The port specifies the port on which the  resource  is  located.+              If  not  specified,  defaults  to the port the current server is+              listening on.+
+ docs/rfc1436.txt view
@@ -0,0 +1,902 @@+
+
+
+
+
+
+Network Working Group                                     F. Anklesaria
+Request for Comments: 1436                                  M. McCahill
+                                                             P. Lindner
+                                                             D. Johnson
+                                                              D. Torrey
+                                                             B. Alberti
+                                                University of Minnesota
+                                                             March 1993
+
+
+                      The Internet Gopher Protocol
+         (a distributed document search and retrieval protocol)
+
+Status of this Memo
+
+   This memo provides information for the Internet community.  It does
+   not specify an Internet standard.  Distribution of this memo is
+   unlimited.
+
+Abstract
+
+   The Internet Gopher protocol is designed for distributed document
+   search and retrieval.  This document describes the protocol, lists
+   some of the implementations currently available, and has an overview
+   of how to implement new client and server applications.  This
+   document is adapted from the basic Internet Gopher protocol document
+   first issued by the Microcomputer Center at the University of
+   Minnesota in 1991.
+
+Introduction
+
+   gopher  n.  1. Any of various short tailed, burrowing mammals of the
+   family Geomyidae, of North America.  2. (Amer. colloq.) Native or
+   inhabitant of Minnesota: the Gopher State.  3. (Amer. colloq.) One
+   who runs errands, does odd-jobs, fetches or delivers documents for
+   office staff.  4. (computer tech.) software following a simple
+   protocol for burrowing through a TCP/IP internet.
+
+   The Internet Gopher protocol and software follow a client-server
+   model.  This protocol assumes a reliable data stream; TCP is assumed.
+   Gopher servers should listen on port 70 (port 70 is assigned to
+   Internet Gopher by IANA).  Documents reside on many autonomous
+   servers on the Internet.  Users run client software on their desktop
+   systems, connecting to a server and sending the server a selector (a
+   line of text, which may be empty) via a TCP connection at a well-
+   known port.  The server responds with a block of text terminated by a
+   period on a line by itself and closes the connection.  No state is
+   retained by the server.
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 1]
+
+RFC 1436                         Gopher                       March 1993
+
+
+   While documents (and services) reside on many servers, Gopher client
+   software presents users with a hierarchy of items and directories
+   much like a file system.  The Gopher interface is designed to
+   resemble a file system since a file system is a good model for
+   organizing documents and services; the user sees what amounts to one
+   big networked information system containing primarily document items,
+   directory items, and search items (the latter allowing searches for
+   documents across subsets of the information base).
+
+   Servers return either directory lists or documents.  Each item in a
+   directory is identified by a type (the kind of object the item is),
+   user-visible name (used to browse and select from listings), an
+   opaque selector string (typically containing a pathname used by the
+   destination host to locate the desired object), a host name (which
+   host to contact to obtain this item), and an IP port number (the port
+   at which the server process listens for connections). The user only
+   sees the user-visible name.  The client software can locate and
+   retrieve any item by the trio of selector, hostname, and port.
+
+   To use a search item, the client submits a query to a special kind of
+   Gopher server: a search server.  In this case, the client sends the
+   selector string (if any) and the list of words to be matched. The
+   response yields "virtual directory listings" that contain items
+   matching the search criteria.
+
+   Gopher servers and clients exist for all popular platforms.  Because
+   the protocol is so sparse and simple, writing servers or clients is
+   quick and straightforward.
+
+1.  Introduction
+
+   The Internet Gopher protocol is designed primarily to act as a
+   distributed document delivery system.  While documents (and services)
+   reside on many servers, Gopher client software presents users with a
+   hierarchy of items and directories much like a file system.  In fact,
+   the Gopher interface is designed to resemble a file system since a
+   file system is a good model for locating documents and services.  Why
+   model a campus-wide information system after a file system?  Several
+   reasons:
+
+      (a) A hierarchical arrangement of information is familiar to many
+      users.  Hierarchical directories containing items (such as
+      documents, servers, and subdirectories) are widely used in
+      electronic bulletin boards and other campus-wide information
+      systems. People who access a campus-wide information server will
+      expect some sort of hierarchical organization to the information
+      presented.
+
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 2]
+
+RFC 1436                         Gopher                       March 1993
+
+
+      (b) A file-system style hierarchy can be expressed in a simple
+      syntax.  The syntax used for the internet Gopher protocol is
+      easily understandable, and was designed to make debugging servers
+      and clients easy.  You can use Telnet to simulate an internet
+      Gopher client's requests and observe the responses from a server.
+      Special purpose software tools are not required.  By keeping the
+      syntax of the pseudo-file system client/server protocol simple, we
+      can also achieve better performance for a very common user
+      activity: browsing through the directory hierarchy.
+
+      (c) Since Gopher originated in a University setting, one of the
+      goals was for departments to have the option of publishing
+      information from their inexpensive desktop machines, and since
+      much of the information can be presented as simple text files
+      arranged in directories, a protocol modeled after a file system
+      has immediate utility.  Because there can be a direct mapping from
+      the file system on the user's desktop machine to the directory
+      structure published via the Gopher protocol, the problem of
+      writing server software for slow desktop systems is minimized.
+
+      (d) A file system metaphor is extensible.  By giving a "type"
+      attribute to items in the pseudo-file system, it is possible to
+      accommodate documents other than simple text documents.  Complex
+      database services can be handled as a separate type of item.  A
+      file-system metaphor does not rule out search or database-style
+      queries for access to documents.  A search-server type is also
+      defined in this pseudo-file system.  Such servers return "virtual
+      directories" or list of documents matching user specified
+      criteria.
+
+2.  The internet Gopher Model
+
+   A detailed BNF rendering of the internet Gopher syntax is available
+   in the appendix...but a close reading of the appendix may not be
+   necessary to understand the internet Gopher protocol.
+
+   In essence, the Gopher protocol consists of a client connecting to a
+   server and sending the server a selector (a line of text, which may
+   be empty) via a TCP connection.  The server responds with a block of
+   text terminated with a period on a line by itself, and closes the
+   connection.  No state is retained by the server between transactions
+   with a client. The simple nature of the protocol stems from the need
+   to implement servers and clients for the slow, smaller desktop
+   computers (1 MB Macs and DOS machines), quickly, and efficiently.
+
+   Below is a simple example of a client/server interaction; more
+   complex interactions are dealt with later.  Assume that a "well-
+   known" Gopher server (this may be duplicated, details are discussed
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 3]
+
+RFC 1436                         Gopher                       March 1993
+
+
+   later) listens at a well known port for the campus (much like a
+   domain-name server).  The only configuration information the client
+   software retains is this server's name and port number (in this
+   example that machine is rawBits.micro.umn.edu and the port 70). In
+   the example below the F character denotes the TAB character.
+
+ Client:          {Opens connection to rawBits.micro.umn.edu at port 70}
+
+ Server:          {Accepts connection but says nothing}
+
+ Client: <CR><LF> {Sends an empty line: Meaning "list what you have"}
+
+ Server:          {Sends a series of lines, each ending with CR LF}
+ 0About internet GopherFStuff:About usFrawBits.micro.umn.eduF70
+ 1Around University of MinnesotaFZ,5692,AUMFunderdog.micro.umn.eduF70
+ 1Microcomputer News & PricesFPrices/Fpserver.bookstore.umn.eduF70
+ 1Courses, Schedules, CalendarsFFevents.ais.umn.eduF9120
+ 1Student-Staff DirectoriesFFuinfo.ais.umn.eduF70
+ 1Departmental PublicationsFStuff:DP:FrawBits.micro.umn.eduF70
+                    {.....etc.....}
+ .                  {Period on a line by itself}
+                    {Server closes connection}
+
+
+   The first character on each line tells whether the line describes a
+   document, directory, or search service (characters '0', '1', '7';
+   there are a handful more of these characters described later).  The
+   succeeding characters up to the tab form a user display string to be
+   shown to the user for use in selecting this document (or directory)
+   for retrieval.  The first character of the line is really defining
+   the type of item described on this line. In nearly every case, the
+   Gopher client software will give the users some sort of idea about
+   what type of item this is (by displaying an icon, a short text tag,
+   or the like).
+
+   The characters following the tab, up to the next tab form a selector
+   string that the client software must send to the server to retrieve
+   the document (or directory listing).  The selector string should mean
+   nothing to the client software; it should never be modified by the
+   client.  In practice, the selector string is often a pathname or
+   other file selector used by the server to locate the item desired.
+   The next two tab delimited fields denote the domain-name of the host
+   that has this document (or directory), and the port at which to
+   connect.  If there are yet other tab delimited fields, the basic
+   Gopher client should ignore them.  A CR LF denotes the end of the
+   item.
+
+
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 4]
+
+RFC 1436                         Gopher                       March 1993
+
+
+   In the example, line 1 describes a document the user will see as
+   "About internet Gopher".  To retrieve this document, the client
+   software must send the retrieval string: "Stuff:About us" to
+   rawBits.micro.umn.edu at port 70.  If the client does this, the
+   server will respond with the contents of the document, terminated by
+   a period on a line by itself.  A client might present the user with a
+   view of the world something like the following list of items:
+
+
+      About Internet Gopher
+      Around the University of Minnesota...
+      Microcomputer News & Prices...
+      Courses, Schedules, Calendars...
+      Student-Staff Directories...
+      Departmental Publications...
+
+
+
+   In this case, directories are displayed with an ellipsis and files
+   are displayed without any.  However, depending on the platform the
+   client is written for and the author's taste, item types could be
+   denoted by other text tags or by icons.  For example, the UNIX
+   curses-based client displays directories with a slash (/) following
+   the name; Macintosh clients display directories alongside an icon of
+   a folder.
+
+   The user does not know or care that the items up for selection may
+   reside on many different machines anywhere on the Internet.
+
+   Suppose the user selects the line "Microcomputer News & Prices...".
+   This appears to be a directory, and so the user expects to see
+   contents of the directory upon request that it be fetched.  The
+   following lines illustrate the ensuing client-server interaction:
+
+
+    Client:           (Connects to pserver.bookstore.umn.edu at port 70)
+    Server:           (Accepts connection but says nothing)
+    Client: Prices/   (Sends the magic string terminated by CRLF)
+    Server:           (Sends a series of lines, each ending with CR LF)
+    0About PricesFPrices/AboutusFpserver.bookstore.umn.eduF70
+    0Macintosh PricesFPrices/MacFpserver.bookstore.umn.eduF70
+    0IBM PricesFPrices/IckFpserver.bookstore.umn.eduF70
+    0Printer & Peripheral PricesFPrices/PPPFpserver.bookstore.umn.eduF70
+                      (.....etc.....)
+    .                 (Period on a line by itself)
+                      (Server closes connection)
+
+
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 5]
+
+RFC 1436                         Gopher                       March 1993
+
+
+3. More details
+
+3.1  Locating services
+
+   Documents (or other services that may be viewed ultimately as
+   documents, such as a student-staff phonebook) are linked to the
+   machine they are on by the trio of selector string, machine domain-
+   name, and IP port.  It is assumed that there will be one well-known
+   top-level or root server for an institution or campus.  The
+   information on this server may be duplicated by one or more other
+   servers to avoid a single point of failure and to spread the load
+   over several servers.  Departments that wish to put up their own
+   departmental servers need to register the machine name and port with
+   the administrators of the top-level Gopher server, much the same way
+   as they register a machine name with the campus domain-name server.
+   An entry which points to the departmental server will then be made at
+   the top level server.  This ensures that users will be able to
+   navigate their way down what amounts to a virtual hierarchical file
+   system with a well known root to any campus server if they desire.
+
+   Note that there is no requirement that a department register
+   secondary servers with the central top-level server; they may just
+   place a link to the secondary servers in their own primary servers.
+   They may indeed place links to any servers they desire in their own
+   server, thus creating a customized view of thethe Gopher information
+   universe; links can of course point back at the top-level server.
+   The virtual (networked) file system is therefore an arbitrary graph
+   structure and not necessarily a rooted tree.  The top-level node is
+   merely one convenient, well-known point of entry.  A set of Gopher
+   servers linked in this manner may function as a campus-wide
+   information system.
+
+   Servers may of course point links at other than secondary servers.
+   Indeed servers may point at other servers offering useful services
+   anywhere on the internet.  Viewed in this manner, Gopher can be seen
+   as an Internet-wide information system.
+
+3.2 Server portability and naming
+
+   It is recommended that all registered servers have alias names
+   (domain name system CNAME) that are used by Gopher clients to locate
+   them.  Links to these servers should use these alias names rather
+   than the primary names.  If information needs to be moved from one
+   machine to another, a simple change of domain name system alias
+   (CNAME) allows this to occur without any reconfiguration of clients
+   in the field.  In short, the domain name system may be used to re-map
+   a server to a new address.  There is nothing to prevent secondary
+   servers or services from running on otherwise named servers or ports
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 6]
+
+RFC 1436                         Gopher                       March 1993
+
+
+   other than 70, however these should be reachable via a primary
+   server.
+
+3.3 Contacting server administrators
+
+   It is recommended that every server administrator have a document
+   called something like: "About Bogus University's Gopher server" as
+   the first item in their server's top level directory.  In this
+   document should be a short description of what the server holds, as
+   well as name, address, phone, and an e-mail address of the person who
+   administers the server.  This provides a way for users to get word to
+   the administrator of a server that has inaccurate information or is
+   not running correctly.  It is also recommended that administrators
+   place the date of last update in files for which such information
+   matters to the users.
+
+3.4  Modular addition of services
+
+   The first character of each line in a server-supplied directory
+   listing indicates whether the item is a file (character '0'), a
+   directory (character '1'), or a search (character '7').  This is the
+   base set of item types in the Gopher protocol.  It is desirable for
+   clients to be able to use different services and speak different
+   protocols (simple ones such as finger; others such as CSO phonebook
+   service, or Telnet, or X.500 directory service) as needs dictate.
+   CSO phonebook service is a client/server phonebook system typically
+   used at Universities to publish names, e-mail addresses, and so on.
+   The CSO phonebook software was developed at the University of
+   Illinois and is also sometimes refered to as ph or qi.  For example,
+   if a server-supplied directory listing marks a certain item with type
+   character '2', then it means that to use this item, the client must
+   speak the CSO protocol.  This removes the need to be able to
+   anticipate all future needs and hard-wire them in the basic Internet
+   Gopher protocol; it keeps the basic protocol extremely simple.  In
+   spite of this simplicity, the scheme has the capability to expand and
+   change with the times by adding an agreed upon type-character for a
+   new service.  This also allows the client implementations to evolve
+   in a modular fashion, simply by dropping in a module (or launching a
+   new process) for some new service.  The servers for the new service
+   of course have to know nothing about Internet Gopher; they can just
+   be off-the shelf CSO, X.500, or other servers.  We do not however,
+   encourage arbitrary or machine-specific proliferation of service
+   types in the basic Gopher protocol.
+
+   On the other hand, subsets of other document retrieval schemes may be
+   mapped onto the Gopher protocol by means of "gateway-servers".
+   Examples of such servers include Gopher-to-FTP gateways, Gopher-to-
+   archie gateways, Gopher-to-WAIS gateways, etc.  There are a number of
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 7]
+
+RFC 1436                         Gopher                       March 1993
+
+
+   advantages of such mechanisms. First, a relatively powerful server
+   machine inherits both the intelligence and work, rather than the more
+   modest, inexpensive desktop system that typically runs client
+   software or basic server software.  Equally important, clients do not
+   have to be modified to take advantage of a new resource.
+
+3.5  Building clients
+
+   A client simply sends the retrieval string to a server if it wants to
+   retrieve a document or view the contents of a directory.  Of course,
+   each host may have pointers to other hosts, resulting in a "graph"
+   (not necessarily a rooted tree) of hosts.  The client software may
+   save (or rather "stack") the locations that it has visited in search
+   of a document.  The user could therefore back out of the current
+   location by unwinding the stack.  Alternatively, a client with
+   multiple-window capability might just be able to display more than
+   one directory or document at the same time.
+
+   A smart client could cache the contents of visited directories
+   (rather than just the directory's item descriptor), thus avoiding
+   network transactions if the information has been previously
+   retrieved.
+
+   If a client does not understand what a say, type 'B' item (not a core
+   item) is, then it may simply ignore the item in the directory
+   listing; the user never even has to see it.  Alternatively, the item
+   could be displayed as an unknown type.
+
+   Top-level or primary servers for a campus are likely to get more
+   traffic than secondary servers, and it would be less tolerable for
+   such primary servers to be down for any long time.  So it makes sense
+   to "clone" such important servers and construct clients that can
+   randomly choose between two such equivalent primary servers when they
+   first connect (to balance server load), moving to one if the other
+   seems to be down.  In fact, smart client implementations do this
+   clone server and load balancing.  Alternatively, it may make sense to
+   have the domain name system return one of a set of redundant of
+   server's IP address to load balance betwen redundant sets of
+   important servers.
+
+3.6  Building ordinary internet Gopher servers
+
+   The retrieval string sent to the server might be a path to a file or
+   directory.  It might be the name of a script, an application or even
+   a query that generates the document or directory returned.  The basic
+   server uses the string it gets up to but not including a CR-LF or a
+   TAB, whichever comes first.
+
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 8]
+
+RFC 1436                         Gopher                       March 1993
+
+
+   All intelligence is carried by the server implementation rather than
+   the protocol.  What you build into more exotic servers is up to you.
+   Server implementations may grow as needs dictate and time allows.
+
+3.7  Special purpose servers
+
+   There are two special server types (beyond the normal Gopher server)
+   also discussed below:
+
+      1.  A server directory listing can point at a CSO nameserver (the
+      server returns a type character of '2') to allow a campus
+      student-staff phonebook lookup service.  This may show up on the
+      user's list of choices, perhaps preceded by the icon of a phone-
+      book.  If this item is selected, the client software must resort
+      to a pure CSO nameserver protocol when it connects to the
+      appropriate host.
+
+      2.  A server can also point at a "search server" (returns a first
+      character of '7').  Such servers may implement campus network (or
+      subnet) wide searching capability.  The most common search servers
+      maintain full-text indexes on the contents of text documents held
+      by some subset of Gopher servers.  Such a "full-text search
+      server" responds to client requests with a list of all documents
+      that contain one or more words (the search criteria).  The client
+      sends the server the selector string, a tab, and the search string
+      (words to search for). If the selector string is empty, the client
+      merely sends the search string.  The server returns the equivalent
+      of a directory listing for documents matching the search criteria.
+      Spaces between words are usually implied Boolean ANDs (although in
+      different implementations or search types, this may not
+      necessarily be true).
+
+   The CSO addition exists for historical reasons: at time of design,
+   the campus phone-book servers at the University of Minnesota used the
+   CSO protocol and it seemed simplest to just engulf them.  The index-
+   server is however very much a Gopher in spirit, albeit with a slight
+   twist in the meaning of the selector-string.  Index servers are a
+   natural place to incorperate gateways to WAIS and WHOIS services.
+
+3.7.1  Building CSO-servers
+
+   A CSO Nameserver implementation for UNIX and associated documentation
+   is available by anonymous ftp from uxa.cso.uiuc.edu.  We do not
+   anticipate implementing it on other machines.
+
+
+
+
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti         [Page 9]
+
+RFC 1436                         Gopher                       March 1993
+
+
+3.7.2  Building full-text search servers
+
+   A full-text search server is a special-purpose server that knows
+   about the Gopher scheme for retrieving documents.  These servers
+   maintain a full-text index of the contents of plain text documents on
+   Gopher servers in some specified domain.  A Gopher full-text search
+   server was implemented using several NeXTstations because it was easy
+   to take advantage of the full-text index/search engine built into the
+   NeXT system software.  A search server for generic UNIX systems based
+   on the public domain WAIS search engine, is also available and
+   currently an optional part of the UNIX gopher server.  In addition,
+   at least one implementation of the gopher server incorperates a
+   gateway to WAIS servers by presenting the WAIS servers to gopherspace
+   as full-text search servers.  The gopher<->WAIS gateway servers does
+   the work of translating from gopher protocol to WAIS so unmodified
+   gopher clients can access WAIS servers via the gateway server.
+
+   By using several index servers (rather than a monolithic index
+   server) indexes may be searched in parallel (although the client
+   software is not aware of this).  While maintaining full-text indexes
+   of documents distributed over many machines may seem a daunting task,
+   the task can be broken into smaller pieces (update only a portion of
+   the indexes, search several partial indexes in parallel) so that it
+   is manageable.  By spreading this task over several small, cheap (and
+   fast) workstations it is possible to take advantage of fine-grain
+   parallelism.  Again, the client software is not aware of this. Client
+   software only needs to know that it can send a search string to an
+   index server and will receive a list of documents that contain the
+   words in the search string.
+
+3.8  Item type characters
+
+   The client software decides what items are available by looking at
+   the first character of each line in a directory listing.  Augmenting
+   this list can extend the protocol.  A list of defined item-type
+   characters follows:
+
+   0   Item is a file
+   1   Item is a directory
+   2   Item is a CSO phone-book server
+   3   Error
+   4   Item is a BinHexed Macintosh file.
+   5   Item is DOS binary archive of some sort.
+       Client must read until the TCP connection closes.  Beware.
+   6   Item is a UNIX uuencoded file.
+   7   Item is an Index-Search server.
+   8   Item points to a text-based telnet session.
+   9   Item is a binary file!
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti        [Page 10]
+
+RFC 1436                         Gopher                       March 1993
+
+
+       Client must read until the TCP connection closes.  Beware.
+   +   Item is a redundant server
+   T   Item points to a text-based tn3270 session.
+   g   Item is a GIF format graphics file.
+   I   Item is some kind of image file.  Client decides how to display.
+
+   Characters '0' through 'Z' are reserved.  Local experiments should
+   use other characters.  Machine-specific extensions are not
+   encouraged.  Note that for type 5 or type 9 the client must be
+   prepared to read until the connection closes.  There will be no
+   period at the end of the file; the contents of these files are binary
+   and the client must decide what to do with them based perhaps on the
+   .xxx extension.
+
+3.9  User display strings and server selector strings
+
+   User display strings are intended to be displayed on a line on a
+   typical screen for a user's viewing pleasure.  While many screens can
+   accommodate 80 character lines, some space is needed to display a tag
+   of some sort to tell the user what sort of item this is.  Because of
+   this, the user display string should be kept under 70 characters in
+   length.  Clients may truncate to a length convenient to them.
+
+4.   Simplicity is intentional
+
+   As far as possible we desire any new features to be carried as new
+   protocols that will be hidden behind new document-types.  The
+   internet Gopher philosophy is:
+
+      (a) Intelligence is held by the server.  Clients have the option
+      of being able to access new document types (different, other types
+      of servers) by simply recognizing the document-type character.
+      Further intelligence to be borne by the protocol should be
+      minimized.
+
+      (b) The well-tempered server ought to send "text" (unless a file
+      must be transferred as raw binary).  Should this text include
+      tabs, formfeeds, frufru?  Probably not, but rude servers will
+      probably send them anyway.  Publishers of documents should be
+      given simple tools (filters) that will alert them if there are any
+      funny characters in the documents they wish to publish, and give
+      them the opportunity to strip the questionable characters out; the
+      publisher may well refuse.
+
+      (c) The well-tempered client should do something reasonable with
+      funny characters received in text; filter them out, leave them in,
+      whatever.
+
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti        [Page 11]
+
+RFC 1436                         Gopher                       March 1993
+
+
+Appendix
+
+   Paul's NQBNF (Not Quite BNF) for the Gopher Protocol.
+
+   Note:  This is modified BNF (as used by the Pascal people) with a few
+          English modifiers thrown in.  Stuff enclosed in '{}' can be
+          repeated zero or more times.  Stuff in '[]' denotes a set of
+          items.  The '-' operator denotes set subtraction.
+
+
+Directory Entity
+
+CR-LF     ::= ASCII Carriage Return Character followed by Line Feed
+              character.
+
+Tab       ::= ASCII Tab character.
+
+NUL       ::= ASCII NUL character.
+
+UNASCII   ::= ASCII - [Tab CR-LF NUL].
+
+Lastline  ::= '.'CR-LF.
+
+TextBlock ::= Block of ASCII text not containing Lastline pattern.
+
+Type      ::= UNASCII.
+
+RedType   ::= '+'.
+
+User_Name ::= {UNASCII}.
+
+Selector  ::= {UNASCII}.
+
+Host      ::= {{UNASCII - ['.']} '.'} {UNASCII - ['.']}.
+
+Note: This is a Fully Qualified Domain Name as defined in RFC 1034.
+      (e.g., gopher.micro.umn.edu)  Hosts that have a CR-LF
+      TAB or NUL in their name get what they deserve.
+
+Digit     ::= '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' .
+
+DigitSeq  ::= digit {digit}.
+
+Port      ::= DigitSeq.
+
+Note: Port corresponds the the TCP Port Number, its value should
+      be in the range [0..65535]; port 70 is officially assigned
+      to gopher.
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti        [Page 12]
+
+RFC 1436                         Gopher                       March 1993
+
+
+DirEntity ::= Type User_Name Tab Selector Tab Host Tab Port CR-LF
+          {RedType User_Name Tab Selector Tab Host Tab Port CR-LF}
+
+
+
+Notes:
+
+   It is *highly* recommended that the User_Name field contain only
+   printable characters, since many different clients will be using
+   it.  However if eight bit characters are used, the characters
+   should conform with the ISO Latin1 Character Set.  The length of
+   the User displayable line should be less than 70 Characters; longer
+   lines may not fit across some screens.
+
+   The Selector string should be no longer than 255 characters.
+
+
+Menu Entity
+
+Menu      ::= {DirEntity} Lastline.
+
+
+Menu Transaction  (Type 1 item)
+
+C: Opens Connection
+S: Accepts Connection
+C: Sends Selector String
+S: Sends Menu Entity
+
+   Connection is closed by either client or server (typically server).
+
+
+Textfile Entity
+
+TextFile  ::= {TextBlock} Lastline
+
+Note:  Lines beginning with periods must be prepended with an extra
+     period to ensure that the transmission is not terminated early.
+     The client should strip extra periods at the beginning of the line.
+
+
+TextFile Transaction (Type 0 item)
+
+C: Opens Connection.
+S: Accepts connection
+C: Sends Selector String.
+S: Sends TextFile Entity.
+
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti        [Page 13]
+
+RFC 1436                         Gopher                       March 1993
+
+
+   Connection is closed by either client or server (typically server).
+
+Note:  The client should be prepared for the server closing the
+       connection without sending the Lastline.  This allows the
+       client to use fingerd servers.
+
+
+Full-Text Search Transaction (Type 7 item)
+
+Word      ::= {UNASCII - ' '}
+BoolOp ::= 'and' | 'or' | 'not' | SPACE
+SearchStr ::= Word {{SPACE BoolOp} SPACE Word}
+
+C: Opens Connection.
+C: Sends Selector String, Tab, Search String.
+S: Sends Menu Entity.
+
+Note:  In absence of 'and', 'or', or 'not' operators, a SPACE is
+       regarded as an implied 'and' operator.  Expression is evaluated
+       left to right.  Further, not all search engines or search
+       gateways currently implemented have the boolean operators
+       implemented.
+
+Binary file Transaction (Type 9 or 5 item)
+
+C: Opens Connection.
+S: Accepts connection
+C: Sends Selector String.
+S: Sends a binary file and closes connection when done.
+
+
+Syntactic Meaning for Directory Entities
+
+
+The client should interpret the type field as follows:
+
+0   The item is a TextFile Entity.
+    Client should use a TextFile Transaction.
+
+1   The item is a Menu Entity.
+    Client should use a Menu Transaction.
+
+2   The information applies to a CSO phone book entity.
+    Client should talk CSO protocol.
+
+3   Signals an error condition.
+
+4   Item is a Macintosh file encoded in BINHEX format
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti        [Page 14]
+
+RFC 1436                         Gopher                       March 1993
+
+
+5   Item is PC-DOS binary file of some sort.  Client gets to decide.
+
+6   Item is a uuencoded file.
+
+7   The information applies to a Index Server.
+    Client should use a FullText Search transaction.
+
+8   The information applies to a Telnet session.
+    Connect to given host at given port. The name to login as at this
+    host is in the selector string.
+
+9   Item is a binary file.  Client must decide what to do with it.
+
++   The information applies to a duplicated server.  The information
+    contained within is a duplicate of the primary server.  The primary
+    server is defined as the last DirEntity that is has a non-plus
+    "Type" field.  The client should use the transaction as defined by
+    the primary server Type field.
+
+g   Item is a GIF graphic file.
+
+I   Item is some kind of image file.  Client gets to decide.
+
+T   The information applies to a tn3270 based telnet session.
+    Connect to given host at given port. The name to login as at this
+    host is in the selector string.
+
+Security Considerations
+
+   Security issues are not discussed in this memo.
+
+Authors' Addresses
+
+   Farhad Anklesaria
+   Computer and Information Services, University of Minnesota
+   Room 152 Shepherd Labs
+   100 Union Street SE
+   Minneapolis, MN 55455
+
+   Phone: (612) 625 1300
+   EMail: fxa@boombox.micro.umn.edu
+
+
+
+
+
+
+
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti        [Page 15]
+
+RFC 1436                         Gopher                       March 1993
+
+
+   Mark McCahill
+   Computer and Information Services, University of Minnesota
+   Room 152 Shepherd Labs
+   100 Union Street SE
+   Minneapolis, MN 55455
+
+   Phone: (612) 625 1300
+   EMail: mpm@boombox.micro.umn.edu
+
+
+   Paul Lindner
+   Computer and Information Services, University of Minnesota
+   Room 152 Shepherd Labs
+   100 Union Street SE
+   Minneapolis, MN 55455
+
+   Phone: (612) 625 1300
+   EMail: lindner@boombox.micro.umn.edu
+
+
+   David Johnson
+   Computer and Information Services, University of Minnesota
+   Room 152 Shepherd Labs
+   100 Union Street SE
+   Minneapolis, MN 55455
+
+   Phone: (612) 625 1300
+   EMail: dmj@boombox.micro.umn.edu
+
+
+   Daniel Torrey
+   Computer and Information Services, University of Minnesota
+   Room 152 Shepherd Labs
+   100 Union Street SE
+   Minneapolis, MN 55455
+
+   Phone: (612) 625 1300
+   EMail: daniel@boombox.micro.umn.edu
+
+
+   Bob Alberti
+   Computer and Information Services, University of Minnesota
+   Room 152 Shepherd Labs
+   100 Union Street SE
+   Minneapolis, MN 55455
+
+   Phone: (612) 625 1300
+   EMail: alberti@boombox.micro.umn.edu
+
+
+
+Anklesari, McCahill, Lindner, Johnson, Torrey & Alberti        [Page 16]
+
+
+
+.
+ etc/spacecookie.json view
@@ -0,0 +1,6 @@+{+  "hostname" : "localhost",+  "user" : "lukas",+  "port" : 7070,+  "root" : "./tmp"+}
+ etc/spacecookie.service view
@@ -0,0 +1,10 @@+[Unit]+Description=Spacecookie Gopher Daemon+After=network.target++[Service]+Type=simple+ExecStart=/usr/local/bin/spacecookie /usr/local/etc/spacecookie.json++[Install]+WantedBy=multi-user.target
+ server/Config.hs view
@@ -0,0 +1,42 @@+{-# LANGUAGE OverloadedStrings #-}+module Config+  ( Config (..)+  ) where++import Control.Applicative ((<$>), (<*>))+import Control.Monad (mzero)+import Data.Aeson+import Data.Aeson.Types+import Data.ByteString (ByteString ())+import qualified Data.ByteString as B+import Network.Gopher.Util++data Config = Config { serverName    :: ByteString+                     , serverPort    :: Integer+                     , runUserName   :: String+                     , rootDirectory :: FilePath+                     }++instance FromJSON Config where+  parseJSON (Object v) = Config <$>+    v .: "hostname" <*>+    v .: "port" <*>+    v .: "user" <*>+    v .: "root"+  parseJSON _ = mzero++instance ToJSON Config where+  toJSON (Config host port user root) = object+    [ "hostname" .= host+    , "port" .= port+    , "user" .= user+    , "root" .= root+    ]++-- auxiliary instances for types that have no default instance+instance FromJSON ByteString where+  parseJSON (String s) = uEncode <$> (parseJSON (String s))+  parseJSON _ = mzero++instance ToJSON ByteString where+  toJSON = toJSON . uDecode
+ server/Main.hs view
@@ -0,0 +1,123 @@+{-# LANGUAGE OverloadedStrings #-}+import Config+import Network.Gopher+import Network.Gopher.Util (santinizePath, uEncode)+import Network.Gopher.Util.Gophermap+import Data.ByteString (ByteString ())+import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as BL+import Data.List (isPrefixOf)+import Control.Applicative ((<|>), (<$>), pure)+import Control.Monad (unless, filterM, sequence, join)+import Control.Monad.IO.Class (liftIO)+import Data.Aeson (decode)+import Data.Attoparsec.ByteString (parseOnly)+import Data.Char (toLower)+import Data.Maybe (fromJust)+import System.Directory (doesDirectoryExist, doesFileExist, getDirectoryContents)+import System.Environment+import System.FilePath.Posix (takeFileName, takeExtension, (</>), dropDrive, splitDirectories)+import System.Posix.Directory (changeWorkingDirectory)++main :: IO ()+main = do+  args <- getArgs+  case args of+    [ configFile ] -> do+      doesFileExist configFile >>= (flip unless) (error "could not open config file")+      config' <- decode <$> BL.readFile configFile+      case config' of+        Just config -> do+          changeWorkingDirectory (rootDirectory config)+          runGopher (GopherConfig (serverName config) (serverPort config) ((Just (runUserName config)))) spacecookie+        Nothing -> error "failed to parse config"+    _ -> error "config file must be given"++spacecookie :: String -> IO GopherResponse+spacecookie path' = do+  let path = "." </> dropDrive (santinizePath path')+  fileType <- gopherFileType path+  pathType <- pathType path++  if not (isListable pathType path')+    then pure . ErrorResponse $ "Accessing '" ++ path' ++ "' is not allowed."+    else case fileType of+           Error -> pure $+             if "URL:" `isPrefixOf` path'+               then ErrorResponse $ "spacecookie does not support proxying HTTP, try using a gopher client that supports the h-type. If you tried to request a file called '" ++ path' ++ "', it does not exist."+               else ErrorResponse $ "The requested file '" ++ path' ++ "' does not exist or is not available."+           -- always use gophermapResponse which falls back+           -- to directoryResponse if there is no gophermap file+           Directory -> gophermapResponse path+           _ -> fileResponse path++fileResponse :: FilePath -> IO GopherResponse+fileResponse path = FileResponse <$> B.readFile path++makeAbsolute :: FilePath -> FilePath+makeAbsolute x = if "./" `isPrefixOf` x+                   then tail x+                   else x++directoryResponse :: FilePath -> IO GopherResponse+directoryResponse path = do+  dir <- join (filterM (\x -> ((flip isListable) x) <$> pathType x) . map (path </>) <$> getDirectoryContents path)+  fileTypes <- mapM gopherFileType dir+  pure . MenuResponse . map (\f -> f Nothing Nothing) $ zipWith (\t f -> Item t (uEncode (takeFileName f)) f) fileTypes (map makeAbsolute dir)++gophermapResponse :: FilePath -> IO GopherResponse+gophermapResponse path = do+  let gophermap = path </> ".gophermap"+  exists <- doesFileExist gophermap+  parsed <- if exists+              then parseOnly parseGophermap <$> B.readFile gophermap+              else pure $ Left "Gophermap file does not exist"+  case parsed of+    Left _ -> directoryResponse path+    Right right -> pure $ gophermapToDirectoryResponse right++-- | calculates the file type identifier used in the Gopher protocol+-- for a given file+gopherFileType :: FilePath -> IO GopherFileType+gopherFileType f = do+  isDir  <- ioCheck Directory doesDirectoryExist+  isFile <- ioCheck File doesFileExist+  let isGif = boolToMaybe GifFile $ takeExtension f == "gif"+  let isImage = boolToMaybe ImageFile $ map toLower (takeExtension f) `elem` ["png", "jpg", "jpeg", "raw", "cr2", "nef"]+  return . fromJust $+    isDir <|> isGif <|> isImage <|>  isFile <|> Just Error+  where ioCheck onSuccess check = fmap (boolToMaybe onSuccess) . check $ f++-- | isListable filters out system files for directory listings+isListable :: PathType -> FilePath -> Bool+isListable Directory' "" = True -- "" is root+isListable _ "" = False+isListable DoesNotExist _ = False+isListable Directory' p+  | (head . last . splitDirectories) p == '.' = False+  | otherwise = True+isListable File' p+  | head (takeFileName p) == '.' = False+  | otherwise = True++-- | True -> Just a+--   False -> Nothing+boolToMaybe :: a -> Bool -> Maybe a+boolToMaybe a True  = Just a+boolToMaybe _ False = Nothing++data PathType+  = Directory'+  | File'+  | DoesNotExist+  deriving (Show, Eq)++pathType :: FilePath -> IO PathType+pathType p = do+  file <- doesFileExist p+  dir  <- doesDirectoryExist p+  if file+    then pure File'+    else if dir+      then pure Directory'+      else pure DoesNotExist
+ spacecookie.cabal view
@@ -0,0 +1,64 @@+name:                spacecookie+version:             0.2.0.1+synopsis:            gopher server daemon+description:         simple gopher server daemon+license:             GPL-3+license-file:        LICENSE+author:              Lukas Epple+maintainer:          git@lukasepple.de+category:            Network+build-type:          Simple+cabal-version:       >=1.10+homepage:            https://github.com/sternenseemann/spacecookie+bug-reports:         https://github.com/sternenseemann/spacecookie/issues+extra-source-files:  CHANGELOG.md+                     README.md+                     etc/spacecookie.json+                     etc/spacecookie.service+                     docs/gophermap+                     docs/gophermap-pygopherd.txt+                     docs/rfc1436.txt++executable spacecookie+  main-is:             Main.hs+  build-depends:       base >= 4.9.0.0 && <5+                     , socket+                     , unix+                     , directory+                     , filepath+                     , containers+                     , bytestring+                     , filepath+                     , mtl+                     , transformers+                     , aeson+                     , attoparsec+                     , spacecookie+  hs-source-dirs:      server+  default-language:    Haskell2010+  other-modules:       Config++library+  hs-source-dirs:      src+  default-language:    Haskell2010+  exposed-modules:     Network.Gopher+                     , Network.Gopher.Util.Gophermap+                     , Network.Gopher.Util+  other-modules:       Network.Gopher.Types+  build-depends:       base >= 4.9.0 && <5+                     , socket+                     , unix+                     , directory+                     , filepath+                     , containers+                     , bytestring+                     , filepath+                     , mtl+                     , transformers+                     , attoparsec+                     , hxt-unicode+                     , fast-logger >= 2.4.0 && < 2.5++source-repository head+  type: git+  location: git://github.com/sternenseemann/spacecookie.git
+ src/Network/Gopher.hs view
@@ -0,0 +1,206 @@+{-# LANGUAGE OverloadedStrings #-}+{-|+Module      : Network.Gopher+Stability   : experimental+Portability : POSIX++= Overview++This is the main module of the spacecookie library. It allows to write gopher applications by taking care of handling gopher requests while leaving the application logic to a user-supplied function.++For a small tutorial an example of a trivial pure gopher application:++@+{-# LANGUAGE OverloadedStrings #-}+import Network.Gopher+import Network.Gopher.Util++main = do+  'runGopherPure' ('GopherConfig' "localhost" 7000 Nothing) (\\req -> 'FileResponse' ('uEncode' req))+@++This server just returns the request string as a file.++There are three possibilities for a 'GopherResponse':++* 'FileResponse': file type agnostic file response, takes a 'ByteString' to support both text and binary files+* 'MenuResponse': a gopher menu (“directory listning”) consisting of a list of 'GopherMenuItem's+* 'ErrorResponse': gopher way to show an error (e. g. if a file is not found). A 'ErrorResponse' results in a menu response with a single entry.++If you use 'runGopher', it is the same story like in the example above, but you can do 'IO' effects. To see a more elaborate example, have a look at the server code in this package.+-}++{-# LANGUAGE GeneralizedNewtypeDeriving #-}+module Network.Gopher (+  -- * Main API+    runGopher+  , runGopherPure+  , GopherConfig (..)+  -- * Helper Functions+  , gophermapToDirectoryResponse+  -- * Representations+  -- ** Responses+  , GopherResponse (..)+  , GopherMenuItem (..)+  , GopherFileType (..)+  -- ** Gophermaps+  , GophermapEntry (..)+  , Gophermap (..)+  ) where++import Prelude hiding (log)++import Network.Gopher.Types+import Network.Gopher.Util+import Network.Gopher.Util.Gophermap++import Control.Applicative ((<$>), (<*>), Applicative (..))+import Control.Concurrent (forkIO, ThreadId ())+import Control.Exception (bracket, catch, IOException (..))+import Control.Monad (forever, when)+import Control.Monad.IO.Class (liftIO, MonadIO (..))+import Control.Monad.Reader (ask, runReaderT, MonadReader (..), ReaderT (..))+import Control.Monad.Error.Class (MonadError (..))+import Data.ByteString (ByteString ())+import qualified Data.ByteString as B+import Data.Maybe (isJust, fromJust, fromMaybe)+import Data.Monoid ((<>))+import qualified Data.String.UTF8 as U+import System.IO+import System.Log.FastLogger+import System.Log.FastLogger.Date+import System.Socket hiding (Error (..))+import System.Socket.Family.Inet6+import System.Socket.Type.Stream+import System.Socket.Protocol.TCP+import System.Posix.User++-- | necessary information to handle gopher requests+data GopherConfig+  = GopherConfig { cServerName    :: ByteString   -- ^ “name” of the server (either ip address or dns name)+                 , cServerPort    :: Integer      -- ^ port to listen on+                 , cRunUserName   :: Maybe String -- ^ user to run the process as+                 }++data Env+  = Env { serverSocket :: Socket Inet6 Stream TCP+        , serverName   :: ByteString+        , serverPort   :: Integer+        , serverFun    :: (String -> IO GopherResponse)+        , logger       :: (TimedFastLogger, IO ()) -- ^ TimedFastLogger and clean up action+        }++initEnv :: Socket Inet6 Stream TCP -> ByteString -> Integer -> (String -> IO GopherResponse) -> IO Env+initEnv sock name port fun = do+  timeCache <- newTimeCache simpleTimeFormat+  logger <- newTimedFastLogger timeCache (LogStderr 128)+  pure $ Env sock name port fun logger++newtype GopherM a = GopherM { runGopherM :: ReaderT Env IO a }+  deriving ( Functor, Applicative, Monad+           , MonadIO, MonadReader Env, MonadError IOException)++gopherM env action = (runReaderT . runGopherM) action env++data LogMessage = LogError String | LogInfo String++instance ToLogStr LogMessage where+  toLogStr (LogError s) = "[Error] " <> toLogStr s+  toLogStr (LogInfo s)  = "[Info] " <> toLogStr s++log :: LogMessage -> GopherM ()+log logMsg = do+  (logger, _) <- logger <$> ask+  liftIO $ logger (\t -> "[" <> toLogStr t <> "]" <> (toLogStr logMsg) <> "\n")++receiveRequest :: Socket Inet6 Stream TCP -> IO ByteString+receiveRequest sock = receiveRequest' sock mempty+  where lengthLimit = 1024+        receiveRequest' sock acc = do+          bs <- liftIO $ receive sock lengthLimit mempty+          case (B.elemIndex (asciiOrd '\n') bs) of+            Just i -> return (acc `B.append` (B.take (i + 1) bs))+            Nothing -> if B.length bs < lengthLimit+                         then return (acc `B.append` bs)+                         else receiveRequest' sock (acc `B.append` bs)++dropPrivileges :: String -> IO ()+dropPrivileges username = do+  uid <- getRealUserID+  when (uid /= 0) $ return ()++  user <- getUserEntryForName username+  setGroupID $ userGroupID user+  setUserID $ userID user++-- | Run a gopher application that may cause effects in 'IO'.+--   The application function is given the gopher request (path)+--   and required to produce a GopherResponse.+runGopher :: GopherConfig -> (String -> IO GopherResponse) -> IO ()+runGopher cfg f = bracket+  (socket :: IO (Socket Inet6 Stream TCP))+  close+  (\sock -> do+    env <- initEnv sock (cServerName cfg) (fromInteger (cServerPort cfg)) f+    gopherM env $ do+      liftIO $ setSocketOption sock (ReuseAddress True)+      liftIO $ setSocketOption sock (V6Only False)+      liftIO $ bind sock (SocketAddressInet6 inet6Any (fromInteger (cServerPort cfg)) 0 0)+      liftIO $ listen sock 5+      log. LogInfo $ "Now listening [::]:" ++ show (cServerPort cfg)++      -- Change UID and GID if necessary+      if isJust (cRunUserName cfg)+        then do+          liftIO (dropPrivileges (fromJust (cRunUserName cfg)))+          log . LogInfo $ "Dropped privileges to " ++ fromJust (cRunUserName cfg)+        else log .LogInfo $ "Privileges were not dropped"++      (forever (acceptAndHandle sock) `catchError`+        (\e -> do+          log . LogError $ show e+          snd . logger <$> ask >>= liftIO)))++forkGopherM :: GopherM () -> GopherM ThreadId+forkGopherM action = ask >>= liftIO . forkIO . (flip gopherM) action++handleIncoming :: Socket Inet6 Stream TCP -> Inet6Address -> GopherM ()+handleIncoming clientSock addr = do+  req <- liftIO $ uDecode . stripNewline <$> receiveRequest clientSock+  log . LogInfo $ "Got request '" ++ req ++ "' from " ++ show addr++  fun <- serverFun <$> ask+  res <- liftIO (fun req) >>= response++  liftIO $ sendAll clientSock res msgNoSignal+  liftIO $ close clientSock+  log . LogInfo $ "Closed connection succesfully to " ++ show addr++acceptAndHandle :: Socket Inet6 Stream TCP -> GopherM ()+acceptAndHandle sock = do+  (clientSock, (SocketAddressInet6 addr _ _ _)) <- liftIO $ accept sock+  log . LogInfo $ "Accepted Connection from " ++ show addr+  forkGopherM $ handleIncoming clientSock addr `catchError` (\e -> do+    liftIO (close clientSock)+    log . LogError $ "Closed connection to " ++ show addr ++ " after error: " ++ show e)+  return ()++-- | Run a gopher application that may not cause effects in 'IO'.+runGopherPure :: GopherConfig -> (String -> GopherResponse) -> IO ()+runGopherPure cfg f = runGopher cfg (fmap pure f)++response :: GopherResponse -> GopherM ByteString+response (MenuResponse items) = do+  env <- ask+  pure $ foldl (\acc (Item fileType title path host port) ->+                 B.append acc $+                   fileTypeToChar fileType `B.cons`+                     B.concat [ title, uEncode "\t", uEncode path, uEncode "\t", fromMaybe (serverName env) host,+                                uEncode "\t", uEncode . show $ fromMaybe (serverPort env) port, uEncode "\r\n" ])+              B.empty items++response (FileResponse str) = pure str+response (ErrorResponse reason) = do+  env <- ask+  pure $ fileTypeToChar Error `B.cons`+    B.concat [uEncode reason, uEncode $  "\tErr\t", serverName env, uEncode "\t", uEncode . show $ serverPort env, uEncode "\r\n"]
+ src/Network/Gopher/Types.hs view
@@ -0,0 +1,102 @@+module Network.Gopher.Types+  ( GopherFileType (..)+  , GopherResponse (..)+  , GopherMenuItem (..)+  , fileTypeToChar+  , charToFileType+  , isFile+  )+  where++import           Prelude               hiding (lookup)++import           Network.Gopher.Util++import           Data.ByteString (ByteString, pack, unpack)+import qualified Data.ByteString as B+import           Data.Char             (ord, chr)+import           Data.Map              (Map (), fromList, lookup)+import           Data.Maybe            (fromJust, fromMaybe)+import           Data.Tuple            (swap)+import           Data.Word             (Word8 ())+import           System.FilePath       (splitPath, takeBaseName)++-- | entry in a gopher menu+data GopherMenuItem = Item GopherFileType ByteString FilePath (Maybe ByteString) (Maybe Integer) -- ^ file type, menu text, filepath (does not need to be a real file), server name (optional), port (optional)+  deriving (Show, Eq)++data GopherResponse+  = MenuResponse [GopherMenuItem] -- ^ gopher menu, wrapper around a list of 'GopherMenuItem's+  | FileResponse ByteString       -- ^ return the given 'ByteString' as a file+  | ErrorResponse String          -- ^ gopher menu containing a single error with the given 'String' as text+  deriving (Show, Eq)++-- | rfc-defined gopher file types plus info line and HTML+data GopherFileType+  = File                 -- ^ text file, default type+  | Directory            -- ^ a gopher menu+  | PhoneBookServer+  | Error                -- ^ error entry in menu+  | BinHexMacintoshFile+  | DOSArchive+  | UnixUuencodedFile+  | IndexSearchServer+  | TelnetSession+  | BinaryFile           -- ^ binary file+  | RedundantServer+  | Tn3270Session+  | GifFile              -- ^ gif+  | ImageFile            -- ^ image of any format+  | InfoLine             -- ^ menu entry without associated file+  | Html                 -- ^ Special type for HTML, most commonly used for <https://en.wikipedia.org/wiki/Gopher_%28protocol%29#URL_links links to other protocols>+  deriving (Show, Eq, Ord, Enum)++fileTypeToChar :: GopherFileType -> Word8+fileTypeToChar t = asciiOrd $+  case t of+    File -> '0'+    Directory -> '1'+    PhoneBookServer -> '2'+    Error -> '3'+    BinHexMacintoshFile -> '4'+    DOSArchive -> '5'+    UnixUuencodedFile -> '6'+    IndexSearchServer -> '7'+    TelnetSession -> '8'+    BinaryFile -> '9'+    RedundantServer -> '+'+    Tn3270Session -> 'T'+    GifFile -> 'g'+    ImageFile -> 'I'+    InfoLine -> 'i'+    Html -> 'h'++charToFileType :: Word8 -> GopherFileType+charToFileType c =+  case asciiChr c of+     '0' -> File+     '1' -> Directory+     '2' -> PhoneBookServer+     '3' -> Error+     '4' -> BinHexMacintoshFile+     '5' -> DOSArchive+     '6' -> UnixUuencodedFile+     '7' -> IndexSearchServer+     '8' -> TelnetSession+     '9' -> BinaryFile+     '+' -> RedundantServer+     'T' -> Tn3270Session+     'g' -> GifFile+     'I' -> ImageFile+     'i' -> InfoLine+     'h' -> Html+     _   -> InfoLine -- default value++isFile :: GopherFileType -> Bool+isFile File = True+isFile BinHexMacintoshFile = True+isFile DOSArchive = True+isFile UnixUuencodedFile = True+isFile GifFile = True+isFile ImageFile = True+isFile _ = False
+ src/Network/Gopher/Util.hs view
@@ -0,0 +1,61 @@+{-|+Module      : Network.Gopher.Util+Stability   : experimental+Portability : POSIX++Helper utilities used within the library and the server which also could be useful for other application code.+-}+{-# LANGUAGE OverloadedStrings #-}+module Network.Gopher.Util (+  -- * Security+    santinizePath+  , santinizeIfNotUrl+  -- * String Encoding+  , asciiOrd+  , asciiChr+  , uEncode+  , uDecode+  -- * Misc Helpers+  , stripNewline+  ) where++import Data.ByteString (ByteString ())+import qualified Data.ByteString as B+import Data.Char (ord, chr)+import Data.List (isPrefixOf)+import qualified Data.String.UTF8 as U+import Data.Word (Word8 ())+import System.FilePath.Posix (pathSeparator, normalise, joinPath, splitPath)++-- | 'chr' a 'Word8'+asciiChr :: Word8 -> Char+asciiChr = chr . fromIntegral++-- | 'ord' a 'Word8'+asciiOrd :: Char -> Word8+asciiOrd = fromIntegral . ord++-- | Encode a 'String' to a UTF-8 'ByteString'+uEncode :: String -> ByteString+uEncode = B.pack . U.encode++-- | Decode a UTF-8 'ByteString' to a 'String'+uDecode :: ByteString -> String+uDecode = fst . U.decode . B.unpack++-- | Strip @\\r@ and @\\n@ from 'ByteString's+stripNewline :: ByteString -> ByteString+stripNewline s+  | B.null s           = B.empty+  | B.head s `elem`+    (map (fromIntegral . ord) "\n\r") = stripNewline (B.tail s)+  | otherwise          = B.head s `B.cons` stripNewline (B.tail s)++-- | Normalise a path and prevent <https://en.wikipedia.org/wiki/Directory_traversal_attack directory traversal attacks>.+santinizePath :: FilePath -> FilePath+santinizePath path = joinPath . filter (\p -> p /= ".." && p /= ".") . splitPath . normalise $ path++santinizeIfNotUrl :: FilePath -> FilePath+santinizeIfNotUrl path = if "URL:" `isPrefixOf` path+                           then path+                           else santinizePath path
+ src/Network/Gopher/Util/Gophermap.hs view
@@ -0,0 +1,137 @@+{-|+Module      : Network.Gopher.Util.Gophermap+Stability   : experimental+Portability : POSIX++This module implements a parser for <https://raw.githubusercontent.com/sternenseemann/spacecookie/master/docs/gophermap-pygopherd.txt gophermap files>.++Example usage:++@+import Network.Gopher.Util.Gophermap+import qualified Data.ByteString as B+import Data.Attoparsec.ByteString++main = do+  file <- B.readFile "gophermap"+  print $ parseOnly parseGophermap file+@+++-}++{-# LANGUAGE OverloadedStrings #-}+module Network.Gopher.Util.Gophermap (+    parseGophermap+  , GophermapEntry (..)+  , Gophermap (..)+  , gophermapToDirectoryResponse+  ) where++import Prelude hiding (take, takeWhile)++import Network.Gopher.Types+import Network.Gopher.Util++import Control.Applicative (many, (<$>), (<|>))+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Reader (ask)+import Data.Attoparsec.ByteString+import Data.ByteString (ByteString (), append, empty, pack, singleton, unpack)+import Data.Maybe (fromMaybe)+import qualified Data.String.UTF8 as U+import Data.Word (Word8 ())++-- | Convert a gophermap to a gopher menu response.+gophermapToDirectoryResponse :: Gophermap -> GopherResponse+gophermapToDirectoryResponse entries =+  MenuResponse (map gophermapEntryToMenuItem entries)++gophermapEntryToMenuItem :: GophermapEntry -> GopherMenuItem+gophermapEntryToMenuItem (GophermapEntry ft desc path host port) =+  Item ft desc (fromMaybe (uDecode desc) path) host port++fileTypeChars :: [Char]+fileTypeChars = "0123456789+TgIih"++-- | A gophermap entry makes all values of a gopher menu item optional except for file type and description. When converting to a 'GopherMenuItem', appropriate default values are used.+data GophermapEntry = GophermapEntry+  GopherFileType ByteString+  (Maybe FilePath) (Maybe ByteString) (Maybe Integer) -- ^ file type, description, path, server name, port number+  deriving (Show, Eq)++type Gophermap = [GophermapEntry]++-- | Attoparsec 'Parser' for the <https://raw.githubusercontent.com/sternenseemann/spacecookie/master/docs/gophermap-pygopherd.txt gophermap file format>+parseGophermap :: Parser Gophermap+parseGophermap = many parseGophermapLine++if' :: Bool -> a -> a -> a+if' True  a _ = a+if' False _ b = b++gopherFileTypeChar :: Parser Word8+gopherFileTypeChar = satisfy (inClass fileTypeChars)++parseGophermapLine :: Parser GophermapEntry+parseGophermapLine = emptyGophermapline <|>+                     regularGophermapline <|>+                     infoGophermapline <|>+                     gophermaplineWithoutFileTypeChar++infoGophermapline :: Parser GophermapEntry+infoGophermapline = do+  text <- takeWhile (notInClass "\t\r\n")+  endOfLine'+  return $ GophermapEntry InfoLine+    text+    Nothing+    Nothing+    Nothing++regularGophermapline :: Parser GophermapEntry+regularGophermapline = do+    fileTypeChar <- gopherFileTypeChar+    text <- itemValue+    pathString <- optionalValue+    host <- optionalValue+    portString <- optionalValue+    endOfLine'+    return $ GophermapEntry (charToFileType fileTypeChar)+      text+      (santinizeIfNotUrl . fst . U.decode . unpack <$> pathString)+      host+      (byteStringToPort <$> portString)++emptyGophermapline :: Parser GophermapEntry+emptyGophermapline = do+  endOfLine'+  return emptyInfoLine+    where emptyInfoLine = GophermapEntry InfoLine (pack []) Nothing Nothing Nothing++gophermaplineWithoutFileTypeChar :: Parser GophermapEntry+gophermaplineWithoutFileTypeChar = do+  text <- itemValue+  pathString <- optionalValue+  host <- optionalValue+  portString <- optionalValue+  endOfLine'+  return $ GophermapEntry InfoLine+    text+    (santinizeIfNotUrl . fst . U.decode . unpack <$> pathString)+    host+    (byteStringToPort <$> portString)++byteStringToPort :: ByteString -> Integer+byteStringToPort s = fromIntegral . read . fst . U.decode . unpack $ s++optionalValue :: Parser (Maybe ByteString)+optionalValue = option Nothing $ do+  satisfy (inClass "\t")+  Just <$> itemValue++itemValue :: Parser ByteString+itemValue = takeTill (inClass "\t\r\n")++endOfLine' :: Parser ()+endOfLine' = (word8 10 >> return ()) <|> (string "\r\n" >> return ())