-
Notifications
You must be signed in to change notification settings - Fork 8
/
bhttp.go
596 lines (506 loc) · 12.4 KB
/
bhttp.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
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
package ohttp
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
type BinaryRequest http.Request
type BinaryResponse http.Response
type frameIndicator uint64
const (
// Framing indicators
knownLengthRequestFrame = frameIndicator(0)
knownLengthResponseFrame = frameIndicator(1)
unknownLengthRequestFrame = frameIndicator(2)
unknownLengthResponseFrame = frameIndicator(3)
)
var (
errProhibitedField = errors.New("Prohibited field detected")
errInformationalNotSupported = errors.New("Informational messages not supported")
)
func isProhibitedField(fieldName string) bool {
prohibitedFields := []string{":method", ":scheme", ":authority", ":path", ":status"}
for _, field := range prohibitedFields {
if field == fieldName {
return true
}
}
return false
}
func (f frameIndicator) Marshal() []byte {
b := new(bytes.Buffer)
Write(b, uint64(f))
return b.Bytes()
}
func UnmarshalFrameIndicator(b io.ByteReader) (frameIndicator, error) {
val, err := Read(b)
if err != nil {
return 0, err
}
return frameIndicator(val), nil
}
func encodeVarintSlice(b *bytes.Buffer, data []byte) {
Write(b, uint64(len(data)))
b.Write([]byte(data))
}
func readVarintSlice(b *bytes.Buffer) ([]byte, error) {
len, err := Read(b)
if err != nil {
return nil, err
}
value := make([]byte, len)
_, err = b.Read(value)
if err != nil {
return nil, err
}
return value, nil
}
// Request with Known-Length {
// Framing Indicator (i) = 0,
// Request Control Data (..),
// Known-Length Field Section (..),
// Known-Length Content (..),
// Known-Length Field Section (..),
// Padding (..),
// }
func (r *BinaryRequest) Marshal() ([]byte, error) {
b := new(bytes.Buffer)
// Framing
b.Write(knownLengthRequestFrame.Marshal())
// Control data
controlData := createRequestControlData(r)
b.Write(controlData.Marshal())
// Header fields
headerFields := requestHeaderFields(r)
encodeVarintSlice(b, headerFields.Marshal())
// Content
if r.Body != nil {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
encodeVarintSlice(b, body)
} else {
encodeVarintSlice(b, []byte{})
}
// Trailer fields
trailerFields := requestTrailerFields(r)
encodeVarintSlice(b, trailerFields.Marshal())
return b.Bytes(), nil
}
func UnmarshalBinaryRequest(data []byte) (*http.Request, error) {
b := bytes.NewBuffer(data)
// Framing
indicator, err := UnmarshalFrameIndicator(b)
if err != nil {
return nil, err
}
// Filter based on the type of frame
switch indicator {
case knownLengthRequestFrame:
break
case knownLengthResponseFrame:
return nil, fmt.Errorf("Expected binary HTTP request, not binary HTTP response")
case unknownLengthRequestFrame:
case unknownLengthResponseFrame:
default:
return nil, fmt.Errorf("Unsupported binary HTTP message type")
}
// Control data
controlData, err := UnmarshalRequestControlData(b)
if err != nil {
return nil, err
}
// Sanity check the method
switch controlData.method {
case http.MethodGet:
break
case http.MethodPost:
break
case http.MethodDelete:
break
case http.MethodPatch:
break
case http.MethodPut:
break
case http.MethodOptions:
break
case http.MethodTrace:
break
case http.MethodHead:
break
case http.MethodConnect:
break
default:
return nil, fmt.Errorf("Unsupported binary HTTP message request method: %s", controlData.method)
}
// Header fields
headerFields := new(fieldList)
encodedFieldData, err := readVarintSlice(b)
if err != nil {
return nil, err
}
err = headerFields.Unmarshal(bytes.NewBuffer(encodedFieldData))
if err != nil {
return nil, err
}
headerMap := make(map[string]string)
for _, field := range headerFields.fields {
if isProhibitedField(field.name) {
return nil, errProhibitedField
}
headerMap[field.name] = field.value
}
// Reconstruct the URL from Scheme, Authority, and Path
authority := controlData.authority
if authority == "" {
authority = headerMap["Host"]
if authority == "" {
authority = headerMap["host"]
}
}
url, err := url.Parse(fmt.Sprintf("%s://%s%s", controlData.scheme, authority, controlData.path))
if err != nil {
return nil, err
}
// Content and trailers
trailerFields := new(fieldList)
content, err := readVarintSlice(b)
if err != nil {
return nil, err
}
if len(content) == 0 {
// Content was truncated, so the trailers MUST also be truncated
trailers, err := readVarintSlice(b)
if err != nil {
return nil, err
}
if len(trailers) != 0 {
return nil, fmt.Errorf("Improperly truncated request")
}
} else {
// Content field was not truncated, so now check for trailers
encodedFieldData, err = readVarintSlice(b)
if err != nil {
return nil, err
}
if len(encodedFieldData) > 0 {
err = trailerFields.Unmarshal(bytes.NewBuffer(encodedFieldData))
if err != nil {
return nil, err
}
for _, field := range trailerFields.fields {
if isProhibitedField(field.name) {
return nil, errProhibitedField
}
}
}
}
// Construct the raw request
request, err := http.NewRequest(controlData.method, url.String(), bytes.NewBuffer(content))
if err != nil {
return nil, err
}
for _, field := range headerFields.fields {
request.Header.Set(field.name, field.value)
}
for _, field := range trailerFields.fields {
request.Trailer.Set(field.name, field.value)
}
return request, nil
}
// Request Control Data {
// Method Length (i),
// Method (..),
// Scheme Length (i),
// Scheme (..),
// Authority Length (i),
// Authority (..),
// Path Length (i),
// Path (..),
// }
type requestControlData struct {
method string
scheme string
authority string
path string
}
func createRequestControlData(r *BinaryRequest) requestControlData {
return requestControlData{
method: r.Method,
scheme: r.URL.Scheme,
authority: r.Host,
path: r.URL.Path,
}
}
func (d requestControlData) Marshal() []byte {
b := new(bytes.Buffer)
encodeVarintSlice(b, []byte(d.method))
encodeVarintSlice(b, []byte(d.scheme))
encodeVarintSlice(b, []byte(d.authority))
encodeVarintSlice(b, []byte(d.path))
return b.Bytes()
}
func UnmarshalRequestControlData(b *bytes.Buffer) (requestControlData, error) {
method, err := readVarintSlice(b)
if err != nil {
return requestControlData{}, err
}
scheme, err := readVarintSlice(b)
if err != nil {
return requestControlData{}, err
}
authority, err := readVarintSlice(b)
if err != nil {
return requestControlData{}, err
}
path, err := readVarintSlice(b)
if err != nil {
return requestControlData{}, err
}
return requestControlData{
method: string(method),
scheme: string(scheme),
authority: string(authority),
path: string(path),
}, nil
}
// Final Response Control Data {
// Status Code (i) = 200..599,
// }
type responseControlData struct {
statusCode int
}
func createResponseControlData(r *BinaryResponse) responseControlData {
return responseControlData{
statusCode: r.StatusCode,
}
}
func (d responseControlData) Marshal() []byte {
b := new(bytes.Buffer)
Write(b, uint64(d.statusCode))
return b.Bytes()
}
func UnmarshalResponseControlData(b *bytes.Buffer) (responseControlData, error) {
statusCode, err := Read(b)
if err != nil {
return responseControlData{}, err
}
return responseControlData{
statusCode: int(statusCode),
}, nil
}
type field struct {
name string
value string
}
func createHeaderFields(h http.Header) fieldList {
fields := make([]field, len(h))
i := 0
for h, v := range h {
// Convert the list of values to a string
b := new(bytes.Buffer)
for i, s := range v {
b.Write([]byte(s))
if i < len(v)-1 {
b.Write([]byte(" "))
}
}
fields[i] = field{
name: strings.ToLower(h),
value: string(b.Bytes()),
}
i++
}
return fieldList{fields}
}
func requestHeaderFields(r *BinaryRequest) fieldList {
return createHeaderFields(r.Header)
}
func requestTrailerFields(r *BinaryRequest) fieldList {
return createHeaderFields(r.Trailer)
}
func responseHeaderFields(r *BinaryResponse) fieldList {
return createHeaderFields(r.Header)
}
func responseTrailerFields(r *BinaryResponse) fieldList {
return createHeaderFields(r.Trailer)
}
func (f field) Marshal() []byte {
b := new(bytes.Buffer)
encodeVarintSlice(b, []byte(f.name))
encodeVarintSlice(b, []byte(f.value))
return b.Bytes()
}
func (f *field) Unmarshal(b *bytes.Buffer) error {
name, err := readVarintSlice(b)
if err != nil {
return err
}
value, err := readVarintSlice(b)
if err != nil {
return err
}
f.name = strings.ToLower(string(name))
f.value = string(value)
return nil
}
type fieldList struct {
fields []field
}
func (l fieldList) Marshal() []byte {
b := new(bytes.Buffer)
for _, f := range l.fields {
b.Write(f.Marshal())
}
return b.Bytes()
}
func (l *fieldList) Unmarshal(b *bytes.Buffer) error {
fields := make([]field, 0)
for {
if b.Len() == 0 {
break
}
field := new(field)
err := field.Unmarshal(b)
if err != nil {
return err
}
fields = append(fields, *field)
}
l.fields = fields
return nil
}
///////
// Responses
type finalResponseControlData struct {
statusCode int // 200..599
}
func (d finalResponseControlData) Marshal() []byte {
b := new(bytes.Buffer)
Write(b, uint64(d.statusCode))
return b.Bytes()
}
type infoResponseControlData struct {
statusCode int // 100..199
}
func (d infoResponseControlData) Marshal() []byte {
b := new(bytes.Buffer)
Write(b, uint64(d.statusCode))
return b.Bytes()
}
// Response with Known-Length {
// Framing Indicator (i) = 1,
// Known-Length Informational Response (..) ...,
// Final Response Control Data (..),
// Known-Length Field Section (..),
// Known-Length Content (..),
// Known-Length Field Section (..),
// Padding (..),
// }
func (r *BinaryResponse) Marshal() ([]byte, error) {
b := new(bytes.Buffer)
// Framing
b.Write(knownLengthResponseFrame.Marshal())
// TODO(caw): if the response is informational (100..199), encode it in an infrmational response code
if r.StatusCode < 200 || r.StatusCode > 599 {
return nil, errInformationalNotSupported
}
// Response control data
controlData := finalResponseControlData{r.StatusCode}
b.Write(controlData.Marshal())
// Header fields
headerFields := responseHeaderFields(r)
encodeVarintSlice(b, headerFields.Marshal())
// Content
if r.Body != nil {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
encodeVarintSlice(b, body)
} else {
encodeVarintSlice(b, []byte{})
}
// Trailer fields
trailerFields := responseTrailerFields(r)
encodeVarintSlice(b, trailerFields.Marshal())
return b.Bytes(), nil
}
func UnmarshalBinaryResponse(data []byte) (*http.Response, error) {
b := bytes.NewBuffer(data)
// Framing
indicator, err := UnmarshalFrameIndicator(b)
if err != nil {
return nil, err
}
// Filter based on the type of frame
switch indicator {
case knownLengthRequestFrame:
return nil, fmt.Errorf("Expected binary HTTP response, not binary HTTP request")
case knownLengthResponseFrame:
break
case unknownLengthRequestFrame:
case unknownLengthResponseFrame:
default:
return nil, fmt.Errorf("Unsupported binary HTTP message type")
}
// Control data
finalStatusCode, err := Read(b)
if err != nil {
return nil, err
}
// TODO(caw): if the status code is informational, then parse subsequent fields
if finalStatusCode < 200 || finalStatusCode > 599 {
return nil, errInformationalNotSupported
}
// Header fields
headerFields := new(fieldList)
encodedFieldData, err := readVarintSlice(b)
if err != nil {
return nil, err
}
err = headerFields.Unmarshal(bytes.NewBuffer(encodedFieldData))
if err != nil {
return nil, err
}
headerMap := make(map[string][]string)
for _, field := range headerFields.fields {
headerMap[field.name] = []string{field.value}
}
// Content
content, err := readVarintSlice(b)
if err != nil {
return nil, err
}
// Trailer
trailerFields := new(fieldList)
encodedFieldData, err = readVarintSlice(b)
if err != nil && err != io.EOF {
return nil, err
}
err = trailerFields.Unmarshal(bytes.NewBuffer(encodedFieldData))
if err != nil {
return nil, err
}
trailerMap := make(map[string][]string)
for _, field := range trailerFields.fields {
trailerMap[field.name] = []string{field.value}
}
// Construct the raw request
resp := &http.Response{
StatusCode: int(finalStatusCode),
Header: headerMap,
Trailer: trailerMap,
Body: ioutil.NopCloser(bytes.NewReader(content)),
}
return resp, nil
}
func CreateBinaryResponse(resp *http.Response) BinaryResponse {
return BinaryResponse(*resp)
}