~sotirisp/kindleto

ref: faaff15151ac14fbdf0cb20b3b6a145bf127af3a kindleto/kindleto.go -rw-r--r-- 6.3 KiB
faaff151Sotiris Papatheodorou Reduce the TOFU cache save interval 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// SPDX-FileCopyrightText: 2020 Paul Gorman
// SPDX-FileCopyrightText: 2021 Sotiris Papatheodorou
// SPDX-License-Identifier: GPL-3.0-or-later

package main

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"flag"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	mathrand "math/rand"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
	"time"
)

var muClientCerts sync.RWMutex
var clientCerts []clientCertificate
var clientCertsChanged bool
var errRedirect error
var maxRedirects int
var addr string
var optClientCertsFile string
var homeFile string
var optHours int
var optLang string
var optLogLevel int
var optPort string
var optTextOnly bool
var optTrust bool
var optWebRoot string
var optTofuFile string
var muServerCerts sync.RWMutex
var serverCerts []serverCertificate
var serverCertsChanged bool
var reCharset *regexp.Regexp
var reGemBlank *regexp.Regexp
var reGemH1 *regexp.Regexp
var reGemH2 *regexp.Regexp
var reGemH3 *regexp.Regexp
var reGemLink *regexp.Regexp
var reGemList *regexp.Regexp
var reGemPre *regexp.Regexp
var reGemResponseHeader *regexp.Regexp
var reGemQuote *regexp.Regexp
var reLang *regexp.Regexp
var reStatus *regexp.Regexp
var tmpls *template.Template

type templateData struct {
	Certs       []clientCertificate
	Charset     string
	Count       int
	Error       string
	HTML        template.HTML
	Lang        string
	Logout      bool
	ManageCerts bool
	Meta        string
	Title       string
	URL         string
	URLUp       string
	Warning     string
}

// absoluteURL makes lineURL absolute using, if necessary, the host and path of baseURL.
func absoluteURL(baseURL *url.URL, lineURL string) (*url.URL, error) {
	var err error

	u, err := url.Parse(lineURL)
	if err != nil {
		return u, err
	}

	return baseURL.ResolveReference(u), err
}

func usage() {
	fmt.Fprintf(flag.CommandLine.Output(), "Usage: %s [OPTIONS]\n", os.Args[0])
	flag.PrintDefaults()
}

func init() {
	mathrand.Seed(time.Now().Unix())

	flag.Usage = usage
	flag.BoolVar(&optTextOnly, "textonly", false, "refuse to proxy non-text file types")
	flag.BoolVar(&optTrust, "trust", false, "don't warn about TLS certificate changes for visited Gemini sites")
	flag.IntVar(&maxRedirects, "r", 5, "maximum redirects to follow")
	flag.IntVar(&optHours, "hours", 72, "hours until transient client TLS certificates expire (zero disables client certs)")
	flag.IntVar(&optLogLevel, "loglevel", 0, "print debugging output; 0=errors only, 1=verbose, 2=very verbose, 3=very very verbose")
	flag.StringVar(&optClientCertsFile, "certfile", "", "JSON file containing client certificates")
	flag.StringVar(&optLang, "lang", "en-US", "RFC4646 language for pages that do not supply one")
	flag.StringVar(&optPort, "port", "1965", "port on which to serve web interface")
	flag.StringVar(&optWebRoot, "webroot", "", "directory containing custom web templates for the proxy")
	flag.StringVar(&optTofuFile, "tofucache", "", "file where TOFU certificates are cached")
	flag.Parse()

	if optWebRoot != "" {
		p, err := filepath.Abs(optWebRoot)
		if err == nil {
			optWebRoot = p
		}

		homeFile = optWebRoot + "/index.gmi"
		if _, err := os.Stat(homeFile); os.IsNotExist(err) {
			homeFile = ""
		}
	}

	addr = "127.0.0.1"
	tmpls = loadTemplates(optWebRoot)

	reCharset = regexp.MustCompile(`\bcharset=([\w-]+)`)
	reGemBlank = regexp.MustCompile(`^\s*$`)
	reGemH1 = regexp.MustCompile(`^#\s*([^#].*)\s*`)
	reGemH2 = regexp.MustCompile(`^##\s*([^#].*)\s*`)
	reGemH3 = regexp.MustCompile(`^###\s*([^#].*)\s*`)
	reGemLink = regexp.MustCompile(`^=>\s*(\S*)\s*(.*)`)
	reGemList = regexp.MustCompile(`^\*\s(.*)\s*`)
	reGemPre = regexp.MustCompile("^```(.*)")
	reGemResponseHeader = regexp.MustCompile(`^\d{2} (.*)\r\n`)
	reGemQuote = regexp.MustCompile(`^>\s(.*)\s*`)
	reLang = regexp.MustCompile(`\blang=([\w-]+)`)
	reStatus = regexp.MustCompile(`\d\d .*`)

	if !optTrust {
		serverCertsChanged = false
		serverCerts = make([]serverCertificate, 0, 500)
	}

	clientCerts = make([]clientCertificate, 0, 500)

	if optClientCertsFile != "" {
		var pCerts []persistentCert

		jc, err := ioutil.ReadFile(optClientCertsFile)
		if err != nil {
			log.Printf("init: failed to read persistent TLS client certificates from JSON file '%s': %v", optClientCertsFile, err)
		} else {
			err := json.Unmarshal(jc, &pCerts)
			if err != nil {
				log.Printf("init: failed to unmarshal JSON client certificates from '%s': %v", optClientCertsFile, err)
			}
		}

		for _, pc := range pCerts {
			var c clientCertificate
			u, err := url.Parse(pc.URL)
			if err != nil {
				log.Printf("init: failed to parse URL %s in client certificate file '%s': %v", c.URL, optClientCertsFile, err)
				continue
			}
			c.URL = pc.URL
			certPEM, err := loadCertificate(pc.CertPEM, optClientCertsFile)
			if err != nil {
				log.Printf("init: failed to read certificate from %s: %v", pc.CertPEM, err)
				continue
			}
			keyPEM, err := loadCertificate(pc.KeyPEM, optClientCertsFile)
			if err != nil {
				log.Printf("init: failed to read certificate private key from %s: %v", pc.KeyPEM, err)
				continue
			}
			c.Cert, err = tls.X509KeyPair(certPEM, keyPEM)
			if err != nil {
				log.Printf("init: failed to parse client certificate PEM data for %s: %v", c.URL, err)
				continue
			}
			c.Leaf, err = x509.ParseCertificate(c.Cert.Certificate[0])
			if err != nil {
				log.Printf("init: failed to parse certificate leaf for %s: %v", pc.URL, err)
				continue
			}
			c.Expires = c.Leaf.NotAfter.String()
			c.CertName = c.Leaf.Subject.CommonName
			c.Host = u.Host
			c.Path = strings.Split(u.Path, "/")

			clientCerts = append(clientCerts, c)
		}
	}
}

func main() {
	if !optTrust {
		go saveTOFU(optTofuFile)
	}

	if optHours > 0 {
		go purgeOldClientCertificates()
	}

	mux := http.NewServeMux()

	mux.HandleFunc("/", proxy)
	mux.HandleFunc("/certificate", clientCertificateRequired)
	mux.HandleFunc("/settings/certificates", manageClientCertificates)
	mux.HandleFunc("/kindleto.css", css)
	mux.HandleFunc("/about.html", func(w http.ResponseWriter, r *http.Request) {
		var td templateData
		td.Title = "Kindleto Help"
		err := tmpls.ExecuteTemplate(w, "about.html.tmpl", td)
		if err != nil {
			log.Println("main:", err.Error())
			http.Error(w, "Internal Server Error", 500)
		}
	})

	if optLogLevel > 0 {
		log.Printf("main: serving insecure HTTP server on %s", addr+":"+optPort)
	}
	err := http.ListenAndServe(addr+":"+optPort, mux)
	if err != nil {
		log.Fatalf("main: could not start HTTPS server: %v", err)
	}

}