about summary refs log tree commit diff
diff options
context:
space:
mode:
authorV <v@anomalous.eu>2021-08-27 06:08:09 +0200
committerV <v@anomalous.eu>2021-08-27 06:08:09 +0200
commitd49fe57776e6d19181c8ccb8d5332ed2c62d5ca8 (patch)
treee3036d32e318bfaef519c316de7e7f44b9351fef
downloadloxy-trunk.tar.zst
Root commit HEAD v0.2.0 trunk
Co-authored-by: edef <edef@edef.eu>
-rw-r--r--LICENSES/CC0-1.0.txt121
-rw-r--r--LICENSES/OSL-3.0.txt47
-rw-r--r--README.adoc64
-rw-r--r--go.mod12
-rw-r--r--go.sum5
-rw-r--r--go.sum.license3
-rw-r--r--listener.go58
-rw-r--r--loxy.854
-rw-r--r--main.go94
-rw-r--r--proxy.go145
-rw-r--r--session.go69
-rw-r--r--store.go135
12 files changed, 807 insertions, 0 deletions
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 <insert your license name here>" 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..6f74045
--- /dev/null
+++ b/README.adoc
@@ -0,0 +1,64 @@
+// SPDX-FileCopyrightText: V <v@anomalous.eu>
+// SPDX-FileCopyrightText: edef <edef@edef.eu>
+// SPDX-License-Identifier: OSL-3.0
+
+= loxy
+
+...a __lo__gging IRC pr__oxy__.
+
+It sits between your IRC client and the IRC servers you connect to, and saves timestamped raw IRC protocol lines to an SQLite database.
+It is implemented as an HTTP proxy server, making it compatible with most modern IRC clients.
+
+It supports systemd socket activation.
+
+== Configuration
+
+Note: since loxy is a transparent proxy, you must ensure your client is set to use insecure connections.
+loxy will only make secure outgoing connections.
+All outgoing connections are currently made to the hardcoded port 6697.
+
+=== Irssi
+
+If your servers are configured to use TLS,footnote:[as they should be!] you will need to either recreate them without it enabled, or remove the `use_tls` flag in your `~/.irssi/config`, since it does not support removing TLS with `/SERVER MODIFY`.
+
+[source,irssi]
+/SET use_proxy ON
+/SET proxy_address <loxy host>
+/SET proxy_port <loxy port>
+/SET -clear proxy_password
+/EVAL SET proxy_string CONNECT %s HTTP/1.0\n\n
+
+=== Quassel
+
+In the network configuration dialogue, for each server in the 'Servers' tab, select 'Edit...'.
+Under the 'Server Info' tab, ensure that the 'Use encrypted connection' option is disabled.
+Under the 'Advanced' tab, select 'Use a Proxy', set the type to 'HTTP', and fill in the host and port as appropriate.
+For an instance of loxy running on the same machine with default options, 'localhost' and '3893' should be good.
+
+== Files
+
+* `listener.go` - listener gathering
+* `main.go` - program entry point
+* `proxy.go` - IRC protocol parsing and proxy server
+* `session.go` - encapsulates a 'session', buffering writes
+* `store.go` - database schema and routines
+
+== Caveats
+
+* doesn't support insecure connections
+* doesn't support invalid certificates (self-signed, expired, etc)
+* only supports one client certificate per instance
+* doesn't support SOCKS, only the HTTP proxy protocol
+
+== TODO
+
+* make loxy serve its own source code over HTTP
+* inject server notices (or numerics) into the proxied connection, to provide license notices and source code links
+* eliminate the caveats
+
+== License
+
+loxy is licensed under the Open Software License, version 3.0.
+
+If you let other people use your loxy instance, you're in charge of fulfilling the license requirements.
+This includes (but is not limited to) informing them of the license and making source code available to them.
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..ae8077d
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,12 @@
+// SPDX-FileCopyrightText: V <v@anomalous.eu>
+// SPDX-FileCopyrightText: edef <edef@edef.eu>
+// SPDX-License-Identifier: OSL-3.0
+
+module go.anomalous.eu/loxy
+
+go 1.16
+
+require (
+	github.com/coreos/go-systemd/v22 v22.3.2
+	github.com/mattn/go-sqlite3 v1.14.8
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..d6818df
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,5 @@
+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/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
+github.com/mattn/go-sqlite3 v1.14.8 h1:gDp86IdQsN/xWjIEmr9MF6o9mpksUgh0fu+9ByFxzIU=
+github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
diff --git a/go.sum.license b/go.sum.license
new file mode 100644
index 0000000..3563113
--- /dev/null
+++ b/go.sum.license
@@ -0,0 +1,3 @@
+SPDX-FileCopyrightText: V <v@anomalous.eu>
+SPDX-FileCopyrightText: edef <edef@edef.eu>
+SPDX-License-Identifier: CC0-1.0
diff --git a/listener.go b/listener.go
new file mode 100644
index 0000000..a4fd692
--- /dev/null
+++ b/listener.go
@@ -0,0 +1,58 @@
+// SPDX-FileCopyrightText: V <v@anomalous.eu>
+// SPDX-FileCopyrightText: edef <edef@edef.eu>
+// SPDX-License-Identifier: OSL-3.0
+
+package main
+
+import (
+	"fmt"
+	"net"
+
+	"github.com/coreos/go-systemd/v22/activation"
+)
+
+type listenAddress string
+
+func (a listenAddress) Listeners() ([]net.Listener, error) {
+	ln, err := net.Listen("tcp", string(a))
+	if err != nil {
+		return nil, err
+	}
+	return []net.Listener{ln}, nil
+}
+
+func (a listenAddress) Get() interface{} {
+	return string(a)
+}
+
+func (a *listenAddress) Set(v string) error {
+	*a = listenAddress(v)
+	return nil
+}
+
+func (a listenAddress) String() string {
+	return string(a)
+}
+
+type activationSocket struct{}
+
+func (activationSocket) Listeners() (lns []net.Listener, err error) {
+	files := activation.Files(true)
+	lns = make([]net.Listener, len(files))
+	for i, f := range files {
+		lns[i], err = net.FileListener(f)
+		if err != nil {
+			return nil, err
+		}
+		f.Close()
+	}
+	return
+}
+
+func (activationSocket) String() string {
+	return "activation socket"
+}
+
+func (activationSocket) Set(string) error {
+	return fmt.Errorf("incompatible with socket activation")
+}
diff --git a/loxy.8 b/loxy.8
new file mode 100644
index 0000000..612d3c0
--- /dev/null
+++ b/loxy.8
@@ -0,0 +1,54 @@
+.\" SPDX-FileCopyrightText: V <v@anomalous.eu>
+.\" SPDX-FileCopyrightText: edef <edef@edef.eu>
+.\" SPDX-License-Identifier: OSL-3.0
+.Dd June 9, 2020
+.Dt LOXY 8
+.Os
+.
+.Sh NAME
+.Nm loxy
+.Nd logging IRC proxy
+.
+.Sh SYNOPSIS
+.Nm
+.Op Fl addr Oo Ar host Oc : Ns Ar port
+.Op Fl cert Ar path
+.Op Fl db Ar path
+.
+.Sh DESCRIPTION
+.Nm
+is a logging IRC proxy.
+It sits between your IRC client and the IRC servers you connect to, and logs timestamped raw IRC protocol lines to an SQLite database.
+It is implemented as an HTTP proxy server, making it compatible with most modern IRC clients.
+.
+.Sh OPTIONS
+.Bl -tag -width addr
+.It Fl addr Oo Ar host Oc : Ns Ar port
+Listening address.
+If
+.Ar port
+is specified, but
+.Ar host
+is empty,
+.Nm
+will listen on all available interfaces.
+Defaults to
+.Sy [::1]:3893 .
+Incompatible with
+.Xr systemd.socket 5
+activation.
+.It Fl cert Ar path
+Path to a file containing a PEM-encoded X.509 certificate and its corresponding private key.
+.It Fl db Ar path
+Path for the SQLite database.
+Defaults to
+.Pa loxy.db .
+.El
+.
+.Sh AUTHORS
+.An -nosplit
+.Nm
+was written by
+.An V Aq Mt v@anomalous.eu
+and
+.An edef Aq Mt edef@edef.eu .
diff --git a/main.go b/main.go
new file mode 100644
index 0000000..5b5f617
--- /dev/null
+++ b/main.go
@@ -0,0 +1,94 @@
+// SPDX-FileCopyrightText: V <v@anomalous.eu>
+// SPDX-FileCopyrightText: edef <edef@edef.eu>
+// SPDX-License-Identifier: OSL-3.0
+
+package main // import "go.anomalous.eu/loxy"
+
+import (
+	"context"
+	"crypto/tls"
+	"flag"
+	"io/ioutil"
+	"log"
+	"net"
+	"net/http"
+	"os"
+	"os/signal"
+	"syscall"
+)
+
+var dbpath, certpath string
+var addr interface {
+	flag.Value
+	Listeners() ([]net.Listener, error)
+}
+
+func init() {
+	if os.Getenv("LISTEN_FDS") == "" {
+		a := listenAddress(net.JoinHostPort("::1", "3893"))
+		addr = &a
+	} else {
+		addr = activationSocket{}
+	}
+
+	flag.Var(addr, "addr", "listen address")
+	flag.StringVar(&dbpath, "db", "loxy.db", "`path` to database")
+	flag.StringVar(&certpath, "cert", "", "`path` to client certificate")
+	log.SetFlags(log.Lshortfile)
+}
+
+func main() {
+	flag.Parse()
+	if flag.NArg() != 0 {
+		flag.Usage()
+		os.Exit(1)
+	}
+
+	tlsConfig := &tls.Config{}
+	if certpath != "" {
+		pem, err := ioutil.ReadFile(certpath)
+		if err != nil {
+			log.Fatal(err)
+		}
+
+		cert, err := tls.X509KeyPair(pem, pem)
+		if err != nil {
+			log.Fatal(err)
+		}
+
+		tlsConfig.Certificates = []tls.Certificate{cert}
+	}
+
+	proxy := NewProxy(OpenStore(dbpath), tlsConfig)
+	server := &http.Server{Handler: proxy}
+
+	ctx, cancel := context.WithCancel(context.Background())
+	server.BaseContext = func(net.Listener) context.Context { return ctx }
+	server.RegisterOnShutdown(cancel)
+
+	sig := make(chan os.Signal, 1)
+	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
+
+	listeners, err := addr.Listeners()
+	if err != nil {
+		log.Fatal(err)
+	}
+
+	serve := make(chan error, len(listeners))
+	for _, ln := range listeners {
+		go func(ln net.Listener) { serve <- server.Serve(ln) }(ln)
+	}
+
+	select {
+	case err = <-serve:
+		log.Printf("http.ListenAndServe: %v", err)
+	case sig := <-sig:
+		log.Printf("caught %v, shutting down", sig)
+		server.Shutdown(context.Background())
+	}
+	proxy.Shutdown()
+
+	if err != nil {
+		os.Exit(1)
+	}
+}
diff --git a/proxy.go b/proxy.go
new file mode 100644
index 0000000..dfee27e
--- /dev/null
+++ b/proxy.go
@@ -0,0 +1,145 @@
+// SPDX-FileCopyrightText: V <v@anomalous.eu>
+// SPDX-FileCopyrightText: edef <edef@edef.eu>
+// SPDX-License-Identifier: OSL-3.0
+
+package main
+
+import (
+	"bufio"
+	"bytes"
+	"crypto/tls"
+	"io"
+	"log"
+	"net"
+	"net/http"
+	"sync"
+)
+
+type sidedConn struct {
+	net.Conn
+	Side
+}
+
+type Proxy struct {
+	store     *Store
+	tlsConfig *tls.Config
+
+	exiting chan struct{}
+	wg      sync.WaitGroup
+}
+
+func NewProxy(store *Store, tlsConfig *tls.Config) *Proxy {
+	return &Proxy{
+		store:     store,
+		tlsConfig: tlsConfig,
+
+		exiting: make(chan struct{}),
+	}
+}
+
+func (p *Proxy) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
+	if req.Method != http.MethodConnect {
+		log.Printf("%s - invalid request %s %s", req.RemoteAddr, req.Method, req.RequestURI)
+		http.Error(resp, "405 I'm a proxy", http.StatusMethodNotAllowed)
+		return
+	}
+
+	host := req.URL.Hostname()
+	log.Printf("%s - new connection to %s", req.RemoteAddr, host)
+
+	server, err := tls.DialWithDialer(
+		&net.Dialer{Cancel: req.Context().Done()},
+		"tcp", net.JoinHostPort(host, "6697"),
+		p.tlsConfig,
+	)
+	if err != nil {
+		log.Printf("%s - failed connection %v", req.RemoteAddr, err)
+		resp.WriteHeader(http.StatusBadGateway)
+		return
+	}
+
+	session := OpenSession(p.store, host)
+	resp.WriteHeader(http.StatusOK)
+
+	// http.Server's Shutdown "does not attempt to close nor wait for hijacked connections",
+	// so we have to bump the waitgroup prior to calling Hijack()
+	p.wg.Add(1)
+	defer p.wg.Done()
+
+	// XXX: bufio.ReadWriter might still contain data
+	// I think it's impossible for err to be non-nil
+	client, _, _ := resp.(http.Hijacker).Hijack()
+	p.proxy(session, sidedConn{client, SideClient}, sidedConn{server, SideServer})
+}
+
+func (p *Proxy) proxy(session *Session, a, b sidedConn) {
+	ch := make(chan func())
+
+	pipe := func(r, w sidedConn) {
+		scanner := bufio.NewScanner(r)
+		scanner.Split(scanIRCLines)
+		for scanner.Scan() {
+			session.Write(r.Side, string(dropLineEnding(scanner.Bytes())))
+			_, err := w.Write(scanner.Bytes())
+			if err != nil {
+				ch <- func() { session.Close(w.Side, err.Error()) }
+				return
+			}
+		}
+
+		err := scanner.Err()
+		if err == nil {
+			err = io.EOF
+		}
+
+		ch <- func() { session.Close(r.Side, err.Error()) }
+	}
+
+	go pipe(a, b)
+	go pipe(b, a)
+
+	done := func() { session.Close(SideProxy, "shutting down") }
+
+	select {
+	case <-p.exiting:
+		a.Close()
+		b.Close()
+		<-ch
+		<-ch
+	case done = <-ch:
+		a.Close()
+		b.Close()
+		<-ch
+	}
+
+	done()
+}
+
+func (p *Proxy) Shutdown() {
+	close(p.exiting)
+	p.wg.Wait()
+	p.store.Close()
+}
+
+func scanIRCLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
+	if atEOF && len(data) == 0 {
+		return 0, nil, nil
+	}
+	if i := bytes.IndexByte(data, '\n'); i >= 0 {
+		// we have a full newline-terminated line
+		return i + 1, data[:i+1], nil
+	}
+	if atEOF {
+		return 0, nil, io.ErrUnexpectedEOF
+	}
+	return 0, nil, nil // request more data
+}
+
+// on a buffer known to end in \n, drop \n or \r\n
+func dropLineEnding(data []byte) []byte {
+	n := len(data)
+	if n > 1 && data[n-1] == '\r' {
+		return data[:n-2]
+	}
+	return data[:n-1]
+}
diff --git a/session.go b/session.go
new file mode 100644
index 0000000..7a65230
--- /dev/null
+++ b/session.go
@@ -0,0 +1,69 @@
+// SPDX-FileCopyrightText: V <v@anomalous.eu>
+// SPDX-FileCopyrightText: edef <edef@edef.eu>
+// SPDX-License-Identifier: OSL-3.0
+
+package main
+
+import (
+	"time"
+)
+
+type Session struct {
+	store *Store
+	id    SessionID
+	q     chan Message
+	done  chan struct{}
+}
+
+func OpenSession(store *Store, host string) *Session {
+	session := &Session{
+		store: store,
+		id:    store.WriteOpen(now(), host),
+		q:     make(chan Message, 1024),
+		done:  make(chan struct{}),
+	}
+
+	go session.batcher()
+	return session
+}
+
+func (s *Session) Write(from Side, data string) {
+	s.q <- Message{now(), from, data}
+}
+
+func (s *Session) Close(by Side, reason string) {
+	close(s.q)
+	<-s.done
+	s.store.WriteClose(s.id, now(), by, reason)
+}
+
+func now() Timestamp {
+	return Timestamp(time.Now().UnixNano())
+}
+
+func (s *Session) batcher() {
+	batch := make([]Message, cap(s.q))
+	for msg := range s.q {
+		batch = append(batch[:0], msg)
+	out:
+		for len(batch) < cap(batch) {
+			select {
+			case msg, ok := <-s.q:
+				if !ok {
+					break out
+				}
+				batch = append(batch, msg)
+			default:
+				break out
+			}
+		}
+
+		s.store.WriteBatch(s.id, batch)
+
+		for i := range batch {
+			batch[i] = Message{}
+		}
+	}
+
+	close(s.done)
+}
diff --git a/store.go b/store.go
new file mode 100644
index 0000000..5f228ae
--- /dev/null
+++ b/store.go
@@ -0,0 +1,135 @@
+// SPDX-FileCopyrightText: V <v@anomalous.eu>
+// SPDX-FileCopyrightText: edef <edef@edef.eu>
+// SPDX-License-Identifier: OSL-3.0
+
+package main
+
+import (
+	"database/sql"
+
+	_ "github.com/mattn/go-sqlite3"
+)
+
+const schema = `
+	CREATE TABLE IF NOT EXISTS sessions (
+		id             INTEGER PRIMARY KEY,
+		opened_at      INTEGER NOT NULL,
+		host           TEXT    NOT NULL,
+		closed_at      INTEGER,
+		closed_by      INTEGER,
+		closed_because TEXT
+	);
+
+	CREATE TABLE IF NOT EXISTS messages (
+		session INTEGER NOT NULL REFERENCES sessions(id),
+		time    INTEGER NOT NULL,
+		side    INTEGER NOT NULL,
+		data    TEXT    NOT NULL
+	);
+`
+
+type SessionID int64
+type Timestamp int64
+type Side byte
+
+const (
+	SideProxy Side = iota
+	SideClient
+	SideServer
+)
+
+type Message struct {
+	when Timestamp
+	side Side
+	data string
+}
+
+type Store struct {
+	open, batch, close *sql.Stmt
+
+	q    chan func(*sql.DB)
+	done chan struct{}
+}
+
+func OpenStore(path string) *Store {
+	db, err := sql.Open("sqlite3", path+"?_foreign_keys=yes")
+	check(err)
+
+	must(db.Exec(schema))
+	must(db.Exec(`UPDATE sessions SET closed_at = ? WHERE closed_at IS NULL`, now()))
+
+	prepare := func(query string) *sql.Stmt {
+		stmt, err := db.Prepare(query)
+		check(err)
+		return stmt
+	}
+
+	s := &Store{
+		open:  prepare(`INSERT INTO sessions(opened_at, host) VALUES(?, ?)`),
+		batch: prepare(`INSERT INTO messages(session, time, side, data) VALUES(?, ?, ?, ?)`),
+		close: prepare(`UPDATE sessions SET closed_at = ?, closed_by = ?, closed_because = ? WHERE id = ?`),
+
+		q:    make(chan func(*sql.DB)),
+		done: make(chan struct{}),
+	}
+
+	go func() {
+		for op := range s.q {
+			op(db)
+		}
+		check(db.Close())
+		close(s.done)
+	}()
+
+	return s
+}
+
+func (s *Store) WriteOpen(when Timestamp, host string) SessionID {
+	ch := make(chan int64, 1)
+	s.q <- func(*sql.DB) {
+		id, err := must(s.open.Exec(when, host)).LastInsertId()
+		check(err)
+		ch <- id
+	}
+	return SessionID(<-ch)
+}
+
+func (s *Store) WriteBatch(id SessionID, batch []Message) {
+	ch := make(chan struct{})
+	s.q <- func(db *sql.DB) {
+		tx, err := db.Begin()
+		check(err)
+
+		stmt := tx.Stmt(s.batch)
+		for _, msg := range batch {
+			must(stmt.Exec(id, msg.when, msg.side, msg.data))
+		}
+
+		check(tx.Commit())
+
+		close(ch)
+	}
+	<-ch
+}
+
+func (s *Store) WriteClose(id SessionID, when Timestamp, by Side, reason string) {
+	s.q <- func(*sql.DB) {
+		must(s.close.Exec(when, by, reason, id))
+	}
+}
+
+func (s *Store) Close() {
+	close(s.q)
+	<-s.done
+}
+
+func check(err error) {
+	if err != nil {
+		panic(err)
+	}
+}
+
+func must(res sql.Result, err error) sql.Result {
+	check(err)
+	return res
+}