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
|
package gemini
import (
"bufio"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"tildegit.org/tjp/gus"
"tildegit.org/tjp/gus/logging"
)
type titanRequestBodyKey struct{}
// TitanRequestBody is the key set in a handler's context for titan requests.
//
// When this key is present in the context (request.URL.Scheme will be "titan"), the
// corresponding value is a *bufio.Reader from which the request body can be read.
var TitanRequestBody = titanRequestBodyKey{}
type server struct {
ctx context.Context
errorLog logging.Logger
network string
address string
cancel context.CancelFunc
wg *sync.WaitGroup
listener net.Listener
handler gus.Handler
}
// NewServer builds a gemini server.
func NewServer(
ctx context.Context,
errorLog logging.Logger,
tlsConfig *tls.Config,
network string,
address string,
handler gus.Handler,
) (gus.Server, error) {
listener, err := net.Listen(network, address)
if err != nil {
return nil, err
}
addr := listener.Addr()
s := &server{
ctx: ctx,
errorLog: errorLog,
network: addr.Network(),
address: addr.String(),
wg: &sync.WaitGroup{},
listener: tls.NewListener(listener, tlsConfig),
handler: handler,
}
return s, nil
}
// Serve starts the server and blocks until it is closed.
//
// This function will allocate resources which are not cleaned up until
// Close() is called.
//
// It will respect cancellation of the context the server was created with,
// but be aware that Close() must still be called in that case to avoid
// dangling goroutines.
//
// On titan protocol requests it sets a key/value pair in the context. The
// key is TitanRequestBody, and the value is a *bufio.Reader from which the
// request body can be read.
func (s *server) Serve() error {
s.wg.Add(1)
defer s.wg.Done()
s.ctx, s.cancel = context.WithCancel(s.ctx)
s.wg.Add(1)
s.propagateCancel()
for {
conn, err := s.listener.Accept()
if err != nil {
if s.Closed() {
err = nil
} else {
_ = s.errorLog.Log("msg", "accept error", "error", err)
}
return err
}
s.wg.Add(1)
go s.handleConn(conn)
}
}
func (s *server) Close() {
s.cancel()
s.wg.Wait()
}
func (s *server) Network() string {
return s.network
}
func (s *server) Address() string {
return s.address
}
func (s *server) Hostname() string {
host, _, _ := net.SplitHostPort(s.address)
return host
}
func (s *server) Port() string {
_, portStr, _ := net.SplitHostPort(s.address)
return portStr
}
func (s *server) handleConn(conn net.Conn) {
defer s.wg.Done()
defer conn.Close()
buf := bufio.NewReader(conn)
var response *gus.Response
req, err := ParseRequest(buf)
if err != nil {
response = BadRequest(err.Error())
} else {
req.Server = s
req.RemoteAddr = conn.RemoteAddr()
if tlsconn, ok := conn.(*tls.Conn); ok {
state := tlsconn.ConnectionState()
req.TLSState = &state
}
ctx := s.ctx
if req.Scheme == "titan" {
len, err := sizeParam(req.Path)
if err == nil {
ctx = context.WithValue(
ctx,
TitanRequestBody,
io.LimitReader(buf, int64(len)),
)
}
}
defer func() {
if r := recover(); r != nil {
err := fmt.Errorf("%s", r)
_ = s.errorLog.Log("msg", "panic in handler", "err", err)
_, _ = io.Copy(conn, NewResponseReader(Failure(err)))
}
}()
response = s.handler(ctx, req)
if response == nil {
response = NotFound("Resource does not exist.")
}
}
defer response.Close()
_, _ = io.Copy(conn, NewResponseReader(response))
}
func (s *server) propagateCancel() {
go func() {
defer s.wg.Done()
<-s.ctx.Done()
_ = s.listener.Close()
}()
}
func (s *server) Closed() bool {
select {
case <-s.ctx.Done():
return true
default:
return false
}
}
func sizeParam(path string) (int, error) {
_, rest, found := strings.Cut(path, ";")
if !found {
return 0, errors.New("no params in path")
}
for _, piece := range strings.Split(rest, ";") {
key, val, _ := strings.Cut(piece, "=")
if key == "size" {
return strconv.Atoi(val)
}
}
return 0, errors.New("no size param found")
}
|