From 5b28e02783c9048305ba651c6d9b843368534410 Mon Sep 17 00:00:00 2001 From: V Date: Sat, 14 Aug 2021 13:19:03 +0200 Subject: Root commit --- LICENSES/CC0-1.0.txt | 121 +++++++++++++++++++++++++++++++++++++++++++++++++++ LICENSES/OSL-3.0.txt | 47 ++++++++++++++++++++ README.adoc | 70 +++++++++++++++++++++++++++++ go.mod | 11 +++++ go.sum | 7 +++ go.sum.license | 2 + main.go | 98 +++++++++++++++++++++++++++++++++++++++++ 7 files changed, 356 insertions(+) create mode 100644 LICENSES/CC0-1.0.txt create mode 100644 LICENSES/OSL-3.0.txt create mode 100644 README.adoc create mode 100644 go.mod create mode 100644 go.sum create mode 100644 go.sum.license create mode 100644 main.go diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/OSL-3.0.txt b/LICENSES/OSL-3.0.txt new file mode 100644 index 0000000..2e8fa27 --- /dev/null +++ b/LICENSES/OSL-3.0.txt @@ -0,0 +1,47 @@ +Open Software License v. 3.0 (OSL-3.0) + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + + Licensed under the Open Software License version 3.0 + +1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + a) to reproduce the Original Work in copies, either alone or as part of a collective work; + + b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + c) to distribute or communicate copies of the Original Work and Derivative Works to the public, with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License; + + d) to perform the Original Work publicly; and + + e) to display the Original Work publicly. + +2) Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + +3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + +4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor’s trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + +5) External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + +6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + +7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + +8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + +9) Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including “fair use” or “fair dealing”). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + +10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + +11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + +12) Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + +13) Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + +14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + +16) Modification of This License. This License is Copyright (c) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/README.adoc b/README.adoc new file mode 100644 index 0000000..74b79bc --- /dev/null +++ b/README.adoc @@ -0,0 +1,70 @@ +// SPDX-FileCopyrightText: V +// SPDX-License-Identifier: OSL-3.0 + += cgiserver + +...is a really simple web server for CGI applications. + +It's lightweightfootnote:[I really do mean this: roughly 100 lines of liberally commented code, most of which is boilerplate] and modern, relying on systemd for socket management and an execution environment. +Each instance of cgiserver is responsible for a single application, which makes privilege separation straightforward and allows for fine-grained sandboxing. +Unlike similar programs such as https://github.com/gnosek/fcgiwrap[fcgiwrap] and https://man.openbsd.org/slowcgi.8[slowcgi]—both of which speak https://en.wikipedia.org/wiki/FastCGI[FastCGI]footnote:[an obsolete binary protocol specifically created to allow CGI applications to run as a single, persistent process]—cgiserver just uses HTTP and https://en.wikipedia.org/wiki/X-Forwarded-For[standard proxy headers]. +Instead of handling routing logic itself, cgiserver leaves that and other such intricacies to your regular web server. + +== Basic usage + +At minimum, cgiserver requires two things: a listening socket, and a CGI application. +To run https://git.zx2c4.com/cgit/about/[CGit], you might write the following: + +.cgit.service +[source,systemd] +---- +[Unit] +Description=Lightweight Git web interface + +[Service] +ExecStart=cgiserver /usr/lib/cgit/cgit.cgi +DynamicUser=true +---- + +.cgit.socket +[source,systemd] +---- +[Socket] +ListenStream=/run/cgit/cgit.sock + +[Install] +WantedBy=sockets.target +---- + +You will then need to configure your web server to reverse proxy requests to `/run/cgit/cgit.sock`. +Naturally, systemd also allows you to listen on TCP ports, but UNIX sockets are preferable as you can limit access to a specific user or group using filesystem permissions. +For more information on socket configuration, see https://www.freedesktop.org/software/systemd/man/systemd.socket.html[`systemd.socket(5)`]. + +WARNING: Do not expose cgiserver directly to the Internet! +It respects proxy headers, which could make your application vulnerable if it uses the originating address for anything important. +Only deploy it behind a web server that understands, filters, and sets these headers itself. + +== Environment + +The CGI application inherits cgiserver's environment, allowing for simple configuration via systemd's https://www.freedesktop.org/software/systemd/man/systemd.exec.html#Environment=[`Environment=`] and https://www.freedesktop.org/software/systemd/man/systemd.exec.html#EnvironmentFile=[`EnvironmentFile=`] directives. +Running with the previous example: if you want to change CGit's config location from the default,footnote:[`/etc/cgitrc`, in case you were wondering] you could add the following: + +.cgit.service +[source,systemd] +---- +[Service] +Environment=CGIT_CONFIG=/etc/cgit/config +---- + +== Multiple CGI applications + +If you have multiple CGI applications, you will need to run a separate instance of cgiserver for each of them. +This isn't a huge issue, as cgiserver has a fairly low memory footprintfootnote:[roughly 4.5MiB per instance when I last checked, although I never seriously benchmarked it] and all mainstream web servers have templating functionality. +In https://caddyserver.com/[Caddy], you could do the following: + +[source,Caddyfile] +reverse_proxy /cgi-bin/* //unix/run/cgi/{file}.sock + +== License + +cgiserver is licensed under the Open Software License, version 3.0. diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ef4566c --- /dev/null +++ b/go.mod @@ -0,0 +1,11 @@ +// SPDX-FileCopyrightText: V +// SPDX-License-Identifier: OSL-3.0 + +module go.anomalous.eu/cgiserver + +go 1.16 + +require ( + github.com/coreos/go-systemd/v22 v22.3.2 + github.com/gorilla/handlers v1.5.1 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5b74262 --- /dev/null +++ b/go.sum @@ -0,0 +1,7 @@ +github.com/coreos/go-systemd/v22 v22.3.2 h1:D9/bQk5vlXQFZ6Kwuu6zaiXJ9oTPe68++AzAJc1DzSI= +github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ= +github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4= +github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q= diff --git a/go.sum.license b/go.sum.license new file mode 100644 index 0000000..29bc7e6 --- /dev/null +++ b/go.sum.license @@ -0,0 +1,2 @@ +SPDX-FileCopyrightText: V +SPDX-License-Identifier: CC0-1.0 diff --git a/main.go b/main.go new file mode 100644 index 0000000..2019888 --- /dev/null +++ b/main.go @@ -0,0 +1,98 @@ +// SPDX-FileCopyrightText: V +// SPDX-License-Identifier: OSL-3.0 + +package main // import "go.anomalous.eu/cgiserver" + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "net/http/cgi" + "os" + "os/signal" + "syscall" + + "github.com/coreos/go-systemd/v22/activation" + "github.com/gorilla/handlers" +) + +func main() { + // The journal already has timestamps, so let's avoid adding our own. + log.SetFlags(0) + + // The default usage message isn't very helpful, so we provide our own. + flag.Usage = func() { + fmt.Fprintln(flag.CommandLine.Output(), "Usage: cgiserver /path/to/application.cgi") + } + + // We didn't configure any flags, so this just serves to display an error + // if someone tries to pass one. It also automatically handles -h/--help. + flag.Parse() + + if flag.NArg() != 1 { + flag.Usage() + os.Exit(1) + } + path := flag.Arg(0) + + // Socket activation makes our life very easy... + lns, err := activation.Listeners() + if err != nil { + log.Fatal(err) + } + if len(lns) == 0 { + log.Print("One or more listening sockets must be configured.") + log.Print("See systemd.socket(5) for more information.") + os.Exit(1) + } + + var handler http.Handler + + // ...and Go's standard library does literally all of the hard work. + handler = &cgi.Handler{ + Path: path, + Env: os.Environ(), // Environment variables aren't inherited by default. + } + + // We want to resolve X-Forwarded-For, etc. + handler = handlers.ProxyHeaders(handler) + + // Additionally, we want to log requests. + handler = handlers.CombinedLoggingHandler(os.Stdout, handler) + + // Catch SIGTERM so we can shutdown gracefully. + sig := make(chan os.Signal, 1) + signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT) + + // Create a Server so we can call Shutdown() on it later. + srv := &http.Server{Handler: handler} + + doom := make(chan error) + for _, ln := range lns { + // Loop variables are unsafe to close over with goroutines, + // so this just shadows it with a fresh binding. + ln := ln + + go func() { + // If any one of these return, it's game over. + doom <- srv.Serve(ln) + }() + } + + select { + case err = <-doom: + // Only the first error matters, the rest will be ErrServerClosed. + log.Printf("Fatal server error: %v", err) + case <-sig: + log.Print("Caught signal, shutting down") + } + + // This will block until all existing connections are handled. + srv.Shutdown(context.Background()) + + if err != nil { + os.Exit(1) + } +} -- cgit 1.4.1