aboutsummaryrefslogtreecommitdiffstats
path: root/gopherproxy.go
blob: 62b744686e16263d2a0eec1b936eff2c07a3589e (plain) (blame)
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package gopherproxy

import (
	"bytes"
	"fmt"
	"html"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"regexp"
	"strings"

	"github.com/temoto/robotstxt"

	"github.com/prologic/go-gopher"

	"github.com/gobuffalo/packr"

	"github.com/davidbyttow/govips/pkg/vips"
)

type Item struct {
	Link template.URL
	Type string
	Text string
}

func renderDirectory(w http.ResponseWriter, tpl *template.Template, styletext string, jstext string, uri string, hostport string, d gopher.Directory) error {
	var title string

	out := make([]Item, len(d.Items))

	for i, x := range d.Items {
		if x.Type == gopher.INFO && x.Selector == "TITLE" {
			title = x.Description
			continue
		}

		tr := Item{
			Text: x.Description,
			Type: x.Type.String(),
		}

		if x.Type == gopher.INFO {
			out[i] = tr
			continue
		}

		if strings.HasPrefix(x.Selector, "URL:") {
			tr.Link = template.URL(x.Selector[4:])
		} else {
			var hostport string
			if x.Port == 70 {
				hostport = x.Host
			} else {
				hostport = fmt.Sprintf("%s:%d", x.Host, x.Port)
			}
			path := url.PathEscape(x.Selector)
			path = strings.Replace(path, "%2F", "/", -1)
			tr.Link = template.URL(
				fmt.Sprintf(
					"/%s/%s%s",
					hostport,
					string(byte(x.Type)),
					path,
				),
			)
		}

		out[i] = tr
	}

	if title == "" {
		title = hostport
	}

	return tpl.Execute(w, struct {
		Title   string
		URI     string
		Style   string
		Script  string
		Lines   []Item
		RawText string
	}{title, fmt.Sprintf("%s/%s", hostport, uri), styletext, jstext, out, ""})
}

// GopherHandler returns a Handler that proxies requests
// to the specified Gopher server as denoated by the first argument
// to the request path and renders the content using the provided template.
// The optional robots parameters points to a robotstxt.RobotsData struct
// to test user agents against a configurable robotst.txt file.
func GopherHandler(tpl *template.Template, robotsdata *robotstxt.RobotsData, robotsdebug bool, styletext string, jstext string, uri string) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		agent := req.UserAgent()
		path := strings.TrimPrefix(req.URL.Path, "/")

		if robotsdata != nil && robotsdebug && !robotsdata.TestAgent(path, agent) {
			log.Printf("UserAgent %s ignored robots.txt", agent)
		}

		parts := strings.Split(path, "/")
		hostport := parts[0]

		if len(hostport) == 0 {
			http.Redirect(w, req, "/"+uri, http.StatusFound)
			return
		}

		var qs string

		if req.URL.RawQuery != "" {
			qs = fmt.Sprintf("?%s", url.QueryEscape(req.URL.RawQuery))
		}

		uri, err := url.QueryUnescape(strings.Join(parts[1:], "/"))
		if err != nil {
			io.WriteString(w, fmt.Sprintf("<b>Error:</b><pre>%s</pre>", err))
			return
		}

		res, err := gopher.Get(
			fmt.Sprintf(
				"gopher://%s/%s%s",
				hostport,
				uri,
				qs,
			),
		)

		if err != nil {
			io.WriteString(w, fmt.Sprintf("<b>Error:</b><pre>%s</pre>", err))
			return
		}

		if res.Body != nil {
			if len(parts) >= 2 && parts[1] == "0" { //strings.HasSuffix(uri, ".txt") || strings.HasSuffix(uri, ".md") {
				// handle .txt files
				buf := new(bytes.Buffer)
				buf.ReadFrom(res.Body)
				tpl.Execute(w, struct {
					Title   string
					URI     string
					Style   string
					Script  string
					RawText string
					Lines   []Item
				}{uri, fmt.Sprintf("%s/%s", hostport, uri), styletext, jstext, buf.String(), nil})
			} else if parts[1] == "T" {
				_, _, err = vips.NewTransform().
					Load(res.Body).
					ResizeStrategy(vips.ResizeStrategyAuto).
					ResizeWidth(160).
					Quality(75).
					Output(w).
					Apply()
			} else {
				io.Copy(w, res.Body)
			}
		} else {
			if err := renderDirectory(w, tpl, styletext, jstext, uri, hostport, res.Dir); err != nil {
				io.WriteString(w, fmt.Sprintf("<b>Error:</b><pre>%s</pre>", err))
				return
			}
		}
	}
}

// RobotsTxtHandler returns the contents of the robots.txt file
// if configured and valid.
func RobotsTxtHandler(robotstxtdata []byte) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		if robotstxtdata == nil {
			http.Error(w, "Not Found", http.StatusNotFound)
			return
		}

		w.Header().Set("Content-Type", "text/plain")
		w.Write(robotstxtdata)
	}
}

func FaviconHandler(favicondata []byte) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		if favicondata == nil {
			http.Error(w, "Not Found", http.StatusNotFound)
			return
		}

		w.Header().Set("Content-Type", "image/vnd.microsoft.icon")
		w.Write(favicondata)
	}
}

func FontHandler(woff2 bool, fontdata []byte) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		if fontdata == nil {
			http.Error(w, "Not Found", http.StatusNotFound)
			return
		}

		if woff2 {
			w.Header().Set("Content-Type", "font/woff2")
		} else {
			w.Header().Set("Content-Type", "font/woff")
		}

		w.Write(fontdata)
	}
}

// ListenAndServe creates a listening HTTP server bound to
// the interface specified by bind and sets up a Gopher to HTTP
// proxy proxying requests as requested and by default will prozy
// to a Gopher server address specified by uri if no servers is
// specified by the request. The robots argument is a pointer to
// a robotstxt.RobotsData struct for testing user agents against
// a configurable robots.txt file.
func ListenAndServe(bind, robotsfile string, robotsdebug bool, uri string) error {
	var (
		tpl        *template.Template
		robotsdata *robotstxt.RobotsData
	)

	robotstxtdata, err := ioutil.ReadFile(robotsfile)
	if err != nil {
		log.Printf("error reading robots.txt: %s", err)
		robotstxtdata = nil
	} else {
		robotsdata, err = robotstxt.FromBytes(robotstxtdata)
		if err != nil {
			log.Printf("error reading robots.txt: %s", err)
			robotstxtdata = nil
		}
	}

	box := packr.NewBox("./assets")

	fontdataw, err := box.Find("iosevka-term-ss03-regular.woff")
	if err != nil {
		fontdataw = []byte{}
	}

	fontdataw2, err := box.Find("iosevka-term-ss03-regular.woff2")
	if err != nil {
		fontdataw2 = []byte{}
	}

	styletext, err := box.FindString("style.css")
	if err != nil {
		styletext = ""
	}

	jstext, err := box.FindString("main.js")
	if err != nil {
		jstext = ""
	}

	favicondata, err := box.Find("favicon.ico")
	if err != nil {
		favicondata = []byte{}
	}

	tpldata, err := ioutil.ReadFile(".template")
	if err == nil {
		tpltext = string(tpldata)
	}

	funcMap := template.FuncMap{
		"safeHtml": func(s string) template.HTML {
			return template.HTML(s)
		},
		"safeCss": func(s string) template.CSS {
			return template.CSS(s)
		},
		"safeJs": func(s string) template.JS {
			return template.JS(s)
		},
		"HTMLEscape": func(s string) string {
			return html.EscapeString(s)
		},
		"split": strings.Split,
		"last": func(s []string) string {
			return s[len(s)-1]
		},
		"pop": func(s []string) []string {
			return s[:len(s)-1]
		},
		"replace": func(pattern, output string, input interface{}) string {
			var re = regexp.MustCompile(pattern)
			var inputStr = fmt.Sprintf("%v", input)
			return re.ReplaceAllString(inputStr, output)
		},
	}

	tpl, err = template.New("gophermenu").Funcs(funcMap).Parse(tpltext)
	if err != nil {
		log.Fatal(err)
	}

	vips.Startup(&vips.Config{
		ConcurrencyLevel: 2,
	})

	http.HandleFunc("/", GopherHandler(tpl, robotsdata, robotsdebug, styletext, jstext, uri))
	http.HandleFunc("/robots.txt", RobotsTxtHandler(robotstxtdata))
	http.HandleFunc("/favicon.ico", FaviconHandler(favicondata))
	http.HandleFunc("/iosevka-term-ss03-regular.woff", FontHandler(false, fontdataw))
	http.HandleFunc("/iosevka-term-ss03-regular.woff2", FontHandler(true, fontdataw2))
	//http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets/"))))

	return http.ListenAndServe(bind, nil)
}