-
Notifications
You must be signed in to change notification settings - Fork 171
/
header.go
148 lines (118 loc) · 2.51 KB
/
header.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
package base
import (
"bufio"
"fmt"
"net/http"
"sort"
"strings"
)
const (
headerMaxEntryCount = 255
headerMaxKeyLength = 512
headerMaxValueLength = 2048
)
func headerKeyNormalize(in string) string {
switch strings.ToLower(in) {
case "rtp-info":
return "RTP-Info"
case "www-authenticate":
return "WWW-Authenticate"
case "cseq":
return "CSeq"
}
return http.CanonicalHeaderKey(in)
}
// HeaderValue is an header value.
type HeaderValue []string
// Header is a RTSP reader, present in both Requests and Responses.
type Header map[string]HeaderValue
func (h *Header) unmarshal(br *bufio.Reader) error {
*h = make(Header)
count := 0
for {
byt, err := br.ReadByte()
if err != nil {
return err
}
if byt == '\r' {
err := readByteEqual(br, '\n')
if err != nil {
return err
}
break
}
if count >= headerMaxEntryCount {
return fmt.Errorf("headers count exceeds %d", headerMaxEntryCount)
}
key := string([]byte{byt})
byts, err := readBytesLimited(br, ':', headerMaxKeyLength-1)
if err != nil {
return fmt.Errorf("value is missing")
}
key += string(byts[:len(byts)-1])
key = headerKeyNormalize(key)
// https://tools.ietf.org/html/rfc2616
// The field value MAY be preceded by any amount of spaces
for {
byt, err := br.ReadByte()
if err != nil {
return err
}
if byt != ' ' {
break
}
}
br.UnreadByte() //nolint:errcheck
byts, err = readBytesLimited(br, '\r', headerMaxValueLength)
if err != nil {
return err
}
val := string(byts[:len(byts)-1])
err = readByteEqual(br, '\n')
if err != nil {
return err
}
(*h)[key] = append((*h)[key], val)
count++
}
return nil
}
func (h Header) marshalSize() int {
// sort headers by key
// in order to obtain deterministic results
keys := make([]string, len(h))
for key := range h {
keys = append(keys, key)
}
sort.Strings(keys)
n := 0
for _, key := range keys {
for _, val := range h[key] {
n += len([]byte(key + ": " + val + "\r\n"))
}
}
n += 2
return n
}
func (h Header) marshalTo(buf []byte) int {
// sort headers by key
// in order to obtain deterministic results
keys := make([]string, len(h))
for key := range h {
keys = append(keys, key)
}
sort.Strings(keys)
pos := 0
for _, key := range keys {
for _, val := range h[key] {
pos += copy(buf[pos:], []byte(key+": "+val+"\r\n"))
}
}
pos += copy(buf[pos:], []byte("\r\n"))
return pos
}
func (h Header) marshal() []byte {
buf := make([]byte, h.marshalSize())
h.marshalTo(buf)
return buf
}