summaryrefslogtreecommitdiff
path: root/src/gmi/gmi.go
blob: e37ca7494e6a444cb9b15a43e9cee90eaed22a6b (plain)
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
// Package gmi implements the gemini-based api for the mediocre-blog.
package gmi

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"mime"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"strings"

	"dev.mediocregopher.com/mediocre-blog.git/src/cache"
	"dev.mediocregopher.com/mediocre-blog.git/src/cfg"
	"dev.mediocregopher.com/mediocre-blog.git/src/post"
	"dev.mediocregopher.com/mediocre-blog.git/src/post/asset"
	"dev.mediocregopher.com/mediocre-go-lib.git/mctx"
	"dev.mediocregopher.com/mediocre-go-lib.git/mlog"
	"git.sr.ht/~adnano/go-gemini"
	"git.sr.ht/~adnano/go-gemini/certificate"
)

// Params are used to instantiate a new API instance. All fields are required
// unless otherwise noted.
type Params struct {
	Logger *mlog.Logger
	Cache  cache.Cache

	PostStore       post.Store
	PostAssetLoader asset.Loader

	PublicURL        *url.URL
	ListenAddr       string
	CertificatesPath string

	HTTPPublicURL        *url.URL
	HTTPGeminiGatewayURL *url.URL
}

// SetupCfg implement the cfg.Cfger interface.
func (p *Params) SetupCfg(cfg *cfg.Cfg) {

	publicURLStr := cfg.String("gemini-public-url", "gemini://localhost:2065", "URL this service is accessible at")

	cfg.StringVar(&p.ListenAddr, "gemini-listen-addr", ":2065", "Address to listen for HTTP requests on")

	cfg.StringVar(&p.CertificatesPath, "gemini-certificates-path", "", "Path to directory where gemini certs should be created/stored")

	cfg.OnInit(func(context.Context) error {

		if p.CertificatesPath == "" {
			return errors.New("-gemini-certificates-path is required")
		}

		var err error

		*publicURLStr = strings.TrimSuffix(*publicURLStr, "/")

		if p.PublicURL, err = url.Parse(*publicURLStr); err != nil {
			return fmt.Errorf("parsing -gemini-public-url: %w", err)
		}

		return nil
	})
}

// Annotate implements mctx.Annotator interface.
func (p *Params) Annotate(a mctx.Annotations) {
	a["geminiPublicURL"] = p.PublicURL
	a["geminiListenAddr"] = p.ListenAddr
	a["geminiCertificatesPath"] = p.CertificatesPath
}

// API will listen on the port configured for it, and serve gemini requests for
// the mediocre-blog.
type API interface {
	Shutdown(ctx context.Context) error
}

type api struct {
	params Params
	srv    *gemini.Server
}

// New initializes and returns a new API instance, including setting up all
// listening ports.
func New(params Params) (API, error) {

	if err := os.MkdirAll(params.CertificatesPath, 0700); err != nil {
		return nil, fmt.Errorf("creating certificate directory %q: %w", params.CertificatesPath, err)
	}

	certStore := new(certificate.Store)
	certStore.Load(params.CertificatesPath)
	certStore.Register(params.PublicURL.Hostname())

	a := &api{
		params: params,
	}

	handler, err := a.handler()
	if err != nil {
		return nil, fmt.Errorf("constructing handler: %w", err)
	}

	a.srv = &gemini.Server{
		Addr:           params.ListenAddr,
		Handler:        handler,
		GetCertificate: certStore.Get,
	}

	go func() {

		err := a.srv.ListenAndServe(context.Background())

		if err != nil && !errors.Is(err, context.Canceled) {

			ctx := mctx.WithAnnotator(context.Background(), &a.params)
			a.params.Logger.Fatal(ctx, "serving gemini server", err)
		}
	}()

	return a, nil
}

func (a *api) Shutdown(ctx context.Context) error {
	return a.srv.Shutdown(ctx)
}

func (a *api) logReqMiddleware(h gemini.Handler) gemini.Handler {

	type logCtxKey string

	return gemini.HandlerFunc(func(
		ctx context.Context,
		rw gemini.ResponseWriter,
		r *gemini.Request,
	) {

		ctx = mctx.Annotate(ctx,
			logCtxKey("url"), r.URL.String(),
		)

		h.ServeGemini(ctx, rw, r)

		a.params.Logger.Info(ctx, "handled gemini request")
	})
}

func indexMiddleware(h gemini.Handler) gemini.Handler {

	return gemini.HandlerFunc(func(
		ctx context.Context,
		rw gemini.ResponseWriter,
		r *gemini.Request,
	) {
		if strings.HasSuffix(r.URL.Path, "/") {
			r.URL.Path += "index.gmi"
		}

		h.ServeGemini(ctx, rw, r)
	})
}

func feedMiddleware(h gemini.Handler) gemini.Handler {

	return gemini.HandlerFunc(func(
		ctx context.Context,
		rw gemini.ResponseWriter,
		r *gemini.Request,
	) {
		rw = forceResponseWriterMediaType(rw, "application/atom+xml")
		h.ServeGemini(ctx, rw, r)
	})
}

func postsMiddleware(tplHandler gemini.Handler) gemini.Handler {

	return gemini.HandlerFunc(func(
		ctx context.Context,
		rw gemini.ResponseWriter,
		r *gemini.Request,
	) {

		id := path.Base(r.URL.Path)
		id = strings.TrimSuffix(id, ".gmi")

		if id == "index" {
			tplHandler.ServeGemini(ctx, rw, r)
			return
		}

		ctx = withTplPath(ctx, "/posts/post.gmi")
		tplHandler.ServeGemini(ctx, rw, r)
	})
}

func (a *api) assetsMiddleware() gemini.Handler {

	return gemini.HandlerFunc(func(
		ctx context.Context,
		rw gemini.ResponseWriter,
		r *gemini.Request,
	) {

		path := strings.TrimPrefix(r.URL.Path, "/assets/")
		mimeType := mime.TypeByExtension(filepath.Ext(path))

		ctx = mctx.Annotate(ctx, "assetPath", path, "mimeType", mimeType)

		if mimeType != "" {
			rw.SetMediaType(mimeType)
		}

		buf := new(bytes.Buffer)

		err := a.params.PostAssetLoader.Load(path, buf, asset.LoadOpts{})

		if errors.Is(err, asset.ErrNotFound) {
			rw.WriteHeader(gemini.StatusNotFound, "Asset not found, sorry!")
			return

		} else if err != nil {
			a.params.Logger.Error(ctx, "error fetching asset", err)
			rw.WriteHeader(gemini.StatusTemporaryFailure, err.Error())
			return
		}

		if _, err := io.Copy(rw, buf); err != nil {
			a.params.Logger.Error(ctx, "error copying asset", err)
			rw.WriteHeader(gemini.StatusTemporaryFailure, err.Error())
			return
		}
	})
}

func (a *api) handler() (gemini.Handler, error) {

	tplHandler, err := a.tplHandler()
	if err != nil {
		return nil, fmt.Errorf("generating tpl handler: %w", err)
	}

	mux := new(gemini.Mux)
	mux.Handle("/posts/", postsMiddleware(tplHandler))
	mux.Handle("/assets/", a.assetsMiddleware())
	mux.Handle("/feed.xml", feedMiddleware(tplHandler))
	mux.Handle("/", tplHandler)

	var h gemini.Handler

	h = mux
	h = indexMiddleware(h)

	h = a.logReqMiddleware(h)
	h = cacheMiddleware(a.params.Cache)(h)

	return h, nil
}