]> Sergey Matveev's repositories - tofuproxy.git/blob - rounds/gemini.go
gemini:// support
[tofuproxy.git] / rounds / gemini.go
1 /*
2 tofuproxy -- flexible HTTP proxy, TLS terminator, X.509 certificates
3              manager, WARC/Gemini browser
4 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
5
6 This program is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, version 3 of the License.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 package rounds
20
21 import (
22         "bufio"
23         "bytes"
24         "context"
25         "fmt"
26         "html"
27         "io"
28         "log"
29         "net/http"
30         "strconv"
31         "strings"
32
33         "go.stargrave.org/tofuproxy/fifos"
34         ttls "go.stargrave.org/tofuproxy/tls"
35 )
36
37 const (
38         ContentTypeGemini = "text/gemini"
39         SchemeGemini      = "gemini://"
40         GeminiEntrypoint  = "https://gemini"
41         GeminiPort        = ":1965"
42 )
43
44 var GemCodeName = map[int]string{
45         10: "INPUT",
46         11: "SENSITIVE INPUT",
47         20: "SUCCESS",
48         30: "REDIRECT - TEMPORARY",
49         31: "REDIRECT - PERMANENT",
50         40: "TEMPORARY FAILURE",
51         41: "SERVER UNAVAILABLE",
52         42: "CGI ERROR",
53         43: "PROXY ERROR",
54         44: "SLOW DOWN",
55         50: "PERMANENT FAILURE",
56         51: "NOT FOUND",
57         52: "GONE",
58         53: "PROXY REQUEST REFUSED",
59         59: "BAD REQUEST",
60         60: "CLIENT CERTIFICATE REQUIRED",
61         61: "CERTIFICATE NOT AUTHORISED",
62         62: "CERTIFICATE NOT VALID",
63 }
64
65 func absolutizeURL(host, u string, paths ...string) string {
66         host = strings.TrimSuffix(host, GeminiPort)
67         if strings.Contains(u, "://") {
68                 return u
69         }
70         if strings.HasPrefix(u, "/") {
71                 return GeminiEntrypoint + "/" + host + u
72         }
73         paths = append([]string{GeminiEntrypoint, host}, paths...)
74         paths = append(paths, u)
75         return strings.Join(paths, "/")
76 }
77
78 func geminifyURL(host, u string, paths ...string) string {
79         u = absolutizeURL(host, u, paths...)
80         if !strings.HasPrefix(u, SchemeGemini) {
81                 return u
82         }
83         return GeminiEntrypoint + "/" + strings.TrimPrefix(u, SchemeGemini)
84 }
85
86 func RoundGemini(
87         host string,
88         resp *http.Response,
89         w http.ResponseWriter,
90         req *http.Request,
91 ) (bool, error) {
92         if host != "gemini" {
93                 return true, nil
94         }
95         paths := strings.Split(strings.TrimPrefix(req.URL.Path, "/"), "/")
96         host, paths = paths[0], paths[1:]
97         hostWithPort := host
98         if !strings.Contains(hostWithPort, ":") {
99                 hostWithPort += GeminiPort
100         }
101         conn, err := ttls.DialTLS(context.TODO(), "tcp", hostWithPort)
102         if err != nil {
103                 log.Printf("%s: can not dial: %+v\n", req.URL, err)
104                 return false, err
105         }
106         _, err = fmt.Fprintf(
107                 conn, "%s%s/%s\r\n",
108                 SchemeGemini, host, strings.Join(paths, "/"),
109         )
110         if err != nil {
111                 log.Printf("%s: can not send request: %+v\n", req.URL, err)
112                 return false, err
113         }
114         if len(paths) > 0 && paths[len(paths)-1] == "" {
115                 paths = paths[:len(paths)-1]
116         }
117         br := bufio.NewReader(conn)
118         rawResp, err := br.ReadString('\n')
119         if err != nil {
120                 log.Printf("%s: can not read response: %+v\n", req.URL, err)
121                 return false, err
122         }
123         cols := strings.SplitN(rawResp, " ", 2)
124         if len(cols) < 2 {
125                 err = fmt.Errorf("invalid response format: %s", rawResp)
126                 log.Printf("%s: %s\n", req.URL, err)
127                 return false, err
128         }
129         code, err := strconv.Atoi(cols[0])
130         if err != nil {
131                 log.Printf("%s: can not parse response code: %+v\n", req.URL, err)
132                 return false, err
133         }
134         codeName := GemCodeName[code]
135         if codeName == "" {
136                 codeName = "UNKNOWN"
137         }
138         if 10 <= code && code <= 19 {
139                 w.Header().Add("Content-Type", "text/plain")
140                 w.WriteHeader(http.StatusBadRequest)
141                 fmt.Fprintf(w, "%s\n%d (%s): INPUT is not supported\n", cols[1], code, codeName)
142                 return false, nil
143         }
144         if 30 <= code && code <= 39 {
145                 w.Header().Add("Content-Type", "text/html")
146                 w.WriteHeader(http.StatusOK)
147                 u := geminifyURL(host, cols[1], paths...)
148                 w.Write([]byte(
149                         fmt.Sprintf(
150                                 `<!DOCTYPE html>
151 <html><head><title>%d (%s) redirection</title></head>
152 <body>Redirection to <a href="%s">%s</a></body></html>`,
153                                 code, codeName, u, u,
154                         )))
155                 fifos.LogRedir <- fmt.Sprintf(
156                         "%s %s\t%d\t%s", req.Method, req.URL, code, cols[1],
157                 )
158                 return false, nil
159         }
160         if 40 <= code && code <= 49 {
161                 w.Header().Add("Content-Type", "text/plain")
162                 w.WriteHeader(http.StatusBadGateway)
163                 fmt.Fprintf(w, "%s\n%d (%s)\n", cols[1], code, codeName)
164                 return false, nil
165         }
166         if 50 <= code && code <= 59 {
167                 w.Header().Add("Content-Type", "text/plain")
168                 w.WriteHeader(http.StatusBadGateway)
169                 fmt.Fprintf(w, "%s\n%d (%s)\n", cols[1], code, codeName)
170                 return false, nil
171         }
172         if 60 <= code && code <= 69 {
173                 w.Header().Add("Content-Type", "text/plain")
174                 w.WriteHeader(http.StatusUnauthorized)
175                 fmt.Fprintf(w, "%s\n%d (%s)\n", cols[1], code, codeName)
176                 return false, nil
177         }
178         if !(20 <= code && code <= 29) {
179                 err = fmt.Errorf("unknown response code: %d", code)
180                 log.Printf("%s: %s\n", req.URL, err)
181                 return false, err
182         }
183         contentType := strings.Split(strings.TrimRight(cols[1], "\r\n"), ";")[0]
184         if contentType == ContentTypeGemini &&
185                 !strings.Contains(req.Header.Get("Accept"), ContentTypeGemini) {
186                 w.Header().Add("Content-Type", "text/html")
187                 w.WriteHeader(http.StatusOK)
188                 raw, err := io.ReadAll(br)
189                 if err != nil {
190                         log.Printf("%s: can not read response body: %+v\n", req.URL, err)
191                         return false, err
192                 }
193                 var buf bytes.Buffer
194                 fmt.Fprintf(&buf, `<!DOCTYPE html>
195 <html><head><title>%d (%s)</title></head><body>
196 `, code, codeName)
197                 pre := false
198                 for _, line := range strings.Split(string(raw), "\n") {
199                         if strings.HasPrefix(line, "```") {
200                                 if pre {
201                                         buf.WriteString("</pre>\n")
202                                 } else {
203                                         buf.WriteString("<pre>" + line[3:] + "\n")
204                                 }
205                                 pre = !pre
206                                 continue
207                         }
208                         if pre {
209                                 fmt.Fprintf(&buf, "%s\n", line)
210                                 continue
211                         }
212                         if strings.HasPrefix(line, "=> ") {
213                                 cols = strings.Fields(line)
214                                 u := geminifyURL(host, cols[1], paths...)
215                                 switch len(cols) {
216                                 case 2:
217                                         fmt.Fprintf(
218                                                 &buf, "<a href=\"%s\">%s</a><br/>\n",
219                                                 u, html.EscapeString(cols[1]),
220                                         )
221                                 default:
222                                         fmt.Fprintf(
223                                                 &buf, "<a href=\"%s\">%s</a> (<tt>%s</tt>)<br/>\n",
224                                                 u, html.EscapeString(strings.Join(cols[2:], " ")), cols[1],
225                                         )
226                                 }
227                                 continue
228                         }
229                         if strings.HasPrefix(line, "# ") {
230                                 fmt.Fprintf(&buf, "<h1>%s</h1>\n", html.EscapeString(line[2:]))
231                                 continue
232                         }
233                         if strings.HasPrefix(line, "## ") {
234                                 fmt.Fprintf(&buf, "<h2>%s</h2>\n", html.EscapeString(line[3:]))
235                                 continue
236                         }
237                         if strings.HasPrefix(line, "### ") {
238                                 fmt.Fprintf(&buf, "<h3>%s</h3>\n", html.EscapeString(line[4:]))
239                                 continue
240                         }
241                         if strings.HasPrefix(line, "* ") {
242                                 fmt.Fprintf(&buf, "&bullet; %s\n", html.EscapeString(line[2:]))
243                                 continue
244                         }
245                         if strings.HasPrefix(line, "> ") {
246                                 fmt.Fprintf(
247                                         &buf, "<blockquote><tt>%s</tt></blockquote>\n",
248                                         html.EscapeString(line[2:]),
249                                 )
250                                 continue
251                         }
252                         fmt.Fprintf(&buf, "%s<br/>\n", html.EscapeString(line))
253                 }
254                 buf.WriteString("</body></html>\n")
255                 _, err = w.Write(buf.Bytes())
256                 return false, err
257         }
258         w.Header().Add("Content-Type", contentType)
259         w.WriteHeader(http.StatusOK)
260         _, err = io.Copy(w, br)
261         if err != nil {
262                 log.Printf("%s: can not read response body: %+v\n", req.URL, err)
263         }
264         return false, err
265 }