aboutsummaryrefslogtreecommitdiffstats
path: root/internal/port/gopher.go
blob: abbc4d93d965d998bf8ab9fb50fc0ef4fc487b1c (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
package port

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

	"git.vulpes.one/Feuerfuchs/port/pkg/libgopher"

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

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

func renderGopherDirectory(w http.ResponseWriter, tpl *template.Template, assetList AssetList, uri string, hostport string, d libgopher.Directory) error {
	var title string

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

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

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

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

		if strings.HasPrefix(x.Selector, "URL:") || strings.HasPrefix(x.Selector, "/URL:") {
			link := strings.TrimPrefix(strings.TrimPrefix(x.Selector, "/"), "URL:")
			if strings.HasPrefix(link, "gemini://") {
				link = fmt.Sprintf(
					"/gemini/%s",
					strings.TrimPrefix(link, "gemini://"),
				)
			} else if strings.HasPrefix(link, "gopher://") {
				link = fmt.Sprintf(
					"/gopher/%s",
					strings.TrimPrefix(link, "gopher://"),
				)
			}
			tr.Link = template.URL(link)
		} else {
			var linkHostport string
			if x.Port != "70" {
				linkHostport = net.JoinHostPort(x.Host, x.Port)
			} else {
				linkHostport = x.Host
			}

			path := url.PathEscape(x.Selector)
			path = strings.Replace(path, "%2F", "/", -1)
			tr.Link = template.URL(
				fmt.Sprintf(
					"/gopher/%s/%s%s",
					linkHostport,
					string(byte(x.Type)),
					path,
				),
			)
		}

		out[i] = tr
	}

	if title == "" {
		if uri != "" {
			title = fmt.Sprintf("%s/%s", hostport, uri)
		} else {
			title = hostport
		}
	}

	return tpl.Execute(w, TemplateVariables{
		Title:    title,
		URI:      fmt.Sprintf("%s/%s", hostport, uri),
		Assets:   assetList,
		Lines:    out,
		Protocol: "gopher",
	})
}

// 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, assetList AssetList, robotsdebug bool) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		agent := req.UserAgent()
		path := strings.TrimPrefix(req.URL.Path, "/gopher/")

		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, "/", http.StatusFound)
			return
		}

		title := hostport

		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 {
			if e := tpl.Execute(w, TemplateVariables{
				Title:    title,
				URI:      hostport,
				Assets:   assetList,
				RawText:  fmt.Sprintf("Error: %s", err),
				Error:    true,
				Protocol: "gopher",
			}); e != nil {
				log.Println("Template error: " + e.Error())
				log.Println(err.Error())
			}
			return
		}

		if uri != "" {
			title = fmt.Sprintf("%s/%s", hostport, uri)
		}

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

		if err != nil {
			if e := tpl.Execute(w, TemplateVariables{
				Title:    title,
				URI:      fmt.Sprintf("%s/%s", hostport, uri),
				Assets:   assetList,
				RawText:  fmt.Sprintf("Error: %s", err),
				Error:    true,
				Protocol: "gopher",
			}); e != nil {
				log.Println("Template error: " + e.Error())
			}
			return
		}

		if res.Body != nil {
			if len(parts) < 2 {
				io.Copy(w, res.Body)
			} else if strings.HasPrefix(parts[1], "0") && !strings.HasSuffix(uri, ".xml") && !strings.HasSuffix(uri, ".asc") {
				buf := new(bytes.Buffer)
				buf.ReadFrom(res.Body)

				if err := tpl.Execute(w, TemplateVariables{
					Title:    title,
					URI:      fmt.Sprintf("%s/%s", hostport, uri),
					Assets:   assetList,
					RawText:  buf.String(),
					Protocol: "gopher",
				}); err != nil {
					log.Println("Template error: " + err.Error())
				}
			} else if strings.HasPrefix(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 := renderGopherDirectory(w, tpl, assetList, uri, hostport, res.Dir); err != nil {
				if e := tpl.Execute(w, TemplateVariables{
					Title:    title,
					URI:      fmt.Sprintf("%s/%s", hostport, uri),
					Assets:   assetList,
					RawText:  fmt.Sprintf("Error: %s", err),
					Error:    true,
					Protocol: "gopher",
				}); e != nil {
					log.Println("Template error: " + e.Error())
					log.Println(e.Error())
				}
			}
		}
	}
}