~sotirisp/kindleto

ref: faaff15151ac14fbdf0cb20b3b6a145bf127af3a kindleto/handlers.go -rw-r--r-- 6.7 KiB
faaff151Sotiris Papatheodorou Reduce the TOFU cache save interval 3 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// SPDX-FileCopyrightText: 2020 Paul Gorman
// SPDX-FileCopyrightText: 2021 Sotiris Papatheodorou
// SPDX-License-Identifier: GPL-3.0-or-later

package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"path"
	"strings"
)

var cssData string = `body {
	font-family: serif;
	font-size: 16pt;
	margin: 0em 1em;
}
h1, h2, h3 {
	font-weight: bold;
	font-family: sans-serif;
	margin-top: 1em;
}
a {
	text-decoration: underline;
	color: black;
}
blockquote {
	border-left: 0.2em solid;
	padding-left: 0.5em;
	margin: 0.5em 2em 0.5em 2em;
}
input, textarea {
	border: 1px solid;
}
pre {
	font-family: monospace;
	overflow: auto;
	padding: 1em 2em 1em 2em;
	margin: 2em 0 2em 0;
}
span.scheme {
	font-size: 0.7em;
	margin-left: 1em;
}
span.scheme {
	font-weight: normal;
}
#header {
	padding-top: 0.25em;
	padding-bottom: 0.25em;
	border-bottom: solid 1px;
}
#header-menu {
	font-size: 0.8em;
}
#url-input {
	padding: 0.25em;
	width: 75%;
}
#footer {
	padding-top: 0.25em;
	padding-bottom: 0.25em;
	border-top: solid 1px;
}
#footer-menu {
	font-size: 0.8em;
}
#url-asking-for-client-cert {
	font-weight: bold;
}
#client-cert-form-button {
	display: block;
	margin: 1em 0 1em 0;
}
#client-cert-name-input {
	width: 30em;
}
#non-gemini-text {
	white-space: pre-wrap;
}
#warning, #error {
	padding: 1em;
	margin: 1em 0 1em 0;
}`

// parentURL returns the parent of the supplied URL as a string. If the path
// component of the supplied URL is empty or is just a slash it returns an
// empty string.
func parentURL(u url.URL) string {
	u.Path = path.Dir(strings.TrimRight(u.Path, "/"))
	if u.Path != "." {
		return u.String()
	}
	return ""
}

// clientCertificateRequired handles transient client certificate choices for our user.
func clientCertificateRequired(w http.ResponseWriter, r *http.Request) {
	var err error

	if r.Method == http.MethodGet && r.URL.Query().Get("url") != "" {
		if optLogLevel > 1 {
			log.Println("clientCertificateRequired: asking user whether to create client certificate for:", r.URL.Query().Get("url"))
		}
		var td templateData
		td.Title = "Kindleto Client Certificate Confirmation"
		td.URL = r.URL.Query().Get("url")
		td.Count = optHours
		if len(clientCerts) > 0 {
			td.ManageCerts = true
		}
		err = tmpls.ExecuteTemplate(w, "certificate.html.tmpl", td)
		if err != nil {
			log.Println("clientCertificateRequired:", err)
			http.Error(w, "Internal Server Error", 500)
		}
	} else if r.Method == http.MethodPost && r.FormValue("url") != "" {
		u, err := url.Parse(r.FormValue("url"))
		if err != nil {
			log.Printf("clientCertificateRequired: failed to parse URL '%s': %v", r.FormValue("url"), err)
			http.Error(w, "Internal Server Error", 500)
		}
		saveClientCert(u, r.FormValue("name"))
		http.Redirect(w, r, "/?url="+geminiQueryEscape(r.FormValue("url")), http.StatusFound)
	} else {
		if optLogLevel > 0 {
			log.Println("clientCertificateRequired: handler accessed without URL in POST or GET")
		}
		http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
	}
}

// manageClientCertificate lets the user view and delete client certificates.
func manageClientCertificates(w http.ResponseWriter, r *http.Request) {
	var err error

	if r.Method == http.MethodGet {
		var td templateData
		td.Title = "Kindleto Manage Client Certificates"
		td.Certs = clientCerts
		if len(clientCerts) > 0 {
			td.ManageCerts = true
		}
		err = tmpls.ExecuteTemplate(w, "certificates.html.tmpl", td)
		if err != nil {
			log.Println("manageClientCertificates:", err)
			http.Error(w, "Internal Server Error", 500)
		}
	}

	if r.Method == http.MethodPost && r.FormValue("url") != "" && r.FormValue("delete") == "delete" {
		u, err := url.Parse(r.FormValue("url"))
		if err != nil {
			log.Printf("manageClientCertificates: failed to parse URL '%s': %v", r.FormValue("url"), err)
			http.Error(w, "Internal Server Error", 500)
		}
		err = deleteClientCert(u)
		if err != nil {
			log.Printf("manageClientCertificates: failed to delete certificate for URL '%s': %v", r.FormValue("url"), err)
			http.Error(w, "Internal Server Error", 500)
		}
		http.Redirect(w, r, "/settings/certificates", http.StatusFound)
	}
}

// proxy handles requests not covered by another handler.
func proxy(w http.ResponseWriter, r *http.Request) {
	var err error
	var targetURL string
	var u *url.URL

	if r.Method == http.MethodPost && r.FormValue("url") != "" {
		targetURL = strings.SplitN(r.FormValue("url"), "?", 2)[0]
		if r.FormValue("input") != "" {
			targetURL = targetURL + "?" + geminiQueryEscape(r.FormValue("input"))
			if optLogLevel > 1 {
				log.Println("proxy: submitting Gemini input:", targetURL)
			}
		} else if r.FormValue("secret") != "" {
			targetURL = targetURL + "?" + geminiQueryEscape(r.FormValue("secret"))
			if optLogLevel > 1 {
				log.Printf("proxy: submitting Gemini sensitive input: %s?REDACTED_SECRET", r.FormValue("url"))
			}
		} else {
			targetURL = r.FormValue("url")
		}

		http.Redirect(w, r, "/?url="+geminiQueryEscape(targetURL), http.StatusFound)
	}

	if r.URL.Query().Get("url") == "" {
		if homeFile != "" {
			u, err := url.Parse(path.Join("file://", homeFile))
			if err != nil {
				log.Println("proxy: failed to parse home file path to URL:", err)
			}
			proxyGemini(w, r, u)
		} else {
			var td templateData
			td.Title = "Kindleto"
			if len(clientCerts) > 0 {
				td.ManageCerts = true
			}
			err = tmpls.ExecuteTemplate(w, "home.html.tmpl", td)
			if err != nil {
				log.Println("proxy:", err)
				http.Error(w, "Internal Server Error", 500)
			}
		}
		return
	}

	u, err = url.Parse(r.URL.Query().Get("url"))
	if err != nil {
		err = fmt.Errorf("proxy: failed to parse URL: %v", err)
		log.Println(err)
		http.Error(w, err.Error(), 500)
	}

	if u.Scheme == "gemini" {
		for i := 0; i <= maxRedirects; i++ {
			u, err = proxyGemini(w, r, u)
			if u != nil && u.Scheme != "gemini" {
				http.Redirect(w, r, u.String(), http.StatusFound)
			}
			if err != nil && errors.Is(err, errRedirect) {
				if i < maxRedirects-1 {
					log.Printf("proxy: redirecting to %s\n", err)
					continue
				} else {
					err = fmt.Errorf("too many redirects, ending at %s", u.String())
					i = maxRedirects + 1
					break
				}
			}
			if err != nil {
				log.Println(err)
			}
			break
		}
	} else {
		err = fmt.Errorf("proxy: proxying of %s not supported (%s)", u.Scheme, u.String())
	}

	if err != nil {
		if optLogLevel > 0 {
			log.Println(err)
		}
		var td templateData
		td.Error = err.Error()
		td.URL = u.String()
		td.URLUp = parentURL(*u)
		td.Title = "Kindleto " + td.URL
		if len(clientCerts) > 0 {
			td.ManageCerts = true
		}
		err = tmpls.ExecuteTemplate(w, "home.html.tmpl", td)
		if err != nil {
			log.Println(err)
			http.Error(w, "Internal Server Error", 500)
		}
	}
}

// css handles serving the CSS file
func css(w http.ResponseWriter, _ *http.Request) {
	w.Header().Set("Content-Type", "text/css")
	io.WriteString(w, cssData)
}