-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrequest.go
278 lines (257 loc) · 7.41 KB
/
request.go
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
package gemini
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net/url"
"strconv"
"strings"
)
// NoBody is an io.ReadCloser with no bytes. Read always returns EOF
// and Close always returns nil. It can be used in an outgoing client
// request to explicitly signal that a request has zero bytes.
// An alternative, however, is to simply set Request.Body to nil.
var NoBody = noBody{}
type noBody struct{}
func (noBody) Read([]byte) (int, error) { return 0, io.EOF }
func (noBody) Close() error { return nil }
func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil }
var (
// verify that an io.Copy from NoBody won't require a buffer:
_ io.WriterTo = NoBody
_ io.ReadCloser = NoBody
)
// Request contains the data of the client request
type Request struct {
URL *url.URL
ctx context.Context
conn *tls.Conn
Titan TitanRequest
}
type TitanRequest struct {
Edit bool
Token string
Mime string
// Size records the length of the associated content.
// The value -1 indicates that the length is unknown.
// Values >= 0 indicate that the given number of bytes may
// be read from Body.
//
// For client requests, a value of 0 with a non-nil Body is
// also treated as unknown.
Size int64
// Body is the request's body.
//
// For client requests, a nil body means the request has no
// body, such as a GET request. The HTTP Client's Transport
// is responsible for calling the Close method.
//
// For server requests, the Request Body is always non-nil
// but will return EOF immediately when no body is present.
// The Server will close the request body. The ServeHTTP
// Handler does not need to.
//
// Body must allow Read to be called concurrently with Close.
// In particular, calling Close should unblock a Read waiting
// for input.
Body io.ReadCloser
getBody func() (io.ReadCloser, error)
}
func (r *Request) Reset(conn *tls.Conn, rawurl string) error {
r.conn = conn
r.Titan.Edit = false
r.Titan.Mime = ""
r.Titan.Size = 0
r.Titan.Token = ""
r.Titan.Body = conn
var err error
r.URL, err = url.ParseRequestURI(rawurl)
if err != nil {
return fmt.Errorf("failed to parse request: %v, error: %v", rawurl, err)
}
if r.URL.Scheme == "" {
return fmt.Errorf("request is missing scheme: %v", rawurl)
}
if r.URL.Scheme == SchemaTitan {
err = r.resetTitanURL()
if err != nil {
return err
}
} else {
r.resetGeminiURL()
}
return err
}
func (r *Request) resetTitanURL() error {
parts := strings.Split(r.URL.Path, ";")
if len(parts) < 2 {
return errors.New("titan parameters expected")
}
r.URL.Path, parts = parts[0], parts[1:]
if parts[0] == "edit" {
r.Titan.Edit = true
if len(parts[1:]) > 0 {
return errors.New("titan request can either be edit or have parameters")
}
return nil
}
for _, part := range parts {
kv := strings.Split(part, "=")
if len(kv) != 2 {
continue
}
key := kv[0]
val := kv[1]
switch key {
case "token":
r.Titan.Token = val
case "mime":
r.Titan.Mime = val
case "size":
var err error
r.Titan.Size, err = strconv.ParseInt(val, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse titan size parameter: %s", val)
}
}
}
return nil
}
func (r *Request) resetGeminiURL() {
// Gemini specific handling
if r.URL.Path == "" {
r.URL.Path = "/"
}
}
// ReadTitanPayload reads titan payload from the stream into byte slice.
func (r *Request) ReadTitanPayload() ([]byte, error) {
buf := make([]byte, r.Titan.Size)
_, err := io.ReadFull(r.Titan.Body, buf)
return buf, err
}
func (r *Request) Certificate() *x509.Certificate {
if len(r.conn.ConnectionState().PeerCertificates) > 0 {
return r.conn.ConnectionState().PeerCertificates[0]
}
return nil
}
// Context returns the request's context. To change the context, use
// WithContext.
//
// The returned context is always non-nil; it defaults to the
// background context.
//
// For outgoing client requests, the context controls cancellation.
//
// For incoming server requests, the context is canceled when the
// client's connection closes, the request is canceled (with HTTP/2),
// or when the ServeHTTP method returns.
func (r *Request) Context() context.Context {
if r.ctx != nil {
return r.ctx
}
return context.Background()
}
// WithContext returns a shallow copy of r with its context changed
// to ctx. The provided ctx must be non-nil.
//
// For outgoing client request, the context controls the entire
// lifetime of a request and its response: obtaining a connection,
// sending the request, and reading the response headers and body.
//
// To create a new request with a context, use NewRequestWithContext.
// To change the context of a request, such as an incoming request you
// want to modify before sending back out, use Request.Clone. Between
// those two uses, it's rare to need WithContext.
func (r *Request) WithContext(ctx context.Context) *Request {
if ctx == nil {
panic("nil context")
}
r2 := new(Request)
*r2 = *r
r2.ctx = ctx
return r2
}
// NewRequestWithContext returns a new Request given a method, URL, and
// optional body.
//
// If the provided body is also an io.Closer, the returned
// Request.Body is set to body and will be closed by the Client
// methods Do, Post, and PostForm, and Transport.RoundTrip.
//
// NewRequestWithContext returns a Request suitable for use with
// Client.Do or Transport.RoundTrip. To create a request for use with
// testing a Server Handler, either use the NewRequest function in the
// net/http/httptest package, use ReadRequest, or manually update the
// Request fields. For an outgoing client request, the context
// controls the entire lifetime of a request and its response:
// obtaining a connection, sending the request, and reading the
// response headers and body. See the Request type's documentation for
// the difference between inbound and outbound request fields.
//
// If body is of type *bytes.Buffer, *bytes.Reader, or
// *strings.Reader, the returned request's ContentLength is set to its
// exact value (instead of -1), GetBody is populated (so 307 and 308
// redirects can replay the body), and Body is set to NoBody if the
// ContentLength is 0.
func NewRequestWithContext(ctx context.Context, urlStr string, body io.Reader) (*Request, error) {
if ctx == nil {
return nil, errors.New("gemini: nil Context")
}
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
req := &Request{
ctx: ctx,
URL: u,
}
if req.URL.Scheme == SchemaGemini {
return req, nil
}
return req, req.Titan.clientRequest(body)
}
func (r *TitanRequest) clientRequest(body io.Reader) error {
rc, ok := body.(io.ReadCloser)
if !ok && body != nil {
rc = io.NopCloser(body)
}
r.Body = rc
if body != nil {
switch v := body.(type) {
case *bytes.Buffer:
r.Size = int64(v.Len())
buf := v.Bytes()
r.getBody = func() (io.ReadCloser, error) {
r := bytes.NewReader(buf)
return io.NopCloser(r), nil
}
case *bytes.Reader:
r.Size = int64(v.Len())
snapshot := *v
r.getBody = func() (io.ReadCloser, error) {
r := snapshot
return io.NopCloser(&r), nil
}
case *strings.Reader:
r.Size = int64(v.Len())
snapshot := *v
r.getBody = func() (io.ReadCloser, error) {
r := snapshot
return io.NopCloser(&r), nil
}
default:
// indicate unknown length
// r.Size = -1
return errors.New("can't handle unknown size titan payloads")
}
if r.Size == 0 {
r.getBody = func() (io.ReadCloser, error) { return NoBody, nil }
}
}
return nil
}