Source file
src/net/http/h2_bundle.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package http
20
21 import (
22 "bufio"
23 "bytes"
24 "compress/gzip"
25 "context"
26 "crypto/rand"
27 "crypto/tls"
28 "encoding/binary"
29 "errors"
30 "fmt"
31 "io"
32 "io/fs"
33 "log"
34 "math"
35 "math/bits"
36 mathrand "math/rand"
37 "net"
38 "net/http/httptrace"
39 "net/textproto"
40 "net/url"
41 "os"
42 "reflect"
43 "runtime"
44 "sort"
45 "strconv"
46 "strings"
47 "sync"
48 "sync/atomic"
49 "time"
50
51 "golang.org/x/net/http/httpguts"
52 "golang.org/x/net/http2/hpack"
53 "golang.org/x/net/idna"
54 )
55
56
57
58
59
60
61
62 func http2asciiEqualFold(s, t string) bool {
63 if len(s) != len(t) {
64 return false
65 }
66 for i := 0; i < len(s); i++ {
67 if http2lower(s[i]) != http2lower(t[i]) {
68 return false
69 }
70 }
71 return true
72 }
73
74
75 func http2lower(b byte) byte {
76 if 'A' <= b && b <= 'Z' {
77 return b + ('a' - 'A')
78 }
79 return b
80 }
81
82
83
84 func http2isASCIIPrint(s string) bool {
85 for i := 0; i < len(s); i++ {
86 if s[i] < ' ' || s[i] > '~' {
87 return false
88 }
89 }
90 return true
91 }
92
93
94
95 func http2asciiToLower(s string) (lower string, ok bool) {
96 if !http2isASCIIPrint(s) {
97 return "", false
98 }
99 return strings.ToLower(s), true
100 }
101
102
103
104
105 const (
106 http2cipher_TLS_NULL_WITH_NULL_NULL uint16 = 0x0000
107 http2cipher_TLS_RSA_WITH_NULL_MD5 uint16 = 0x0001
108 http2cipher_TLS_RSA_WITH_NULL_SHA uint16 = 0x0002
109 http2cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0003
110 http2cipher_TLS_RSA_WITH_RC4_128_MD5 uint16 = 0x0004
111 http2cipher_TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
112 http2cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x0006
113 http2cipher_TLS_RSA_WITH_IDEA_CBC_SHA uint16 = 0x0007
114 http2cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0008
115 http2cipher_TLS_RSA_WITH_DES_CBC_SHA uint16 = 0x0009
116 http2cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000A
117 http2cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000B
118 http2cipher_TLS_DH_DSS_WITH_DES_CBC_SHA uint16 = 0x000C
119 http2cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x000D
120 http2cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x000E
121 http2cipher_TLS_DH_RSA_WITH_DES_CBC_SHA uint16 = 0x000F
122 http2cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0010
123 http2cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0011
124 http2cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA uint16 = 0x0012
125 http2cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0x0013
126 http2cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0014
127 http2cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA uint16 = 0x0015
128 http2cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x0016
129 http2cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 uint16 = 0x0017
130 http2cipher_TLS_DH_anon_WITH_RC4_128_MD5 uint16 = 0x0018
131 http2cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA uint16 = 0x0019
132 http2cipher_TLS_DH_anon_WITH_DES_CBC_SHA uint16 = 0x001A
133 http2cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0x001B
134
135 http2cipher_TLS_KRB5_WITH_DES_CBC_SHA uint16 = 0x001E
136 http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA uint16 = 0x001F
137 http2cipher_TLS_KRB5_WITH_RC4_128_SHA uint16 = 0x0020
138 http2cipher_TLS_KRB5_WITH_IDEA_CBC_SHA uint16 = 0x0021
139 http2cipher_TLS_KRB5_WITH_DES_CBC_MD5 uint16 = 0x0022
140 http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5 uint16 = 0x0023
141 http2cipher_TLS_KRB5_WITH_RC4_128_MD5 uint16 = 0x0024
142 http2cipher_TLS_KRB5_WITH_IDEA_CBC_MD5 uint16 = 0x0025
143 http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA uint16 = 0x0026
144 http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA uint16 = 0x0027
145 http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA uint16 = 0x0028
146 http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 uint16 = 0x0029
147 http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5 uint16 = 0x002A
148 http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5 uint16 = 0x002B
149 http2cipher_TLS_PSK_WITH_NULL_SHA uint16 = 0x002C
150 http2cipher_TLS_DHE_PSK_WITH_NULL_SHA uint16 = 0x002D
151 http2cipher_TLS_RSA_PSK_WITH_NULL_SHA uint16 = 0x002E
152 http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002F
153 http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0030
154 http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0031
155 http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA uint16 = 0x0032
156 http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0x0033
157 http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA uint16 = 0x0034
158 http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
159 http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0036
160 http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0037
161 http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA uint16 = 0x0038
162 http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0039
163 http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA uint16 = 0x003A
164 http2cipher_TLS_RSA_WITH_NULL_SHA256 uint16 = 0x003B
165 http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003C
166 http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x003D
167 http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x003E
168 http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x003F
169 http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 uint16 = 0x0040
170 http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0041
171 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0042
172 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0043
173 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0044
174 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0045
175 http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA uint16 = 0x0046
176
177
178
179
180
181 http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0x0067
182 http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x0068
183 http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x0069
184 http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 uint16 = 0x006A
185 http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 uint16 = 0x006B
186 http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256 uint16 = 0x006C
187 http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256 uint16 = 0x006D
188
189 http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0084
190 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0085
191 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0086
192 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0087
193 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0088
194 http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA uint16 = 0x0089
195 http2cipher_TLS_PSK_WITH_RC4_128_SHA uint16 = 0x008A
196 http2cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008B
197 http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA uint16 = 0x008C
198 http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA uint16 = 0x008D
199 http2cipher_TLS_DHE_PSK_WITH_RC4_128_SHA uint16 = 0x008E
200 http2cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x008F
201 http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0090
202 http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0091
203 http2cipher_TLS_RSA_PSK_WITH_RC4_128_SHA uint16 = 0x0092
204 http2cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0x0093
205 http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA uint16 = 0x0094
206 http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA uint16 = 0x0095
207 http2cipher_TLS_RSA_WITH_SEED_CBC_SHA uint16 = 0x0096
208 http2cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA uint16 = 0x0097
209 http2cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA uint16 = 0x0098
210 http2cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA uint16 = 0x0099
211 http2cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA uint16 = 0x009A
212 http2cipher_TLS_DH_anon_WITH_SEED_CBC_SHA uint16 = 0x009B
213 http2cipher_TLS_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009C
214 http2cipher_TLS_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009D
215 http2cipher_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x009E
216 http2cipher_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x009F
217 http2cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0x00A0
218 http2cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0x00A1
219 http2cipher_TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A2
220 http2cipher_TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A3
221 http2cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256 uint16 = 0x00A4
222 http2cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384 uint16 = 0x00A5
223 http2cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256 uint16 = 0x00A6
224 http2cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384 uint16 = 0x00A7
225 http2cipher_TLS_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00A8
226 http2cipher_TLS_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00A9
227 http2cipher_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AA
228 http2cipher_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AB
229 http2cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 uint16 = 0x00AC
230 http2cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 uint16 = 0x00AD
231 http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00AE
232 http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00AF
233 http2cipher_TLS_PSK_WITH_NULL_SHA256 uint16 = 0x00B0
234 http2cipher_TLS_PSK_WITH_NULL_SHA384 uint16 = 0x00B1
235 http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B2
236 http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B3
237 http2cipher_TLS_DHE_PSK_WITH_NULL_SHA256 uint16 = 0x00B4
238 http2cipher_TLS_DHE_PSK_WITH_NULL_SHA384 uint16 = 0x00B5
239 http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0x00B6
240 http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0x00B7
241 http2cipher_TLS_RSA_PSK_WITH_NULL_SHA256 uint16 = 0x00B8
242 http2cipher_TLS_RSA_PSK_WITH_NULL_SHA384 uint16 = 0x00B9
243 http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BA
244 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BB
245 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BC
246 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BD
247 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BE
248 http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0x00BF
249 http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C0
250 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C1
251 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C2
252 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C3
253 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C4
254 http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256 uint16 = 0x00C5
255
256 http2cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV uint16 = 0x00FF
257
258 http2cipher_TLS_FALLBACK_SCSV uint16 = 0x5600
259
260 http2cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA uint16 = 0xC001
261 http2cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA uint16 = 0xC002
262 http2cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC003
263 http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC004
264 http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC005
265 http2cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA uint16 = 0xC006
266 http2cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xC007
267 http2cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC008
268 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xC009
269 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xC00A
270 http2cipher_TLS_ECDH_RSA_WITH_NULL_SHA uint16 = 0xC00B
271 http2cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA uint16 = 0xC00C
272 http2cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC00D
273 http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC00E
274 http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC00F
275 http2cipher_TLS_ECDHE_RSA_WITH_NULL_SHA uint16 = 0xC010
276 http2cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xC011
277 http2cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC012
278 http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC013
279 http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC014
280 http2cipher_TLS_ECDH_anon_WITH_NULL_SHA uint16 = 0xC015
281 http2cipher_TLS_ECDH_anon_WITH_RC4_128_SHA uint16 = 0xC016
282 http2cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA uint16 = 0xC017
283 http2cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA uint16 = 0xC018
284 http2cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA uint16 = 0xC019
285 http2cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01A
286 http2cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01B
287 http2cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA uint16 = 0xC01C
288 http2cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA uint16 = 0xC01D
289 http2cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA uint16 = 0xC01E
290 http2cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA uint16 = 0xC01F
291 http2cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA uint16 = 0xC020
292 http2cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA uint16 = 0xC021
293 http2cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA uint16 = 0xC022
294 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC023
295 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC024
296 http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC025
297 http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC026
298 http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC027
299 http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC028
300 http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 uint16 = 0xC029
301 http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 uint16 = 0xC02A
302 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02B
303 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02C
304 http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02D
305 http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC02E
306 http2cipher_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC02F
307 http2cipher_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC030
308 http2cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xC031
309 http2cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 uint16 = 0xC032
310 http2cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA uint16 = 0xC033
311 http2cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA uint16 = 0xC034
312 http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA uint16 = 0xC035
313 http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA uint16 = 0xC036
314 http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 uint16 = 0xC037
315 http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 uint16 = 0xC038
316 http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA uint16 = 0xC039
317 http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256 uint16 = 0xC03A
318 http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384 uint16 = 0xC03B
319 http2cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03C
320 http2cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03D
321 http2cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC03E
322 http2cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC03F
323 http2cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC040
324 http2cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC041
325 http2cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC042
326 http2cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC043
327 http2cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC044
328 http2cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC045
329 http2cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC046
330 http2cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC047
331 http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC048
332 http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC049
333 http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04A
334 http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04B
335 http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04C
336 http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04D
337 http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC04E
338 http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC04F
339 http2cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC050
340 http2cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC051
341 http2cipher_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC052
342 http2cipher_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC053
343 http2cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC054
344 http2cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC055
345 http2cipher_TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC056
346 http2cipher_TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC057
347 http2cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC058
348 http2cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC059
349 http2cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05A
350 http2cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05B
351 http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05C
352 http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05D
353 http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC05E
354 http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC05F
355 http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC060
356 http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC061
357 http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC062
358 http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC063
359 http2cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC064
360 http2cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC065
361 http2cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC066
362 http2cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC067
363 http2cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC068
364 http2cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC069
365 http2cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06A
366 http2cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06B
367 http2cipher_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06C
368 http2cipher_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06D
369 http2cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 uint16 = 0xC06E
370 http2cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 uint16 = 0xC06F
371 http2cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 uint16 = 0xC070
372 http2cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 uint16 = 0xC071
373 http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC072
374 http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC073
375 http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC074
376 http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC075
377 http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC076
378 http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC077
379 http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC078
380 http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC079
381 http2cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07A
382 http2cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07B
383 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07C
384 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07D
385 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC07E
386 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC07F
387 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC080
388 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC081
389 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC082
390 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC083
391 http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC084
392 http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC085
393 http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC086
394 http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC087
395 http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC088
396 http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC089
397 http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08A
398 http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08B
399 http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08C
400 http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08D
401 http2cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC08E
402 http2cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC08F
403 http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC090
404 http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC091
405 http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 uint16 = 0xC092
406 http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 uint16 = 0xC093
407 http2cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC094
408 http2cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC095
409 http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC096
410 http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC097
411 http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC098
412 http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC099
413 http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 uint16 = 0xC09A
414 http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 uint16 = 0xC09B
415 http2cipher_TLS_RSA_WITH_AES_128_CCM uint16 = 0xC09C
416 http2cipher_TLS_RSA_WITH_AES_256_CCM uint16 = 0xC09D
417 http2cipher_TLS_DHE_RSA_WITH_AES_128_CCM uint16 = 0xC09E
418 http2cipher_TLS_DHE_RSA_WITH_AES_256_CCM uint16 = 0xC09F
419 http2cipher_TLS_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A0
420 http2cipher_TLS_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A1
421 http2cipher_TLS_DHE_RSA_WITH_AES_128_CCM_8 uint16 = 0xC0A2
422 http2cipher_TLS_DHE_RSA_WITH_AES_256_CCM_8 uint16 = 0xC0A3
423 http2cipher_TLS_PSK_WITH_AES_128_CCM uint16 = 0xC0A4
424 http2cipher_TLS_PSK_WITH_AES_256_CCM uint16 = 0xC0A5
425 http2cipher_TLS_DHE_PSK_WITH_AES_128_CCM uint16 = 0xC0A6
426 http2cipher_TLS_DHE_PSK_WITH_AES_256_CCM uint16 = 0xC0A7
427 http2cipher_TLS_PSK_WITH_AES_128_CCM_8 uint16 = 0xC0A8
428 http2cipher_TLS_PSK_WITH_AES_256_CCM_8 uint16 = 0xC0A9
429 http2cipher_TLS_PSK_DHE_WITH_AES_128_CCM_8 uint16 = 0xC0AA
430 http2cipher_TLS_PSK_DHE_WITH_AES_256_CCM_8 uint16 = 0xC0AB
431 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM uint16 = 0xC0AC
432 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM uint16 = 0xC0AD
433 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 uint16 = 0xC0AE
434 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 uint16 = 0xC0AF
435
436
437
438 http2cipher_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA8
439 http2cipher_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCA9
440 http2cipher_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAA
441 http2cipher_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAB
442 http2cipher_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAC
443 http2cipher_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAD
444 http2cipher_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 uint16 = 0xCCAE
445 )
446
447
448
449
450
451
452
453
454 func http2isBadCipher(cipher uint16) bool {
455 switch cipher {
456 case http2cipher_TLS_NULL_WITH_NULL_NULL,
457 http2cipher_TLS_RSA_WITH_NULL_MD5,
458 http2cipher_TLS_RSA_WITH_NULL_SHA,
459 http2cipher_TLS_RSA_EXPORT_WITH_RC4_40_MD5,
460 http2cipher_TLS_RSA_WITH_RC4_128_MD5,
461 http2cipher_TLS_RSA_WITH_RC4_128_SHA,
462 http2cipher_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
463 http2cipher_TLS_RSA_WITH_IDEA_CBC_SHA,
464 http2cipher_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,
465 http2cipher_TLS_RSA_WITH_DES_CBC_SHA,
466 http2cipher_TLS_RSA_WITH_3DES_EDE_CBC_SHA,
467 http2cipher_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
468 http2cipher_TLS_DH_DSS_WITH_DES_CBC_SHA,
469 http2cipher_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA,
470 http2cipher_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
471 http2cipher_TLS_DH_RSA_WITH_DES_CBC_SHA,
472 http2cipher_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA,
473 http2cipher_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
474 http2cipher_TLS_DHE_DSS_WITH_DES_CBC_SHA,
475 http2cipher_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
476 http2cipher_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
477 http2cipher_TLS_DHE_RSA_WITH_DES_CBC_SHA,
478 http2cipher_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
479 http2cipher_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5,
480 http2cipher_TLS_DH_anon_WITH_RC4_128_MD5,
481 http2cipher_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA,
482 http2cipher_TLS_DH_anon_WITH_DES_CBC_SHA,
483 http2cipher_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA,
484 http2cipher_TLS_KRB5_WITH_DES_CBC_SHA,
485 http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_SHA,
486 http2cipher_TLS_KRB5_WITH_RC4_128_SHA,
487 http2cipher_TLS_KRB5_WITH_IDEA_CBC_SHA,
488 http2cipher_TLS_KRB5_WITH_DES_CBC_MD5,
489 http2cipher_TLS_KRB5_WITH_3DES_EDE_CBC_MD5,
490 http2cipher_TLS_KRB5_WITH_RC4_128_MD5,
491 http2cipher_TLS_KRB5_WITH_IDEA_CBC_MD5,
492 http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA,
493 http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA,
494 http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_SHA,
495 http2cipher_TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5,
496 http2cipher_TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5,
497 http2cipher_TLS_KRB5_EXPORT_WITH_RC4_40_MD5,
498 http2cipher_TLS_PSK_WITH_NULL_SHA,
499 http2cipher_TLS_DHE_PSK_WITH_NULL_SHA,
500 http2cipher_TLS_RSA_PSK_WITH_NULL_SHA,
501 http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA,
502 http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA,
503 http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA,
504 http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
505 http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
506 http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA,
507 http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA,
508 http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA,
509 http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA,
510 http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
511 http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
512 http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA,
513 http2cipher_TLS_RSA_WITH_NULL_SHA256,
514 http2cipher_TLS_RSA_WITH_AES_128_CBC_SHA256,
515 http2cipher_TLS_RSA_WITH_AES_256_CBC_SHA256,
516 http2cipher_TLS_DH_DSS_WITH_AES_128_CBC_SHA256,
517 http2cipher_TLS_DH_RSA_WITH_AES_128_CBC_SHA256,
518 http2cipher_TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
519 http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
520 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA,
521 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA,
522 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA,
523 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
524 http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA,
525 http2cipher_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
526 http2cipher_TLS_DH_DSS_WITH_AES_256_CBC_SHA256,
527 http2cipher_TLS_DH_RSA_WITH_AES_256_CBC_SHA256,
528 http2cipher_TLS_DHE_DSS_WITH_AES_256_CBC_SHA256,
529 http2cipher_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
530 http2cipher_TLS_DH_anon_WITH_AES_128_CBC_SHA256,
531 http2cipher_TLS_DH_anon_WITH_AES_256_CBC_SHA256,
532 http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
533 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA,
534 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA,
535 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA,
536 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
537 http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA,
538 http2cipher_TLS_PSK_WITH_RC4_128_SHA,
539 http2cipher_TLS_PSK_WITH_3DES_EDE_CBC_SHA,
540 http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA,
541 http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA,
542 http2cipher_TLS_DHE_PSK_WITH_RC4_128_SHA,
543 http2cipher_TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA,
544 http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA,
545 http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA,
546 http2cipher_TLS_RSA_PSK_WITH_RC4_128_SHA,
547 http2cipher_TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA,
548 http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA,
549 http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA,
550 http2cipher_TLS_RSA_WITH_SEED_CBC_SHA,
551 http2cipher_TLS_DH_DSS_WITH_SEED_CBC_SHA,
552 http2cipher_TLS_DH_RSA_WITH_SEED_CBC_SHA,
553 http2cipher_TLS_DHE_DSS_WITH_SEED_CBC_SHA,
554 http2cipher_TLS_DHE_RSA_WITH_SEED_CBC_SHA,
555 http2cipher_TLS_DH_anon_WITH_SEED_CBC_SHA,
556 http2cipher_TLS_RSA_WITH_AES_128_GCM_SHA256,
557 http2cipher_TLS_RSA_WITH_AES_256_GCM_SHA384,
558 http2cipher_TLS_DH_RSA_WITH_AES_128_GCM_SHA256,
559 http2cipher_TLS_DH_RSA_WITH_AES_256_GCM_SHA384,
560 http2cipher_TLS_DH_DSS_WITH_AES_128_GCM_SHA256,
561 http2cipher_TLS_DH_DSS_WITH_AES_256_GCM_SHA384,
562 http2cipher_TLS_DH_anon_WITH_AES_128_GCM_SHA256,
563 http2cipher_TLS_DH_anon_WITH_AES_256_GCM_SHA384,
564 http2cipher_TLS_PSK_WITH_AES_128_GCM_SHA256,
565 http2cipher_TLS_PSK_WITH_AES_256_GCM_SHA384,
566 http2cipher_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256,
567 http2cipher_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384,
568 http2cipher_TLS_PSK_WITH_AES_128_CBC_SHA256,
569 http2cipher_TLS_PSK_WITH_AES_256_CBC_SHA384,
570 http2cipher_TLS_PSK_WITH_NULL_SHA256,
571 http2cipher_TLS_PSK_WITH_NULL_SHA384,
572 http2cipher_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256,
573 http2cipher_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384,
574 http2cipher_TLS_DHE_PSK_WITH_NULL_SHA256,
575 http2cipher_TLS_DHE_PSK_WITH_NULL_SHA384,
576 http2cipher_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256,
577 http2cipher_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384,
578 http2cipher_TLS_RSA_PSK_WITH_NULL_SHA256,
579 http2cipher_TLS_RSA_PSK_WITH_NULL_SHA384,
580 http2cipher_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
581 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256,
582 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
583 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256,
584 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
585 http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256,
586 http2cipher_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
587 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256,
588 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256,
589 http2cipher_TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256,
590 http2cipher_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
591 http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256,
592 http2cipher_TLS_EMPTY_RENEGOTIATION_INFO_SCSV,
593 http2cipher_TLS_ECDH_ECDSA_WITH_NULL_SHA,
594 http2cipher_TLS_ECDH_ECDSA_WITH_RC4_128_SHA,
595 http2cipher_TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
596 http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
597 http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA,
598 http2cipher_TLS_ECDHE_ECDSA_WITH_NULL_SHA,
599 http2cipher_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
600 http2cipher_TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
601 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
602 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
603 http2cipher_TLS_ECDH_RSA_WITH_NULL_SHA,
604 http2cipher_TLS_ECDH_RSA_WITH_RC4_128_SHA,
605 http2cipher_TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
606 http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
607 http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA,
608 http2cipher_TLS_ECDHE_RSA_WITH_NULL_SHA,
609 http2cipher_TLS_ECDHE_RSA_WITH_RC4_128_SHA,
610 http2cipher_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
611 http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
612 http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
613 http2cipher_TLS_ECDH_anon_WITH_NULL_SHA,
614 http2cipher_TLS_ECDH_anon_WITH_RC4_128_SHA,
615 http2cipher_TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA,
616 http2cipher_TLS_ECDH_anon_WITH_AES_128_CBC_SHA,
617 http2cipher_TLS_ECDH_anon_WITH_AES_256_CBC_SHA,
618 http2cipher_TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA,
619 http2cipher_TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA,
620 http2cipher_TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA,
621 http2cipher_TLS_SRP_SHA_WITH_AES_128_CBC_SHA,
622 http2cipher_TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA,
623 http2cipher_TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA,
624 http2cipher_TLS_SRP_SHA_WITH_AES_256_CBC_SHA,
625 http2cipher_TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA,
626 http2cipher_TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA,
627 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
628 http2cipher_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
629 http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
630 http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384,
631 http2cipher_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
632 http2cipher_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
633 http2cipher_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
634 http2cipher_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384,
635 http2cipher_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
636 http2cipher_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384,
637 http2cipher_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
638 http2cipher_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384,
639 http2cipher_TLS_ECDHE_PSK_WITH_RC4_128_SHA,
640 http2cipher_TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA,
641 http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA,
642 http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA,
643 http2cipher_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
644 http2cipher_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384,
645 http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA,
646 http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA256,
647 http2cipher_TLS_ECDHE_PSK_WITH_NULL_SHA384,
648 http2cipher_TLS_RSA_WITH_ARIA_128_CBC_SHA256,
649 http2cipher_TLS_RSA_WITH_ARIA_256_CBC_SHA384,
650 http2cipher_TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256,
651 http2cipher_TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384,
652 http2cipher_TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256,
653 http2cipher_TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384,
654 http2cipher_TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256,
655 http2cipher_TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384,
656 http2cipher_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256,
657 http2cipher_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384,
658 http2cipher_TLS_DH_anon_WITH_ARIA_128_CBC_SHA256,
659 http2cipher_TLS_DH_anon_WITH_ARIA_256_CBC_SHA384,
660 http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256,
661 http2cipher_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384,
662 http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256,
663 http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384,
664 http2cipher_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256,
665 http2cipher_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384,
666 http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256,
667 http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384,
668 http2cipher_TLS_RSA_WITH_ARIA_128_GCM_SHA256,
669 http2cipher_TLS_RSA_WITH_ARIA_256_GCM_SHA384,
670 http2cipher_TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256,
671 http2cipher_TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384,
672 http2cipher_TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256,
673 http2cipher_TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384,
674 http2cipher_TLS_DH_anon_WITH_ARIA_128_GCM_SHA256,
675 http2cipher_TLS_DH_anon_WITH_ARIA_256_GCM_SHA384,
676 http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256,
677 http2cipher_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384,
678 http2cipher_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256,
679 http2cipher_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384,
680 http2cipher_TLS_PSK_WITH_ARIA_128_CBC_SHA256,
681 http2cipher_TLS_PSK_WITH_ARIA_256_CBC_SHA384,
682 http2cipher_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256,
683 http2cipher_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384,
684 http2cipher_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256,
685 http2cipher_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384,
686 http2cipher_TLS_PSK_WITH_ARIA_128_GCM_SHA256,
687 http2cipher_TLS_PSK_WITH_ARIA_256_GCM_SHA384,
688 http2cipher_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256,
689 http2cipher_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384,
690 http2cipher_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256,
691 http2cipher_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384,
692 http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
693 http2cipher_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
694 http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
695 http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
696 http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
697 http2cipher_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
698 http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256,
699 http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384,
700 http2cipher_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256,
701 http2cipher_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384,
702 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
703 http2cipher_TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
704 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256,
705 http2cipher_TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384,
706 http2cipher_TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256,
707 http2cipher_TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384,
708 http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256,
709 http2cipher_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384,
710 http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256,
711 http2cipher_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384,
712 http2cipher_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256,
713 http2cipher_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384,
714 http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256,
715 http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384,
716 http2cipher_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256,
717 http2cipher_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384,
718 http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
719 http2cipher_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
720 http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256,
721 http2cipher_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384,
722 http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256,
723 http2cipher_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384,
724 http2cipher_TLS_RSA_WITH_AES_128_CCM,
725 http2cipher_TLS_RSA_WITH_AES_256_CCM,
726 http2cipher_TLS_RSA_WITH_AES_128_CCM_8,
727 http2cipher_TLS_RSA_WITH_AES_256_CCM_8,
728 http2cipher_TLS_PSK_WITH_AES_128_CCM,
729 http2cipher_TLS_PSK_WITH_AES_256_CCM,
730 http2cipher_TLS_PSK_WITH_AES_128_CCM_8,
731 http2cipher_TLS_PSK_WITH_AES_256_CCM_8:
732 return true
733 default:
734 return false
735 }
736 }
737
738
739 type http2ClientConnPool interface {
740
741
742
743
744
745
746 GetClientConn(req *Request, addr string) (*http2ClientConn, error)
747 MarkDead(*http2ClientConn)
748 }
749
750
751
752 type http2clientConnPoolIdleCloser interface {
753 http2ClientConnPool
754 closeIdleConnections()
755 }
756
757 var (
758 _ http2clientConnPoolIdleCloser = (*http2clientConnPool)(nil)
759 _ http2clientConnPoolIdleCloser = http2noDialClientConnPool{}
760 )
761
762
763 type http2clientConnPool struct {
764 t *http2Transport
765
766 mu sync.Mutex
767
768
769 conns map[string][]*http2ClientConn
770 dialing map[string]*http2dialCall
771 keys map[*http2ClientConn][]string
772 addConnCalls map[string]*http2addConnCall
773 }
774
775 func (p *http2clientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error) {
776 return p.getClientConn(req, addr, http2dialOnMiss)
777 }
778
779 const (
780 http2dialOnMiss = true
781 http2noDialOnMiss = false
782 )
783
784 func (p *http2clientConnPool) getClientConn(req *Request, addr string, dialOnMiss bool) (*http2ClientConn, error) {
785
786 if http2isConnectionCloseRequest(req) && dialOnMiss {
787
788 http2traceGetConn(req, addr)
789 const singleUse = true
790 cc, err := p.t.dialClientConn(req.Context(), addr, singleUse)
791 if err != nil {
792 return nil, err
793 }
794 return cc, nil
795 }
796 for {
797 p.mu.Lock()
798 for _, cc := range p.conns[addr] {
799 if cc.ReserveNewRequest() {
800
801
802
803 if !cc.getConnCalled {
804 http2traceGetConn(req, addr)
805 }
806 cc.getConnCalled = false
807 p.mu.Unlock()
808 return cc, nil
809 }
810 }
811 if !dialOnMiss {
812 p.mu.Unlock()
813 return nil, http2ErrNoCachedConn
814 }
815 http2traceGetConn(req, addr)
816 call := p.getStartDialLocked(req.Context(), addr)
817 p.mu.Unlock()
818 <-call.done
819 if http2shouldRetryDial(call, req) {
820 continue
821 }
822 cc, err := call.res, call.err
823 if err != nil {
824 return nil, err
825 }
826 if cc.ReserveNewRequest() {
827 return cc, nil
828 }
829 }
830 }
831
832
833 type http2dialCall struct {
834 _ http2incomparable
835 p *http2clientConnPool
836
837
838 ctx context.Context
839 done chan struct{}
840 res *http2ClientConn
841 err error
842 }
843
844
845 func (p *http2clientConnPool) getStartDialLocked(ctx context.Context, addr string) *http2dialCall {
846 if call, ok := p.dialing[addr]; ok {
847
848 return call
849 }
850 call := &http2dialCall{p: p, done: make(chan struct{}), ctx: ctx}
851 if p.dialing == nil {
852 p.dialing = make(map[string]*http2dialCall)
853 }
854 p.dialing[addr] = call
855 go call.dial(call.ctx, addr)
856 return call
857 }
858
859
860 func (c *http2dialCall) dial(ctx context.Context, addr string) {
861 const singleUse = false
862 c.res, c.err = c.p.t.dialClientConn(ctx, addr, singleUse)
863
864 c.p.mu.Lock()
865 delete(c.p.dialing, addr)
866 if c.err == nil {
867 c.p.addConnLocked(addr, c.res)
868 }
869 c.p.mu.Unlock()
870
871 close(c.done)
872 }
873
874
875
876
877
878
879
880
881
882 func (p *http2clientConnPool) addConnIfNeeded(key string, t *http2Transport, c *tls.Conn) (used bool, err error) {
883 p.mu.Lock()
884 for _, cc := range p.conns[key] {
885 if cc.CanTakeNewRequest() {
886 p.mu.Unlock()
887 return false, nil
888 }
889 }
890 call, dup := p.addConnCalls[key]
891 if !dup {
892 if p.addConnCalls == nil {
893 p.addConnCalls = make(map[string]*http2addConnCall)
894 }
895 call = &http2addConnCall{
896 p: p,
897 done: make(chan struct{}),
898 }
899 p.addConnCalls[key] = call
900 go call.run(t, key, c)
901 }
902 p.mu.Unlock()
903
904 <-call.done
905 if call.err != nil {
906 return false, call.err
907 }
908 return !dup, nil
909 }
910
911 type http2addConnCall struct {
912 _ http2incomparable
913 p *http2clientConnPool
914 done chan struct{}
915 err error
916 }
917
918 func (c *http2addConnCall) run(t *http2Transport, key string, tc *tls.Conn) {
919 cc, err := t.NewClientConn(tc)
920
921 p := c.p
922 p.mu.Lock()
923 if err != nil {
924 c.err = err
925 } else {
926 cc.getConnCalled = true
927 p.addConnLocked(key, cc)
928 }
929 delete(p.addConnCalls, key)
930 p.mu.Unlock()
931 close(c.done)
932 }
933
934
935 func (p *http2clientConnPool) addConnLocked(key string, cc *http2ClientConn) {
936 for _, v := range p.conns[key] {
937 if v == cc {
938 return
939 }
940 }
941 if p.conns == nil {
942 p.conns = make(map[string][]*http2ClientConn)
943 }
944 if p.keys == nil {
945 p.keys = make(map[*http2ClientConn][]string)
946 }
947 p.conns[key] = append(p.conns[key], cc)
948 p.keys[cc] = append(p.keys[cc], key)
949 }
950
951 func (p *http2clientConnPool) MarkDead(cc *http2ClientConn) {
952 p.mu.Lock()
953 defer p.mu.Unlock()
954 for _, key := range p.keys[cc] {
955 vv, ok := p.conns[key]
956 if !ok {
957 continue
958 }
959 newList := http2filterOutClientConn(vv, cc)
960 if len(newList) > 0 {
961 p.conns[key] = newList
962 } else {
963 delete(p.conns, key)
964 }
965 }
966 delete(p.keys, cc)
967 }
968
969 func (p *http2clientConnPool) closeIdleConnections() {
970 p.mu.Lock()
971 defer p.mu.Unlock()
972
973
974
975
976
977
978 for _, vv := range p.conns {
979 for _, cc := range vv {
980 cc.closeIfIdle()
981 }
982 }
983 }
984
985 func http2filterOutClientConn(in []*http2ClientConn, exclude *http2ClientConn) []*http2ClientConn {
986 out := in[:0]
987 for _, v := range in {
988 if v != exclude {
989 out = append(out, v)
990 }
991 }
992
993
994 if len(in) != len(out) {
995 in[len(in)-1] = nil
996 }
997 return out
998 }
999
1000
1001
1002
1003 type http2noDialClientConnPool struct{ *http2clientConnPool }
1004
1005 func (p http2noDialClientConnPool) GetClientConn(req *Request, addr string) (*http2ClientConn, error) {
1006 return p.getClientConn(req, addr, http2noDialOnMiss)
1007 }
1008
1009
1010
1011
1012
1013 func http2shouldRetryDial(call *http2dialCall, req *Request) bool {
1014 if call.err == nil {
1015
1016 return false
1017 }
1018 if call.ctx == req.Context() {
1019
1020
1021
1022 return false
1023 }
1024 if !errors.Is(call.err, context.Canceled) && !errors.Is(call.err, context.DeadlineExceeded) {
1025
1026
1027 return false
1028 }
1029
1030
1031 return call.ctx.Err() != nil
1032 }
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044 var http2dataChunkPools = [...]sync.Pool{
1045 {New: func() interface{} { return new([1 << 10]byte) }},
1046 {New: func() interface{} { return new([2 << 10]byte) }},
1047 {New: func() interface{} { return new([4 << 10]byte) }},
1048 {New: func() interface{} { return new([8 << 10]byte) }},
1049 {New: func() interface{} { return new([16 << 10]byte) }},
1050 }
1051
1052 func http2getDataBufferChunk(size int64) []byte {
1053 switch {
1054 case size <= 1<<10:
1055 return http2dataChunkPools[0].Get().(*[1 << 10]byte)[:]
1056 case size <= 2<<10:
1057 return http2dataChunkPools[1].Get().(*[2 << 10]byte)[:]
1058 case size <= 4<<10:
1059 return http2dataChunkPools[2].Get().(*[4 << 10]byte)[:]
1060 case size <= 8<<10:
1061 return http2dataChunkPools[3].Get().(*[8 << 10]byte)[:]
1062 default:
1063 return http2dataChunkPools[4].Get().(*[16 << 10]byte)[:]
1064 }
1065 }
1066
1067 func http2putDataBufferChunk(p []byte) {
1068 switch len(p) {
1069 case 1 << 10:
1070 http2dataChunkPools[0].Put((*[1 << 10]byte)(p))
1071 case 2 << 10:
1072 http2dataChunkPools[1].Put((*[2 << 10]byte)(p))
1073 case 4 << 10:
1074 http2dataChunkPools[2].Put((*[4 << 10]byte)(p))
1075 case 8 << 10:
1076 http2dataChunkPools[3].Put((*[8 << 10]byte)(p))
1077 case 16 << 10:
1078 http2dataChunkPools[4].Put((*[16 << 10]byte)(p))
1079 default:
1080 panic(fmt.Sprintf("unexpected buffer len=%v", len(p)))
1081 }
1082 }
1083
1084
1085
1086
1087
1088
1089 type http2dataBuffer struct {
1090 chunks [][]byte
1091 r int
1092 w int
1093 size int
1094 expected int64
1095 }
1096
1097 var http2errReadEmpty = errors.New("read from empty dataBuffer")
1098
1099
1100
1101 func (b *http2dataBuffer) Read(p []byte) (int, error) {
1102 if b.size == 0 {
1103 return 0, http2errReadEmpty
1104 }
1105 var ntotal int
1106 for len(p) > 0 && b.size > 0 {
1107 readFrom := b.bytesFromFirstChunk()
1108 n := copy(p, readFrom)
1109 p = p[n:]
1110 ntotal += n
1111 b.r += n
1112 b.size -= n
1113
1114 if b.r == len(b.chunks[0]) {
1115 http2putDataBufferChunk(b.chunks[0])
1116 end := len(b.chunks) - 1
1117 copy(b.chunks[:end], b.chunks[1:])
1118 b.chunks[end] = nil
1119 b.chunks = b.chunks[:end]
1120 b.r = 0
1121 }
1122 }
1123 return ntotal, nil
1124 }
1125
1126 func (b *http2dataBuffer) bytesFromFirstChunk() []byte {
1127 if len(b.chunks) == 1 {
1128 return b.chunks[0][b.r:b.w]
1129 }
1130 return b.chunks[0][b.r:]
1131 }
1132
1133
1134 func (b *http2dataBuffer) Len() int {
1135 return b.size
1136 }
1137
1138
1139 func (b *http2dataBuffer) Write(p []byte) (int, error) {
1140 ntotal := len(p)
1141 for len(p) > 0 {
1142
1143
1144
1145 want := int64(len(p))
1146 if b.expected > want {
1147 want = b.expected
1148 }
1149 chunk := b.lastChunkOrAlloc(want)
1150 n := copy(chunk[b.w:], p)
1151 p = p[n:]
1152 b.w += n
1153 b.size += n
1154 b.expected -= int64(n)
1155 }
1156 return ntotal, nil
1157 }
1158
1159 func (b *http2dataBuffer) lastChunkOrAlloc(want int64) []byte {
1160 if len(b.chunks) != 0 {
1161 last := b.chunks[len(b.chunks)-1]
1162 if b.w < len(last) {
1163 return last
1164 }
1165 }
1166 chunk := http2getDataBufferChunk(want)
1167 b.chunks = append(b.chunks, chunk)
1168 b.w = 0
1169 return chunk
1170 }
1171
1172
1173 type http2ErrCode uint32
1174
1175 const (
1176 http2ErrCodeNo http2ErrCode = 0x0
1177 http2ErrCodeProtocol http2ErrCode = 0x1
1178 http2ErrCodeInternal http2ErrCode = 0x2
1179 http2ErrCodeFlowControl http2ErrCode = 0x3
1180 http2ErrCodeSettingsTimeout http2ErrCode = 0x4
1181 http2ErrCodeStreamClosed http2ErrCode = 0x5
1182 http2ErrCodeFrameSize http2ErrCode = 0x6
1183 http2ErrCodeRefusedStream http2ErrCode = 0x7
1184 http2ErrCodeCancel http2ErrCode = 0x8
1185 http2ErrCodeCompression http2ErrCode = 0x9
1186 http2ErrCodeConnect http2ErrCode = 0xa
1187 http2ErrCodeEnhanceYourCalm http2ErrCode = 0xb
1188 http2ErrCodeInadequateSecurity http2ErrCode = 0xc
1189 http2ErrCodeHTTP11Required http2ErrCode = 0xd
1190 )
1191
1192 var http2errCodeName = map[http2ErrCode]string{
1193 http2ErrCodeNo: "NO_ERROR",
1194 http2ErrCodeProtocol: "PROTOCOL_ERROR",
1195 http2ErrCodeInternal: "INTERNAL_ERROR",
1196 http2ErrCodeFlowControl: "FLOW_CONTROL_ERROR",
1197 http2ErrCodeSettingsTimeout: "SETTINGS_TIMEOUT",
1198 http2ErrCodeStreamClosed: "STREAM_CLOSED",
1199 http2ErrCodeFrameSize: "FRAME_SIZE_ERROR",
1200 http2ErrCodeRefusedStream: "REFUSED_STREAM",
1201 http2ErrCodeCancel: "CANCEL",
1202 http2ErrCodeCompression: "COMPRESSION_ERROR",
1203 http2ErrCodeConnect: "CONNECT_ERROR",
1204 http2ErrCodeEnhanceYourCalm: "ENHANCE_YOUR_CALM",
1205 http2ErrCodeInadequateSecurity: "INADEQUATE_SECURITY",
1206 http2ErrCodeHTTP11Required: "HTTP_1_1_REQUIRED",
1207 }
1208
1209 func (e http2ErrCode) String() string {
1210 if s, ok := http2errCodeName[e]; ok {
1211 return s
1212 }
1213 return fmt.Sprintf("unknown error code 0x%x", uint32(e))
1214 }
1215
1216 func (e http2ErrCode) stringToken() string {
1217 if s, ok := http2errCodeName[e]; ok {
1218 return s
1219 }
1220 return fmt.Sprintf("ERR_UNKNOWN_%d", uint32(e))
1221 }
1222
1223
1224
1225 type http2ConnectionError http2ErrCode
1226
1227 func (e http2ConnectionError) Error() string {
1228 return fmt.Sprintf("connection error: %s", http2ErrCode(e))
1229 }
1230
1231
1232
1233 type http2StreamError struct {
1234 StreamID uint32
1235 Code http2ErrCode
1236 Cause error
1237 }
1238
1239
1240
1241
1242 var http2errFromPeer = errors.New("received from peer")
1243
1244 func http2streamError(id uint32, code http2ErrCode) http2StreamError {
1245 return http2StreamError{StreamID: id, Code: code}
1246 }
1247
1248 func (e http2StreamError) Error() string {
1249 if e.Cause != nil {
1250 return fmt.Sprintf("stream error: stream ID %d; %v; %v", e.StreamID, e.Code, e.Cause)
1251 }
1252 return fmt.Sprintf("stream error: stream ID %d; %v", e.StreamID, e.Code)
1253 }
1254
1255
1256
1257
1258
1259
1260 type http2goAwayFlowError struct{}
1261
1262 func (http2goAwayFlowError) Error() string { return "connection exceeded flow control window size" }
1263
1264
1265
1266
1267
1268
1269
1270
1271 type http2connError struct {
1272 Code http2ErrCode
1273 Reason string
1274 }
1275
1276 func (e http2connError) Error() string {
1277 return fmt.Sprintf("http2: connection error: %v: %v", e.Code, e.Reason)
1278 }
1279
1280 type http2pseudoHeaderError string
1281
1282 func (e http2pseudoHeaderError) Error() string {
1283 return fmt.Sprintf("invalid pseudo-header %q", string(e))
1284 }
1285
1286 type http2duplicatePseudoHeaderError string
1287
1288 func (e http2duplicatePseudoHeaderError) Error() string {
1289 return fmt.Sprintf("duplicate pseudo-header %q", string(e))
1290 }
1291
1292 type http2headerFieldNameError string
1293
1294 func (e http2headerFieldNameError) Error() string {
1295 return fmt.Sprintf("invalid header field name %q", string(e))
1296 }
1297
1298 type http2headerFieldValueError string
1299
1300 func (e http2headerFieldValueError) Error() string {
1301 return fmt.Sprintf("invalid header field value for %q", string(e))
1302 }
1303
1304 var (
1305 http2errMixPseudoHeaderTypes = errors.New("mix of request and response pseudo headers")
1306 http2errPseudoAfterRegular = errors.New("pseudo header field after regular")
1307 )
1308
1309
1310
1311 const http2inflowMinRefresh = 4 << 10
1312
1313
1314
1315
1316 type http2inflow struct {
1317 avail int32
1318 unsent int32
1319 }
1320
1321
1322 func (f *http2inflow) init(n int32) {
1323 f.avail = n
1324 }
1325
1326
1327
1328
1329
1330
1331
1332
1333 func (f *http2inflow) add(n int) (connAdd int32) {
1334 if n < 0 {
1335 panic("negative update")
1336 }
1337 unsent := int64(f.unsent) + int64(n)
1338
1339
1340 const maxWindow = 1<<31 - 1
1341 if unsent+int64(f.avail) > maxWindow {
1342 panic("flow control update exceeds maximum window size")
1343 }
1344 f.unsent = int32(unsent)
1345 if f.unsent < http2inflowMinRefresh && f.unsent < f.avail {
1346
1347
1348 return 0
1349 }
1350 f.avail += f.unsent
1351 f.unsent = 0
1352 return int32(unsent)
1353 }
1354
1355
1356
1357 func (f *http2inflow) take(n uint32) bool {
1358 if n > uint32(f.avail) {
1359 return false
1360 }
1361 f.avail -= int32(n)
1362 return true
1363 }
1364
1365
1366
1367
1368 func http2takeInflows(f1, f2 *http2inflow, n uint32) bool {
1369 if n > uint32(f1.avail) || n > uint32(f2.avail) {
1370 return false
1371 }
1372 f1.avail -= int32(n)
1373 f2.avail -= int32(n)
1374 return true
1375 }
1376
1377
1378 type http2outflow struct {
1379 _ http2incomparable
1380
1381
1382
1383 n int32
1384
1385
1386
1387
1388 conn *http2outflow
1389 }
1390
1391 func (f *http2outflow) setConnFlow(cf *http2outflow) { f.conn = cf }
1392
1393 func (f *http2outflow) available() int32 {
1394 n := f.n
1395 if f.conn != nil && f.conn.n < n {
1396 n = f.conn.n
1397 }
1398 return n
1399 }
1400
1401 func (f *http2outflow) take(n int32) {
1402 if n > f.available() {
1403 panic("internal error: took too much")
1404 }
1405 f.n -= n
1406 if f.conn != nil {
1407 f.conn.n -= n
1408 }
1409 }
1410
1411
1412
1413 func (f *http2outflow) add(n int32) bool {
1414 sum := f.n + n
1415 if (sum > n) == (f.n > 0) {
1416 f.n = sum
1417 return true
1418 }
1419 return false
1420 }
1421
1422 const http2frameHeaderLen = 9
1423
1424 var http2padZeros = make([]byte, 255)
1425
1426
1427
1428 type http2FrameType uint8
1429
1430 const (
1431 http2FrameData http2FrameType = 0x0
1432 http2FrameHeaders http2FrameType = 0x1
1433 http2FramePriority http2FrameType = 0x2
1434 http2FrameRSTStream http2FrameType = 0x3
1435 http2FrameSettings http2FrameType = 0x4
1436 http2FramePushPromise http2FrameType = 0x5
1437 http2FramePing http2FrameType = 0x6
1438 http2FrameGoAway http2FrameType = 0x7
1439 http2FrameWindowUpdate http2FrameType = 0x8
1440 http2FrameContinuation http2FrameType = 0x9
1441 )
1442
1443 var http2frameName = map[http2FrameType]string{
1444 http2FrameData: "DATA",
1445 http2FrameHeaders: "HEADERS",
1446 http2FramePriority: "PRIORITY",
1447 http2FrameRSTStream: "RST_STREAM",
1448 http2FrameSettings: "SETTINGS",
1449 http2FramePushPromise: "PUSH_PROMISE",
1450 http2FramePing: "PING",
1451 http2FrameGoAway: "GOAWAY",
1452 http2FrameWindowUpdate: "WINDOW_UPDATE",
1453 http2FrameContinuation: "CONTINUATION",
1454 }
1455
1456 func (t http2FrameType) String() string {
1457 if s, ok := http2frameName[t]; ok {
1458 return s
1459 }
1460 return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t))
1461 }
1462
1463
1464
1465 type http2Flags uint8
1466
1467
1468 func (f http2Flags) Has(v http2Flags) bool {
1469 return (f & v) == v
1470 }
1471
1472
1473 const (
1474
1475 http2FlagDataEndStream http2Flags = 0x1
1476 http2FlagDataPadded http2Flags = 0x8
1477
1478
1479 http2FlagHeadersEndStream http2Flags = 0x1
1480 http2FlagHeadersEndHeaders http2Flags = 0x4
1481 http2FlagHeadersPadded http2Flags = 0x8
1482 http2FlagHeadersPriority http2Flags = 0x20
1483
1484
1485 http2FlagSettingsAck http2Flags = 0x1
1486
1487
1488 http2FlagPingAck http2Flags = 0x1
1489
1490
1491 http2FlagContinuationEndHeaders http2Flags = 0x4
1492
1493 http2FlagPushPromiseEndHeaders http2Flags = 0x4
1494 http2FlagPushPromisePadded http2Flags = 0x8
1495 )
1496
1497 var http2flagName = map[http2FrameType]map[http2Flags]string{
1498 http2FrameData: {
1499 http2FlagDataEndStream: "END_STREAM",
1500 http2FlagDataPadded: "PADDED",
1501 },
1502 http2FrameHeaders: {
1503 http2FlagHeadersEndStream: "END_STREAM",
1504 http2FlagHeadersEndHeaders: "END_HEADERS",
1505 http2FlagHeadersPadded: "PADDED",
1506 http2FlagHeadersPriority: "PRIORITY",
1507 },
1508 http2FrameSettings: {
1509 http2FlagSettingsAck: "ACK",
1510 },
1511 http2FramePing: {
1512 http2FlagPingAck: "ACK",
1513 },
1514 http2FrameContinuation: {
1515 http2FlagContinuationEndHeaders: "END_HEADERS",
1516 },
1517 http2FramePushPromise: {
1518 http2FlagPushPromiseEndHeaders: "END_HEADERS",
1519 http2FlagPushPromisePadded: "PADDED",
1520 },
1521 }
1522
1523
1524
1525
1526 type http2frameParser func(fc *http2frameCache, fh http2FrameHeader, countError func(string), payload []byte) (http2Frame, error)
1527
1528 var http2frameParsers = map[http2FrameType]http2frameParser{
1529 http2FrameData: http2parseDataFrame,
1530 http2FrameHeaders: http2parseHeadersFrame,
1531 http2FramePriority: http2parsePriorityFrame,
1532 http2FrameRSTStream: http2parseRSTStreamFrame,
1533 http2FrameSettings: http2parseSettingsFrame,
1534 http2FramePushPromise: http2parsePushPromise,
1535 http2FramePing: http2parsePingFrame,
1536 http2FrameGoAway: http2parseGoAwayFrame,
1537 http2FrameWindowUpdate: http2parseWindowUpdateFrame,
1538 http2FrameContinuation: http2parseContinuationFrame,
1539 }
1540
1541 func http2typeFrameParser(t http2FrameType) http2frameParser {
1542 if f := http2frameParsers[t]; f != nil {
1543 return f
1544 }
1545 return http2parseUnknownFrame
1546 }
1547
1548
1549
1550
1551 type http2FrameHeader struct {
1552 valid bool
1553
1554
1555
1556
1557 Type http2FrameType
1558
1559
1560
1561 Flags http2Flags
1562
1563
1564
1565
1566 Length uint32
1567
1568
1569
1570 StreamID uint32
1571 }
1572
1573
1574
1575 func (h http2FrameHeader) Header() http2FrameHeader { return h }
1576
1577 func (h http2FrameHeader) String() string {
1578 var buf bytes.Buffer
1579 buf.WriteString("[FrameHeader ")
1580 h.writeDebug(&buf)
1581 buf.WriteByte(']')
1582 return buf.String()
1583 }
1584
1585 func (h http2FrameHeader) writeDebug(buf *bytes.Buffer) {
1586 buf.WriteString(h.Type.String())
1587 if h.Flags != 0 {
1588 buf.WriteString(" flags=")
1589 set := 0
1590 for i := uint8(0); i < 8; i++ {
1591 if h.Flags&(1<<i) == 0 {
1592 continue
1593 }
1594 set++
1595 if set > 1 {
1596 buf.WriteByte('|')
1597 }
1598 name := http2flagName[h.Type][http2Flags(1<<i)]
1599 if name != "" {
1600 buf.WriteString(name)
1601 } else {
1602 fmt.Fprintf(buf, "0x%x", 1<<i)
1603 }
1604 }
1605 }
1606 if h.StreamID != 0 {
1607 fmt.Fprintf(buf, " stream=%d", h.StreamID)
1608 }
1609 fmt.Fprintf(buf, " len=%d", h.Length)
1610 }
1611
1612 func (h *http2FrameHeader) checkValid() {
1613 if !h.valid {
1614 panic("Frame accessor called on non-owned Frame")
1615 }
1616 }
1617
1618 func (h *http2FrameHeader) invalidate() { h.valid = false }
1619
1620
1621
1622 var http2fhBytes = sync.Pool{
1623 New: func() interface{} {
1624 buf := make([]byte, http2frameHeaderLen)
1625 return &buf
1626 },
1627 }
1628
1629
1630
1631 func http2ReadFrameHeader(r io.Reader) (http2FrameHeader, error) {
1632 bufp := http2fhBytes.Get().(*[]byte)
1633 defer http2fhBytes.Put(bufp)
1634 return http2readFrameHeader(*bufp, r)
1635 }
1636
1637 func http2readFrameHeader(buf []byte, r io.Reader) (http2FrameHeader, error) {
1638 _, err := io.ReadFull(r, buf[:http2frameHeaderLen])
1639 if err != nil {
1640 return http2FrameHeader{}, err
1641 }
1642 return http2FrameHeader{
1643 Length: (uint32(buf[0])<<16 | uint32(buf[1])<<8 | uint32(buf[2])),
1644 Type: http2FrameType(buf[3]),
1645 Flags: http2Flags(buf[4]),
1646 StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
1647 valid: true,
1648 }, nil
1649 }
1650
1651
1652
1653
1654
1655
1656 type http2Frame interface {
1657 Header() http2FrameHeader
1658
1659
1660
1661
1662 invalidate()
1663 }
1664
1665
1666 type http2Framer struct {
1667 r io.Reader
1668 lastFrame http2Frame
1669 errDetail error
1670
1671
1672
1673
1674 countError func(errToken string)
1675
1676
1677
1678 lastHeaderStream uint32
1679
1680 maxReadSize uint32
1681 headerBuf [http2frameHeaderLen]byte
1682
1683
1684
1685
1686 getReadBuf func(size uint32) []byte
1687 readBuf []byte
1688
1689 maxWriteSize uint32
1690
1691 w io.Writer
1692 wbuf []byte
1693
1694
1695
1696
1697
1698
1699
1700 AllowIllegalWrites bool
1701
1702
1703
1704
1705
1706
1707 AllowIllegalReads bool
1708
1709
1710
1711
1712 ReadMetaHeaders *hpack.Decoder
1713
1714
1715
1716
1717
1718 MaxHeaderListSize uint32
1719
1720
1721
1722
1723
1724
1725
1726 logReads, logWrites bool
1727
1728 debugFramer *http2Framer
1729 debugFramerBuf *bytes.Buffer
1730 debugReadLoggerf func(string, ...interface{})
1731 debugWriteLoggerf func(string, ...interface{})
1732
1733 frameCache *http2frameCache
1734 }
1735
1736 func (fr *http2Framer) maxHeaderListSize() uint32 {
1737 if fr.MaxHeaderListSize == 0 {
1738 return 16 << 20
1739 }
1740 return fr.MaxHeaderListSize
1741 }
1742
1743 func (f *http2Framer) startWrite(ftype http2FrameType, flags http2Flags, streamID uint32) {
1744
1745 f.wbuf = append(f.wbuf[:0],
1746 0,
1747 0,
1748 0,
1749 byte(ftype),
1750 byte(flags),
1751 byte(streamID>>24),
1752 byte(streamID>>16),
1753 byte(streamID>>8),
1754 byte(streamID))
1755 }
1756
1757 func (f *http2Framer) endWrite() error {
1758
1759
1760 length := len(f.wbuf) - http2frameHeaderLen
1761 if length >= (1 << 24) {
1762 return http2ErrFrameTooLarge
1763 }
1764 _ = append(f.wbuf[:0],
1765 byte(length>>16),
1766 byte(length>>8),
1767 byte(length))
1768 if f.logWrites {
1769 f.logWrite()
1770 }
1771
1772 n, err := f.w.Write(f.wbuf)
1773 if err == nil && n != len(f.wbuf) {
1774 err = io.ErrShortWrite
1775 }
1776 return err
1777 }
1778
1779 func (f *http2Framer) logWrite() {
1780 if f.debugFramer == nil {
1781 f.debugFramerBuf = new(bytes.Buffer)
1782 f.debugFramer = http2NewFramer(nil, f.debugFramerBuf)
1783 f.debugFramer.logReads = false
1784
1785
1786 f.debugFramer.AllowIllegalReads = true
1787 }
1788 f.debugFramerBuf.Write(f.wbuf)
1789 fr, err := f.debugFramer.ReadFrame()
1790 if err != nil {
1791 f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f)
1792 return
1793 }
1794 f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, http2summarizeFrame(fr))
1795 }
1796
1797 func (f *http2Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) }
1798
1799 func (f *http2Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) }
1800
1801 func (f *http2Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) }
1802
1803 func (f *http2Framer) writeUint32(v uint32) {
1804 f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
1805 }
1806
1807 const (
1808 http2minMaxFrameSize = 1 << 14
1809 http2maxFrameSize = 1<<24 - 1
1810 )
1811
1812
1813
1814
1815 func (fr *http2Framer) SetReuseFrames() {
1816 if fr.frameCache != nil {
1817 return
1818 }
1819 fr.frameCache = &http2frameCache{}
1820 }
1821
1822 type http2frameCache struct {
1823 dataFrame http2DataFrame
1824 }
1825
1826 func (fc *http2frameCache) getDataFrame() *http2DataFrame {
1827 if fc == nil {
1828 return &http2DataFrame{}
1829 }
1830 return &fc.dataFrame
1831 }
1832
1833
1834 func http2NewFramer(w io.Writer, r io.Reader) *http2Framer {
1835 fr := &http2Framer{
1836 w: w,
1837 r: r,
1838 countError: func(string) {},
1839 logReads: http2logFrameReads,
1840 logWrites: http2logFrameWrites,
1841 debugReadLoggerf: log.Printf,
1842 debugWriteLoggerf: log.Printf,
1843 }
1844 fr.getReadBuf = func(size uint32) []byte {
1845 if cap(fr.readBuf) >= int(size) {
1846 return fr.readBuf[:size]
1847 }
1848 fr.readBuf = make([]byte, size)
1849 return fr.readBuf
1850 }
1851 fr.SetMaxReadFrameSize(http2maxFrameSize)
1852 return fr
1853 }
1854
1855
1856
1857
1858
1859 func (fr *http2Framer) SetMaxReadFrameSize(v uint32) {
1860 if v > http2maxFrameSize {
1861 v = http2maxFrameSize
1862 }
1863 fr.maxReadSize = v
1864 }
1865
1866
1867
1868
1869
1870
1871
1872
1873 func (fr *http2Framer) ErrorDetail() error {
1874 return fr.errDetail
1875 }
1876
1877
1878
1879 var http2ErrFrameTooLarge = errors.New("http2: frame too large")
1880
1881
1882
1883 func http2terminalReadFrameError(err error) bool {
1884 if _, ok := err.(http2StreamError); ok {
1885 return false
1886 }
1887 return err != nil
1888 }
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900 func (fr *http2Framer) ReadFrame() (http2Frame, error) {
1901 fr.errDetail = nil
1902 if fr.lastFrame != nil {
1903 fr.lastFrame.invalidate()
1904 }
1905 fh, err := http2readFrameHeader(fr.headerBuf[:], fr.r)
1906 if err != nil {
1907 return nil, err
1908 }
1909 if fh.Length > fr.maxReadSize {
1910 return nil, http2ErrFrameTooLarge
1911 }
1912 payload := fr.getReadBuf(fh.Length)
1913 if _, err := io.ReadFull(fr.r, payload); err != nil {
1914 return nil, err
1915 }
1916 f, err := http2typeFrameParser(fh.Type)(fr.frameCache, fh, fr.countError, payload)
1917 if err != nil {
1918 if ce, ok := err.(http2connError); ok {
1919 return nil, fr.connError(ce.Code, ce.Reason)
1920 }
1921 return nil, err
1922 }
1923 if err := fr.checkFrameOrder(f); err != nil {
1924 return nil, err
1925 }
1926 if fr.logReads {
1927 fr.debugReadLoggerf("http2: Framer %p: read %v", fr, http2summarizeFrame(f))
1928 }
1929 if fh.Type == http2FrameHeaders && fr.ReadMetaHeaders != nil {
1930 return fr.readMetaFrame(f.(*http2HeadersFrame))
1931 }
1932 return f, nil
1933 }
1934
1935
1936
1937
1938
1939 func (fr *http2Framer) connError(code http2ErrCode, reason string) error {
1940 fr.errDetail = errors.New(reason)
1941 return http2ConnectionError(code)
1942 }
1943
1944
1945
1946
1947 func (fr *http2Framer) checkFrameOrder(f http2Frame) error {
1948 last := fr.lastFrame
1949 fr.lastFrame = f
1950 if fr.AllowIllegalReads {
1951 return nil
1952 }
1953
1954 fh := f.Header()
1955 if fr.lastHeaderStream != 0 {
1956 if fh.Type != http2FrameContinuation {
1957 return fr.connError(http2ErrCodeProtocol,
1958 fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d",
1959 fh.Type, fh.StreamID,
1960 last.Header().Type, fr.lastHeaderStream))
1961 }
1962 if fh.StreamID != fr.lastHeaderStream {
1963 return fr.connError(http2ErrCodeProtocol,
1964 fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d",
1965 fh.StreamID, fr.lastHeaderStream))
1966 }
1967 } else if fh.Type == http2FrameContinuation {
1968 return fr.connError(http2ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID))
1969 }
1970
1971 switch fh.Type {
1972 case http2FrameHeaders, http2FrameContinuation:
1973 if fh.Flags.Has(http2FlagHeadersEndHeaders) {
1974 fr.lastHeaderStream = 0
1975 } else {
1976 fr.lastHeaderStream = fh.StreamID
1977 }
1978 }
1979
1980 return nil
1981 }
1982
1983
1984
1985
1986 type http2DataFrame struct {
1987 http2FrameHeader
1988 data []byte
1989 }
1990
1991 func (f *http2DataFrame) StreamEnded() bool {
1992 return f.http2FrameHeader.Flags.Has(http2FlagDataEndStream)
1993 }
1994
1995
1996
1997
1998
1999 func (f *http2DataFrame) Data() []byte {
2000 f.checkValid()
2001 return f.data
2002 }
2003
2004 func http2parseDataFrame(fc *http2frameCache, fh http2FrameHeader, countError func(string), payload []byte) (http2Frame, error) {
2005 if fh.StreamID == 0 {
2006
2007
2008
2009
2010
2011 countError("frame_data_stream_0")
2012 return nil, http2connError{http2ErrCodeProtocol, "DATA frame with stream ID 0"}
2013 }
2014 f := fc.getDataFrame()
2015 f.http2FrameHeader = fh
2016
2017 var padSize byte
2018 if fh.Flags.Has(http2FlagDataPadded) {
2019 var err error
2020 payload, padSize, err = http2readByte(payload)
2021 if err != nil {
2022 countError("frame_data_pad_byte_short")
2023 return nil, err
2024 }
2025 }
2026 if int(padSize) > len(payload) {
2027
2028
2029
2030
2031 countError("frame_data_pad_too_big")
2032 return nil, http2connError{http2ErrCodeProtocol, "pad size larger than data payload"}
2033 }
2034 f.data = payload[:len(payload)-int(padSize)]
2035 return f, nil
2036 }
2037
2038 var (
2039 http2errStreamID = errors.New("invalid stream ID")
2040 http2errDepStreamID = errors.New("invalid dependent stream ID")
2041 http2errPadLength = errors.New("pad length too large")
2042 http2errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled")
2043 )
2044
2045 func http2validStreamIDOrZero(streamID uint32) bool {
2046 return streamID&(1<<31) == 0
2047 }
2048
2049 func http2validStreamID(streamID uint32) bool {
2050 return streamID != 0 && streamID&(1<<31) == 0
2051 }
2052
2053
2054
2055
2056
2057
2058 func (f *http2Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
2059 return f.WriteDataPadded(streamID, endStream, data, nil)
2060 }
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071 func (f *http2Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
2072 if err := f.startWriteDataPadded(streamID, endStream, data, pad); err != nil {
2073 return err
2074 }
2075 return f.endWrite()
2076 }
2077
2078
2079
2080 func (f *http2Framer) startWriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
2081 if !http2validStreamID(streamID) && !f.AllowIllegalWrites {
2082 return http2errStreamID
2083 }
2084 if len(pad) > 0 {
2085 if len(pad) > 255 {
2086 return http2errPadLength
2087 }
2088 if !f.AllowIllegalWrites {
2089 for _, b := range pad {
2090 if b != 0 {
2091
2092 return http2errPadBytes
2093 }
2094 }
2095 }
2096 }
2097 var flags http2Flags
2098 if endStream {
2099 flags |= http2FlagDataEndStream
2100 }
2101 if pad != nil {
2102 flags |= http2FlagDataPadded
2103 }
2104 f.startWrite(http2FrameData, flags, streamID)
2105 if pad != nil {
2106 f.wbuf = append(f.wbuf, byte(len(pad)))
2107 }
2108 f.wbuf = append(f.wbuf, data...)
2109 f.wbuf = append(f.wbuf, pad...)
2110 return nil
2111 }
2112
2113
2114
2115
2116
2117
2118 type http2SettingsFrame struct {
2119 http2FrameHeader
2120 p []byte
2121 }
2122
2123 func http2parseSettingsFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
2124 if fh.Flags.Has(http2FlagSettingsAck) && fh.Length > 0 {
2125
2126
2127
2128
2129
2130
2131 countError("frame_settings_ack_with_length")
2132 return nil, http2ConnectionError(http2ErrCodeFrameSize)
2133 }
2134 if fh.StreamID != 0 {
2135
2136
2137
2138
2139
2140
2141
2142 countError("frame_settings_has_stream")
2143 return nil, http2ConnectionError(http2ErrCodeProtocol)
2144 }
2145 if len(p)%6 != 0 {
2146 countError("frame_settings_mod_6")
2147
2148 return nil, http2ConnectionError(http2ErrCodeFrameSize)
2149 }
2150 f := &http2SettingsFrame{http2FrameHeader: fh, p: p}
2151 if v, ok := f.Value(http2SettingInitialWindowSize); ok && v > (1<<31)-1 {
2152 countError("frame_settings_window_size_too_big")
2153
2154
2155
2156 return nil, http2ConnectionError(http2ErrCodeFlowControl)
2157 }
2158 return f, nil
2159 }
2160
2161 func (f *http2SettingsFrame) IsAck() bool {
2162 return f.http2FrameHeader.Flags.Has(http2FlagSettingsAck)
2163 }
2164
2165 func (f *http2SettingsFrame) Value(id http2SettingID) (v uint32, ok bool) {
2166 f.checkValid()
2167 for i := 0; i < f.NumSettings(); i++ {
2168 if s := f.Setting(i); s.ID == id {
2169 return s.Val, true
2170 }
2171 }
2172 return 0, false
2173 }
2174
2175
2176
2177 func (f *http2SettingsFrame) Setting(i int) http2Setting {
2178 buf := f.p
2179 return http2Setting{
2180 ID: http2SettingID(binary.BigEndian.Uint16(buf[i*6 : i*6+2])),
2181 Val: binary.BigEndian.Uint32(buf[i*6+2 : i*6+6]),
2182 }
2183 }
2184
2185 func (f *http2SettingsFrame) NumSettings() int { return len(f.p) / 6 }
2186
2187
2188 func (f *http2SettingsFrame) HasDuplicates() bool {
2189 num := f.NumSettings()
2190 if num == 0 {
2191 return false
2192 }
2193
2194
2195 if num < 10 {
2196 for i := 0; i < num; i++ {
2197 idi := f.Setting(i).ID
2198 for j := i + 1; j < num; j++ {
2199 idj := f.Setting(j).ID
2200 if idi == idj {
2201 return true
2202 }
2203 }
2204 }
2205 return false
2206 }
2207 seen := map[http2SettingID]bool{}
2208 for i := 0; i < num; i++ {
2209 id := f.Setting(i).ID
2210 if seen[id] {
2211 return true
2212 }
2213 seen[id] = true
2214 }
2215 return false
2216 }
2217
2218
2219
2220 func (f *http2SettingsFrame) ForeachSetting(fn func(http2Setting) error) error {
2221 f.checkValid()
2222 for i := 0; i < f.NumSettings(); i++ {
2223 if err := fn(f.Setting(i)); err != nil {
2224 return err
2225 }
2226 }
2227 return nil
2228 }
2229
2230
2231
2232
2233
2234
2235 func (f *http2Framer) WriteSettings(settings ...http2Setting) error {
2236 f.startWrite(http2FrameSettings, 0, 0)
2237 for _, s := range settings {
2238 f.writeUint16(uint16(s.ID))
2239 f.writeUint32(s.Val)
2240 }
2241 return f.endWrite()
2242 }
2243
2244
2245
2246
2247
2248 func (f *http2Framer) WriteSettingsAck() error {
2249 f.startWrite(http2FrameSettings, http2FlagSettingsAck, 0)
2250 return f.endWrite()
2251 }
2252
2253
2254
2255
2256
2257 type http2PingFrame struct {
2258 http2FrameHeader
2259 Data [8]byte
2260 }
2261
2262 func (f *http2PingFrame) IsAck() bool { return f.Flags.Has(http2FlagPingAck) }
2263
2264 func http2parsePingFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), payload []byte) (http2Frame, error) {
2265 if len(payload) != 8 {
2266 countError("frame_ping_length")
2267 return nil, http2ConnectionError(http2ErrCodeFrameSize)
2268 }
2269 if fh.StreamID != 0 {
2270 countError("frame_ping_has_stream")
2271 return nil, http2ConnectionError(http2ErrCodeProtocol)
2272 }
2273 f := &http2PingFrame{http2FrameHeader: fh}
2274 copy(f.Data[:], payload)
2275 return f, nil
2276 }
2277
2278 func (f *http2Framer) WritePing(ack bool, data [8]byte) error {
2279 var flags http2Flags
2280 if ack {
2281 flags = http2FlagPingAck
2282 }
2283 f.startWrite(http2FramePing, flags, 0)
2284 f.writeBytes(data[:])
2285 return f.endWrite()
2286 }
2287
2288
2289
2290 type http2GoAwayFrame struct {
2291 http2FrameHeader
2292 LastStreamID uint32
2293 ErrCode http2ErrCode
2294 debugData []byte
2295 }
2296
2297
2298
2299
2300
2301 func (f *http2GoAwayFrame) DebugData() []byte {
2302 f.checkValid()
2303 return f.debugData
2304 }
2305
2306 func http2parseGoAwayFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
2307 if fh.StreamID != 0 {
2308 countError("frame_goaway_has_stream")
2309 return nil, http2ConnectionError(http2ErrCodeProtocol)
2310 }
2311 if len(p) < 8 {
2312 countError("frame_goaway_short")
2313 return nil, http2ConnectionError(http2ErrCodeFrameSize)
2314 }
2315 return &http2GoAwayFrame{
2316 http2FrameHeader: fh,
2317 LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
2318 ErrCode: http2ErrCode(binary.BigEndian.Uint32(p[4:8])),
2319 debugData: p[8:],
2320 }, nil
2321 }
2322
2323 func (f *http2Framer) WriteGoAway(maxStreamID uint32, code http2ErrCode, debugData []byte) error {
2324 f.startWrite(http2FrameGoAway, 0, 0)
2325 f.writeUint32(maxStreamID & (1<<31 - 1))
2326 f.writeUint32(uint32(code))
2327 f.writeBytes(debugData)
2328 return f.endWrite()
2329 }
2330
2331
2332
2333 type http2UnknownFrame struct {
2334 http2FrameHeader
2335 p []byte
2336 }
2337
2338
2339
2340
2341
2342
2343 func (f *http2UnknownFrame) Payload() []byte {
2344 f.checkValid()
2345 return f.p
2346 }
2347
2348 func http2parseUnknownFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
2349 return &http2UnknownFrame{fh, p}, nil
2350 }
2351
2352
2353
2354 type http2WindowUpdateFrame struct {
2355 http2FrameHeader
2356 Increment uint32
2357 }
2358
2359 func http2parseWindowUpdateFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
2360 if len(p) != 4 {
2361 countError("frame_windowupdate_bad_len")
2362 return nil, http2ConnectionError(http2ErrCodeFrameSize)
2363 }
2364 inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff
2365 if inc == 0 {
2366
2367
2368
2369
2370
2371
2372 if fh.StreamID == 0 {
2373 countError("frame_windowupdate_zero_inc_conn")
2374 return nil, http2ConnectionError(http2ErrCodeProtocol)
2375 }
2376 countError("frame_windowupdate_zero_inc_stream")
2377 return nil, http2streamError(fh.StreamID, http2ErrCodeProtocol)
2378 }
2379 return &http2WindowUpdateFrame{
2380 http2FrameHeader: fh,
2381 Increment: inc,
2382 }, nil
2383 }
2384
2385
2386
2387
2388
2389 func (f *http2Framer) WriteWindowUpdate(streamID, incr uint32) error {
2390
2391 if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
2392 return errors.New("illegal window increment value")
2393 }
2394 f.startWrite(http2FrameWindowUpdate, 0, streamID)
2395 f.writeUint32(incr)
2396 return f.endWrite()
2397 }
2398
2399
2400
2401 type http2HeadersFrame struct {
2402 http2FrameHeader
2403
2404
2405 Priority http2PriorityParam
2406
2407 headerFragBuf []byte
2408 }
2409
2410 func (f *http2HeadersFrame) HeaderBlockFragment() []byte {
2411 f.checkValid()
2412 return f.headerFragBuf
2413 }
2414
2415 func (f *http2HeadersFrame) HeadersEnded() bool {
2416 return f.http2FrameHeader.Flags.Has(http2FlagHeadersEndHeaders)
2417 }
2418
2419 func (f *http2HeadersFrame) StreamEnded() bool {
2420 return f.http2FrameHeader.Flags.Has(http2FlagHeadersEndStream)
2421 }
2422
2423 func (f *http2HeadersFrame) HasPriority() bool {
2424 return f.http2FrameHeader.Flags.Has(http2FlagHeadersPriority)
2425 }
2426
2427 func http2parseHeadersFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (_ http2Frame, err error) {
2428 hf := &http2HeadersFrame{
2429 http2FrameHeader: fh,
2430 }
2431 if fh.StreamID == 0 {
2432
2433
2434
2435
2436 countError("frame_headers_zero_stream")
2437 return nil, http2connError{http2ErrCodeProtocol, "HEADERS frame with stream ID 0"}
2438 }
2439 var padLength uint8
2440 if fh.Flags.Has(http2FlagHeadersPadded) {
2441 if p, padLength, err = http2readByte(p); err != nil {
2442 countError("frame_headers_pad_short")
2443 return
2444 }
2445 }
2446 if fh.Flags.Has(http2FlagHeadersPriority) {
2447 var v uint32
2448 p, v, err = http2readUint32(p)
2449 if err != nil {
2450 countError("frame_headers_prio_short")
2451 return nil, err
2452 }
2453 hf.Priority.StreamDep = v & 0x7fffffff
2454 hf.Priority.Exclusive = (v != hf.Priority.StreamDep)
2455 p, hf.Priority.Weight, err = http2readByte(p)
2456 if err != nil {
2457 countError("frame_headers_prio_weight_short")
2458 return nil, err
2459 }
2460 }
2461 if len(p)-int(padLength) < 0 {
2462 countError("frame_headers_pad_too_big")
2463 return nil, http2streamError(fh.StreamID, http2ErrCodeProtocol)
2464 }
2465 hf.headerFragBuf = p[:len(p)-int(padLength)]
2466 return hf, nil
2467 }
2468
2469
2470 type http2HeadersFrameParam struct {
2471
2472 StreamID uint32
2473
2474 BlockFragment []byte
2475
2476
2477
2478
2479
2480 EndStream bool
2481
2482
2483
2484
2485 EndHeaders bool
2486
2487
2488
2489 PadLength uint8
2490
2491
2492
2493 Priority http2PriorityParam
2494 }
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504 func (f *http2Framer) WriteHeaders(p http2HeadersFrameParam) error {
2505 if !http2validStreamID(p.StreamID) && !f.AllowIllegalWrites {
2506 return http2errStreamID
2507 }
2508 var flags http2Flags
2509 if p.PadLength != 0 {
2510 flags |= http2FlagHeadersPadded
2511 }
2512 if p.EndStream {
2513 flags |= http2FlagHeadersEndStream
2514 }
2515 if p.EndHeaders {
2516 flags |= http2FlagHeadersEndHeaders
2517 }
2518 if !p.Priority.IsZero() {
2519 flags |= http2FlagHeadersPriority
2520 }
2521 f.startWrite(http2FrameHeaders, flags, p.StreamID)
2522 if p.PadLength != 0 {
2523 f.writeByte(p.PadLength)
2524 }
2525 if !p.Priority.IsZero() {
2526 v := p.Priority.StreamDep
2527 if !http2validStreamIDOrZero(v) && !f.AllowIllegalWrites {
2528 return http2errDepStreamID
2529 }
2530 if p.Priority.Exclusive {
2531 v |= 1 << 31
2532 }
2533 f.writeUint32(v)
2534 f.writeByte(p.Priority.Weight)
2535 }
2536 f.wbuf = append(f.wbuf, p.BlockFragment...)
2537 f.wbuf = append(f.wbuf, http2padZeros[:p.PadLength]...)
2538 return f.endWrite()
2539 }
2540
2541
2542
2543 type http2PriorityFrame struct {
2544 http2FrameHeader
2545 http2PriorityParam
2546 }
2547
2548
2549 type http2PriorityParam struct {
2550
2551
2552
2553 StreamDep uint32
2554
2555
2556 Exclusive bool
2557
2558
2559
2560
2561
2562 Weight uint8
2563 }
2564
2565 func (p http2PriorityParam) IsZero() bool {
2566 return p == http2PriorityParam{}
2567 }
2568
2569 func http2parsePriorityFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), payload []byte) (http2Frame, error) {
2570 if fh.StreamID == 0 {
2571 countError("frame_priority_zero_stream")
2572 return nil, http2connError{http2ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
2573 }
2574 if len(payload) != 5 {
2575 countError("frame_priority_bad_length")
2576 return nil, http2connError{http2ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))}
2577 }
2578 v := binary.BigEndian.Uint32(payload[:4])
2579 streamID := v & 0x7fffffff
2580 return &http2PriorityFrame{
2581 http2FrameHeader: fh,
2582 http2PriorityParam: http2PriorityParam{
2583 Weight: payload[4],
2584 StreamDep: streamID,
2585 Exclusive: streamID != v,
2586 },
2587 }, nil
2588 }
2589
2590
2591
2592
2593
2594 func (f *http2Framer) WritePriority(streamID uint32, p http2PriorityParam) error {
2595 if !http2validStreamID(streamID) && !f.AllowIllegalWrites {
2596 return http2errStreamID
2597 }
2598 if !http2validStreamIDOrZero(p.StreamDep) {
2599 return http2errDepStreamID
2600 }
2601 f.startWrite(http2FramePriority, 0, streamID)
2602 v := p.StreamDep
2603 if p.Exclusive {
2604 v |= 1 << 31
2605 }
2606 f.writeUint32(v)
2607 f.writeByte(p.Weight)
2608 return f.endWrite()
2609 }
2610
2611
2612
2613 type http2RSTStreamFrame struct {
2614 http2FrameHeader
2615 ErrCode http2ErrCode
2616 }
2617
2618 func http2parseRSTStreamFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
2619 if len(p) != 4 {
2620 countError("frame_rststream_bad_len")
2621 return nil, http2ConnectionError(http2ErrCodeFrameSize)
2622 }
2623 if fh.StreamID == 0 {
2624 countError("frame_rststream_zero_stream")
2625 return nil, http2ConnectionError(http2ErrCodeProtocol)
2626 }
2627 return &http2RSTStreamFrame{fh, http2ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
2628 }
2629
2630
2631
2632
2633
2634 func (f *http2Framer) WriteRSTStream(streamID uint32, code http2ErrCode) error {
2635 if !http2validStreamID(streamID) && !f.AllowIllegalWrites {
2636 return http2errStreamID
2637 }
2638 f.startWrite(http2FrameRSTStream, 0, streamID)
2639 f.writeUint32(uint32(code))
2640 return f.endWrite()
2641 }
2642
2643
2644
2645 type http2ContinuationFrame struct {
2646 http2FrameHeader
2647 headerFragBuf []byte
2648 }
2649
2650 func http2parseContinuationFrame(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (http2Frame, error) {
2651 if fh.StreamID == 0 {
2652 countError("frame_continuation_zero_stream")
2653 return nil, http2connError{http2ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
2654 }
2655 return &http2ContinuationFrame{fh, p}, nil
2656 }
2657
2658 func (f *http2ContinuationFrame) HeaderBlockFragment() []byte {
2659 f.checkValid()
2660 return f.headerFragBuf
2661 }
2662
2663 func (f *http2ContinuationFrame) HeadersEnded() bool {
2664 return f.http2FrameHeader.Flags.Has(http2FlagContinuationEndHeaders)
2665 }
2666
2667
2668
2669
2670
2671 func (f *http2Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
2672 if !http2validStreamID(streamID) && !f.AllowIllegalWrites {
2673 return http2errStreamID
2674 }
2675 var flags http2Flags
2676 if endHeaders {
2677 flags |= http2FlagContinuationEndHeaders
2678 }
2679 f.startWrite(http2FrameContinuation, flags, streamID)
2680 f.wbuf = append(f.wbuf, headerBlockFragment...)
2681 return f.endWrite()
2682 }
2683
2684
2685
2686 type http2PushPromiseFrame struct {
2687 http2FrameHeader
2688 PromiseID uint32
2689 headerFragBuf []byte
2690 }
2691
2692 func (f *http2PushPromiseFrame) HeaderBlockFragment() []byte {
2693 f.checkValid()
2694 return f.headerFragBuf
2695 }
2696
2697 func (f *http2PushPromiseFrame) HeadersEnded() bool {
2698 return f.http2FrameHeader.Flags.Has(http2FlagPushPromiseEndHeaders)
2699 }
2700
2701 func http2parsePushPromise(_ *http2frameCache, fh http2FrameHeader, countError func(string), p []byte) (_ http2Frame, err error) {
2702 pp := &http2PushPromiseFrame{
2703 http2FrameHeader: fh,
2704 }
2705 if pp.StreamID == 0 {
2706
2707
2708
2709
2710
2711
2712 countError("frame_pushpromise_zero_stream")
2713 return nil, http2ConnectionError(http2ErrCodeProtocol)
2714 }
2715
2716
2717 var padLength uint8
2718 if fh.Flags.Has(http2FlagPushPromisePadded) {
2719 if p, padLength, err = http2readByte(p); err != nil {
2720 countError("frame_pushpromise_pad_short")
2721 return
2722 }
2723 }
2724
2725 p, pp.PromiseID, err = http2readUint32(p)
2726 if err != nil {
2727 countError("frame_pushpromise_promiseid_short")
2728 return
2729 }
2730 pp.PromiseID = pp.PromiseID & (1<<31 - 1)
2731
2732 if int(padLength) > len(p) {
2733
2734 countError("frame_pushpromise_pad_too_big")
2735 return nil, http2ConnectionError(http2ErrCodeProtocol)
2736 }
2737 pp.headerFragBuf = p[:len(p)-int(padLength)]
2738 return pp, nil
2739 }
2740
2741
2742 type http2PushPromiseParam struct {
2743
2744 StreamID uint32
2745
2746
2747
2748 PromiseID uint32
2749
2750
2751 BlockFragment []byte
2752
2753
2754
2755
2756 EndHeaders bool
2757
2758
2759
2760 PadLength uint8
2761 }
2762
2763
2764
2765
2766
2767
2768
2769
2770 func (f *http2Framer) WritePushPromise(p http2PushPromiseParam) error {
2771 if !http2validStreamID(p.StreamID) && !f.AllowIllegalWrites {
2772 return http2errStreamID
2773 }
2774 var flags http2Flags
2775 if p.PadLength != 0 {
2776 flags |= http2FlagPushPromisePadded
2777 }
2778 if p.EndHeaders {
2779 flags |= http2FlagPushPromiseEndHeaders
2780 }
2781 f.startWrite(http2FramePushPromise, flags, p.StreamID)
2782 if p.PadLength != 0 {
2783 f.writeByte(p.PadLength)
2784 }
2785 if !http2validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
2786 return http2errStreamID
2787 }
2788 f.writeUint32(p.PromiseID)
2789 f.wbuf = append(f.wbuf, p.BlockFragment...)
2790 f.wbuf = append(f.wbuf, http2padZeros[:p.PadLength]...)
2791 return f.endWrite()
2792 }
2793
2794
2795
2796 func (f *http2Framer) WriteRawFrame(t http2FrameType, flags http2Flags, streamID uint32, payload []byte) error {
2797 f.startWrite(t, flags, streamID)
2798 f.writeBytes(payload)
2799 return f.endWrite()
2800 }
2801
2802 func http2readByte(p []byte) (remain []byte, b byte, err error) {
2803 if len(p) == 0 {
2804 return nil, 0, io.ErrUnexpectedEOF
2805 }
2806 return p[1:], p[0], nil
2807 }
2808
2809 func http2readUint32(p []byte) (remain []byte, v uint32, err error) {
2810 if len(p) < 4 {
2811 return nil, 0, io.ErrUnexpectedEOF
2812 }
2813 return p[4:], binary.BigEndian.Uint32(p[:4]), nil
2814 }
2815
2816 type http2streamEnder interface {
2817 StreamEnded() bool
2818 }
2819
2820 type http2headersEnder interface {
2821 HeadersEnded() bool
2822 }
2823
2824 type http2headersOrContinuation interface {
2825 http2headersEnder
2826 HeaderBlockFragment() []byte
2827 }
2828
2829
2830
2831
2832
2833
2834
2835 type http2MetaHeadersFrame struct {
2836 *http2HeadersFrame
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848 Fields []hpack.HeaderField
2849
2850
2851
2852
2853 Truncated bool
2854 }
2855
2856
2857
2858 func (mh *http2MetaHeadersFrame) PseudoValue(pseudo string) string {
2859 for _, hf := range mh.Fields {
2860 if !hf.IsPseudo() {
2861 return ""
2862 }
2863 if hf.Name[1:] == pseudo {
2864 return hf.Value
2865 }
2866 }
2867 return ""
2868 }
2869
2870
2871
2872 func (mh *http2MetaHeadersFrame) RegularFields() []hpack.HeaderField {
2873 for i, hf := range mh.Fields {
2874 if !hf.IsPseudo() {
2875 return mh.Fields[i:]
2876 }
2877 }
2878 return nil
2879 }
2880
2881
2882
2883 func (mh *http2MetaHeadersFrame) PseudoFields() []hpack.HeaderField {
2884 for i, hf := range mh.Fields {
2885 if !hf.IsPseudo() {
2886 return mh.Fields[:i]
2887 }
2888 }
2889 return mh.Fields
2890 }
2891
2892 func (mh *http2MetaHeadersFrame) checkPseudos() error {
2893 var isRequest, isResponse bool
2894 pf := mh.PseudoFields()
2895 for i, hf := range pf {
2896 switch hf.Name {
2897 case ":method", ":path", ":scheme", ":authority":
2898 isRequest = true
2899 case ":status":
2900 isResponse = true
2901 default:
2902 return http2pseudoHeaderError(hf.Name)
2903 }
2904
2905
2906
2907 for _, hf2 := range pf[:i] {
2908 if hf.Name == hf2.Name {
2909 return http2duplicatePseudoHeaderError(hf.Name)
2910 }
2911 }
2912 }
2913 if isRequest && isResponse {
2914 return http2errMixPseudoHeaderTypes
2915 }
2916 return nil
2917 }
2918
2919 func (fr *http2Framer) maxHeaderStringLen() int {
2920 v := fr.maxHeaderListSize()
2921 if uint32(int(v)) == v {
2922 return int(v)
2923 }
2924
2925
2926 return 0
2927 }
2928
2929
2930
2931
2932 func (fr *http2Framer) readMetaFrame(hf *http2HeadersFrame) (http2Frame, error) {
2933 if fr.AllowIllegalReads {
2934 return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
2935 }
2936 mh := &http2MetaHeadersFrame{
2937 http2HeadersFrame: hf,
2938 }
2939 var remainSize = fr.maxHeaderListSize()
2940 var sawRegular bool
2941
2942 var invalid error
2943 hdec := fr.ReadMetaHeaders
2944 hdec.SetEmitEnabled(true)
2945 hdec.SetMaxStringLength(fr.maxHeaderStringLen())
2946 hdec.SetEmitFunc(func(hf hpack.HeaderField) {
2947 if http2VerboseLogs && fr.logReads {
2948 fr.debugReadLoggerf("http2: decoded hpack field %+v", hf)
2949 }
2950 if !httpguts.ValidHeaderFieldValue(hf.Value) {
2951
2952 invalid = http2headerFieldValueError(hf.Name)
2953 }
2954 isPseudo := strings.HasPrefix(hf.Name, ":")
2955 if isPseudo {
2956 if sawRegular {
2957 invalid = http2errPseudoAfterRegular
2958 }
2959 } else {
2960 sawRegular = true
2961 if !http2validWireHeaderFieldName(hf.Name) {
2962 invalid = http2headerFieldNameError(hf.Name)
2963 }
2964 }
2965
2966 if invalid != nil {
2967 hdec.SetEmitEnabled(false)
2968 return
2969 }
2970
2971 size := hf.Size()
2972 if size > remainSize {
2973 hdec.SetEmitEnabled(false)
2974 mh.Truncated = true
2975 remainSize = 0
2976 return
2977 }
2978 remainSize -= size
2979
2980 mh.Fields = append(mh.Fields, hf)
2981 })
2982
2983 defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})
2984
2985 var hc http2headersOrContinuation = hf
2986 for {
2987 frag := hc.HeaderBlockFragment()
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997 if int64(len(frag)) > int64(2*remainSize) {
2998 if http2VerboseLogs {
2999 log.Printf("http2: header list too large")
3000 }
3001
3002
3003 return mh, http2ConnectionError(http2ErrCodeProtocol)
3004 }
3005
3006
3007
3008
3009 if invalid != nil {
3010 if http2VerboseLogs {
3011 log.Printf("http2: invalid header: %v", invalid)
3012 }
3013
3014
3015 return mh, http2ConnectionError(http2ErrCodeProtocol)
3016 }
3017
3018 if _, err := hdec.Write(frag); err != nil {
3019 return mh, http2ConnectionError(http2ErrCodeCompression)
3020 }
3021
3022 if hc.HeadersEnded() {
3023 break
3024 }
3025 if f, err := fr.ReadFrame(); err != nil {
3026 return nil, err
3027 } else {
3028 hc = f.(*http2ContinuationFrame)
3029 }
3030 }
3031
3032 mh.http2HeadersFrame.headerFragBuf = nil
3033 mh.http2HeadersFrame.invalidate()
3034
3035 if err := hdec.Close(); err != nil {
3036 return mh, http2ConnectionError(http2ErrCodeCompression)
3037 }
3038 if invalid != nil {
3039 fr.errDetail = invalid
3040 if http2VerboseLogs {
3041 log.Printf("http2: invalid header: %v", invalid)
3042 }
3043 return nil, http2StreamError{mh.StreamID, http2ErrCodeProtocol, invalid}
3044 }
3045 if err := mh.checkPseudos(); err != nil {
3046 fr.errDetail = err
3047 if http2VerboseLogs {
3048 log.Printf("http2: invalid pseudo headers: %v", err)
3049 }
3050 return nil, http2StreamError{mh.StreamID, http2ErrCodeProtocol, err}
3051 }
3052 return mh, nil
3053 }
3054
3055 func http2summarizeFrame(f http2Frame) string {
3056 var buf bytes.Buffer
3057 f.Header().writeDebug(&buf)
3058 switch f := f.(type) {
3059 case *http2SettingsFrame:
3060 n := 0
3061 f.ForeachSetting(func(s http2Setting) error {
3062 n++
3063 if n == 1 {
3064 buf.WriteString(", settings:")
3065 }
3066 fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val)
3067 return nil
3068 })
3069 if n > 0 {
3070 buf.Truncate(buf.Len() - 1)
3071 }
3072 case *http2DataFrame:
3073 data := f.Data()
3074 const max = 256
3075 if len(data) > max {
3076 data = data[:max]
3077 }
3078 fmt.Fprintf(&buf, " data=%q", data)
3079 if len(f.Data()) > max {
3080 fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max)
3081 }
3082 case *http2WindowUpdateFrame:
3083 if f.StreamID == 0 {
3084 buf.WriteString(" (conn)")
3085 }
3086 fmt.Fprintf(&buf, " incr=%v", f.Increment)
3087 case *http2PingFrame:
3088 fmt.Fprintf(&buf, " ping=%q", f.Data[:])
3089 case *http2GoAwayFrame:
3090 fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q",
3091 f.LastStreamID, f.ErrCode, f.debugData)
3092 case *http2RSTStreamFrame:
3093 fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode)
3094 }
3095 return buf.String()
3096 }
3097
3098 var http2DebugGoroutines = os.Getenv("DEBUG_HTTP2_GOROUTINES") == "1"
3099
3100 type http2goroutineLock uint64
3101
3102 func http2newGoroutineLock() http2goroutineLock {
3103 if !http2DebugGoroutines {
3104 return 0
3105 }
3106 return http2goroutineLock(http2curGoroutineID())
3107 }
3108
3109 func (g http2goroutineLock) check() {
3110 if !http2DebugGoroutines {
3111 return
3112 }
3113 if http2curGoroutineID() != uint64(g) {
3114 panic("running on the wrong goroutine")
3115 }
3116 }
3117
3118 func (g http2goroutineLock) checkNotOn() {
3119 if !http2DebugGoroutines {
3120 return
3121 }
3122 if http2curGoroutineID() == uint64(g) {
3123 panic("running on the wrong goroutine")
3124 }
3125 }
3126
3127 var http2goroutineSpace = []byte("goroutine ")
3128
3129 func http2curGoroutineID() uint64 {
3130 bp := http2littleBuf.Get().(*[]byte)
3131 defer http2littleBuf.Put(bp)
3132 b := *bp
3133 b = b[:runtime.Stack(b, false)]
3134
3135 b = bytes.TrimPrefix(b, http2goroutineSpace)
3136 i := bytes.IndexByte(b, ' ')
3137 if i < 0 {
3138 panic(fmt.Sprintf("No space found in %q", b))
3139 }
3140 b = b[:i]
3141 n, err := http2parseUintBytes(b, 10, 64)
3142 if err != nil {
3143 panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err))
3144 }
3145 return n
3146 }
3147
3148 var http2littleBuf = sync.Pool{
3149 New: func() interface{} {
3150 buf := make([]byte, 64)
3151 return &buf
3152 },
3153 }
3154
3155
3156 func http2parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) {
3157 var cutoff, maxVal uint64
3158
3159 if bitSize == 0 {
3160 bitSize = int(strconv.IntSize)
3161 }
3162
3163 s0 := s
3164 switch {
3165 case len(s) < 1:
3166 err = strconv.ErrSyntax
3167 goto Error
3168
3169 case 2 <= base && base <= 36:
3170
3171
3172 case base == 0:
3173
3174 switch {
3175 case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'):
3176 base = 16
3177 s = s[2:]
3178 if len(s) < 1 {
3179 err = strconv.ErrSyntax
3180 goto Error
3181 }
3182 case s[0] == '0':
3183 base = 8
3184 default:
3185 base = 10
3186 }
3187
3188 default:
3189 err = errors.New("invalid base " + strconv.Itoa(base))
3190 goto Error
3191 }
3192
3193 n = 0
3194 cutoff = http2cutoff64(base)
3195 maxVal = 1<<uint(bitSize) - 1
3196
3197 for i := 0; i < len(s); i++ {
3198 var v byte
3199 d := s[i]
3200 switch {
3201 case '0' <= d && d <= '9':
3202 v = d - '0'
3203 case 'a' <= d && d <= 'z':
3204 v = d - 'a' + 10
3205 case 'A' <= d && d <= 'Z':
3206 v = d - 'A' + 10
3207 default:
3208 n = 0
3209 err = strconv.ErrSyntax
3210 goto Error
3211 }
3212 if int(v) >= base {
3213 n = 0
3214 err = strconv.ErrSyntax
3215 goto Error
3216 }
3217
3218 if n >= cutoff {
3219
3220 n = 1<<64 - 1
3221 err = strconv.ErrRange
3222 goto Error
3223 }
3224 n *= uint64(base)
3225
3226 n1 := n + uint64(v)
3227 if n1 < n || n1 > maxVal {
3228
3229 n = 1<<64 - 1
3230 err = strconv.ErrRange
3231 goto Error
3232 }
3233 n = n1
3234 }
3235
3236 return n, nil
3237
3238 Error:
3239 return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err}
3240 }
3241
3242
3243 func http2cutoff64(base int) uint64 {
3244 if base < 2 {
3245 return 0
3246 }
3247 return (1<<64-1)/uint64(base) + 1
3248 }
3249
3250 var (
3251 http2commonBuildOnce sync.Once
3252 http2commonLowerHeader map[string]string
3253 http2commonCanonHeader map[string]string
3254 )
3255
3256 func http2buildCommonHeaderMapsOnce() {
3257 http2commonBuildOnce.Do(http2buildCommonHeaderMaps)
3258 }
3259
3260 func http2buildCommonHeaderMaps() {
3261 common := []string{
3262 "accept",
3263 "accept-charset",
3264 "accept-encoding",
3265 "accept-language",
3266 "accept-ranges",
3267 "age",
3268 "access-control-allow-credentials",
3269 "access-control-allow-headers",
3270 "access-control-allow-methods",
3271 "access-control-allow-origin",
3272 "access-control-expose-headers",
3273 "access-control-max-age",
3274 "access-control-request-headers",
3275 "access-control-request-method",
3276 "allow",
3277 "authorization",
3278 "cache-control",
3279 "content-disposition",
3280 "content-encoding",
3281 "content-language",
3282 "content-length",
3283 "content-location",
3284 "content-range",
3285 "content-type",
3286 "cookie",
3287 "date",
3288 "etag",
3289 "expect",
3290 "expires",
3291 "from",
3292 "host",
3293 "if-match",
3294 "if-modified-since",
3295 "if-none-match",
3296 "if-unmodified-since",
3297 "last-modified",
3298 "link",
3299 "location",
3300 "max-forwards",
3301 "origin",
3302 "proxy-authenticate",
3303 "proxy-authorization",
3304 "range",
3305 "referer",
3306 "refresh",
3307 "retry-after",
3308 "server",
3309 "set-cookie",
3310 "strict-transport-security",
3311 "trailer",
3312 "transfer-encoding",
3313 "user-agent",
3314 "vary",
3315 "via",
3316 "www-authenticate",
3317 "x-forwarded-for",
3318 "x-forwarded-proto",
3319 }
3320 http2commonLowerHeader = make(map[string]string, len(common))
3321 http2commonCanonHeader = make(map[string]string, len(common))
3322 for _, v := range common {
3323 chk := CanonicalHeaderKey(v)
3324 http2commonLowerHeader[chk] = v
3325 http2commonCanonHeader[v] = chk
3326 }
3327 }
3328
3329 func http2lowerHeader(v string) (lower string, ascii bool) {
3330 http2buildCommonHeaderMapsOnce()
3331 if s, ok := http2commonLowerHeader[v]; ok {
3332 return s, true
3333 }
3334 return http2asciiToLower(v)
3335 }
3336
3337 func http2canonicalHeader(v string) string {
3338 http2buildCommonHeaderMapsOnce()
3339 if s, ok := http2commonCanonHeader[v]; ok {
3340 return s
3341 }
3342 return CanonicalHeaderKey(v)
3343 }
3344
3345 var (
3346 http2VerboseLogs bool
3347 http2logFrameWrites bool
3348 http2logFrameReads bool
3349 http2inTests bool
3350 )
3351
3352 func init() {
3353 e := os.Getenv("GODEBUG")
3354 if strings.Contains(e, "http2debug=1") {
3355 http2VerboseLogs = true
3356 }
3357 if strings.Contains(e, "http2debug=2") {
3358 http2VerboseLogs = true
3359 http2logFrameWrites = true
3360 http2logFrameReads = true
3361 }
3362 }
3363
3364 const (
3365
3366
3367 http2ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
3368
3369
3370
3371 http2initialMaxFrameSize = 16384
3372
3373
3374
3375 http2NextProtoTLS = "h2"
3376
3377
3378 http2initialHeaderTableSize = 4096
3379
3380 http2initialWindowSize = 65535
3381
3382 http2defaultMaxReadFrameSize = 1 << 20
3383 )
3384
3385 var (
3386 http2clientPreface = []byte(http2ClientPreface)
3387 )
3388
3389 type http2streamState int
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403 const (
3404 http2stateIdle http2streamState = iota
3405 http2stateOpen
3406 http2stateHalfClosedLocal
3407 http2stateHalfClosedRemote
3408 http2stateClosed
3409 )
3410
3411 var http2stateName = [...]string{
3412 http2stateIdle: "Idle",
3413 http2stateOpen: "Open",
3414 http2stateHalfClosedLocal: "HalfClosedLocal",
3415 http2stateHalfClosedRemote: "HalfClosedRemote",
3416 http2stateClosed: "Closed",
3417 }
3418
3419 func (st http2streamState) String() string {
3420 return http2stateName[st]
3421 }
3422
3423
3424 type http2Setting struct {
3425
3426
3427 ID http2SettingID
3428
3429
3430 Val uint32
3431 }
3432
3433 func (s http2Setting) String() string {
3434 return fmt.Sprintf("[%v = %d]", s.ID, s.Val)
3435 }
3436
3437
3438 func (s http2Setting) Valid() error {
3439
3440 switch s.ID {
3441 case http2SettingEnablePush:
3442 if s.Val != 1 && s.Val != 0 {
3443 return http2ConnectionError(http2ErrCodeProtocol)
3444 }
3445 case http2SettingInitialWindowSize:
3446 if s.Val > 1<<31-1 {
3447 return http2ConnectionError(http2ErrCodeFlowControl)
3448 }
3449 case http2SettingMaxFrameSize:
3450 if s.Val < 16384 || s.Val > 1<<24-1 {
3451 return http2ConnectionError(http2ErrCodeProtocol)
3452 }
3453 }
3454 return nil
3455 }
3456
3457
3458
3459 type http2SettingID uint16
3460
3461 const (
3462 http2SettingHeaderTableSize http2SettingID = 0x1
3463 http2SettingEnablePush http2SettingID = 0x2
3464 http2SettingMaxConcurrentStreams http2SettingID = 0x3
3465 http2SettingInitialWindowSize http2SettingID = 0x4
3466 http2SettingMaxFrameSize http2SettingID = 0x5
3467 http2SettingMaxHeaderListSize http2SettingID = 0x6
3468 )
3469
3470 var http2settingName = map[http2SettingID]string{
3471 http2SettingHeaderTableSize: "HEADER_TABLE_SIZE",
3472 http2SettingEnablePush: "ENABLE_PUSH",
3473 http2SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
3474 http2SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
3475 http2SettingMaxFrameSize: "MAX_FRAME_SIZE",
3476 http2SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
3477 }
3478
3479 func (s http2SettingID) String() string {
3480 if v, ok := http2settingName[s]; ok {
3481 return v
3482 }
3483 return fmt.Sprintf("UNKNOWN_SETTING_%d", uint16(s))
3484 }
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495 func http2validWireHeaderFieldName(v string) bool {
3496 if len(v) == 0 {
3497 return false
3498 }
3499 for _, r := range v {
3500 if !httpguts.IsTokenRune(r) {
3501 return false
3502 }
3503 if 'A' <= r && r <= 'Z' {
3504 return false
3505 }
3506 }
3507 return true
3508 }
3509
3510 func http2httpCodeString(code int) string {
3511 switch code {
3512 case 200:
3513 return "200"
3514 case 404:
3515 return "404"
3516 }
3517 return strconv.Itoa(code)
3518 }
3519
3520
3521 type http2stringWriter interface {
3522 WriteString(s string) (n int, err error)
3523 }
3524
3525
3526 type http2gate chan struct{}
3527
3528 func (g http2gate) Done() { g <- struct{}{} }
3529
3530 func (g http2gate) Wait() { <-g }
3531
3532
3533 type http2closeWaiter chan struct{}
3534
3535
3536
3537
3538
3539 func (cw *http2closeWaiter) Init() {
3540 *cw = make(chan struct{})
3541 }
3542
3543
3544 func (cw http2closeWaiter) Close() {
3545 close(cw)
3546 }
3547
3548
3549 func (cw http2closeWaiter) Wait() {
3550 <-cw
3551 }
3552
3553
3554
3555
3556 type http2bufferedWriter struct {
3557 _ http2incomparable
3558 w io.Writer
3559 bw *bufio.Writer
3560 }
3561
3562 func http2newBufferedWriter(w io.Writer) *http2bufferedWriter {
3563 return &http2bufferedWriter{w: w}
3564 }
3565
3566
3567
3568
3569
3570
3571
3572 const http2bufWriterPoolBufferSize = 4 << 10
3573
3574 var http2bufWriterPool = sync.Pool{
3575 New: func() interface{} {
3576 return bufio.NewWriterSize(nil, http2bufWriterPoolBufferSize)
3577 },
3578 }
3579
3580 func (w *http2bufferedWriter) Available() int {
3581 if w.bw == nil {
3582 return http2bufWriterPoolBufferSize
3583 }
3584 return w.bw.Available()
3585 }
3586
3587 func (w *http2bufferedWriter) Write(p []byte) (n int, err error) {
3588 if w.bw == nil {
3589 bw := http2bufWriterPool.Get().(*bufio.Writer)
3590 bw.Reset(w.w)
3591 w.bw = bw
3592 }
3593 return w.bw.Write(p)
3594 }
3595
3596 func (w *http2bufferedWriter) Flush() error {
3597 bw := w.bw
3598 if bw == nil {
3599 return nil
3600 }
3601 err := bw.Flush()
3602 bw.Reset(nil)
3603 http2bufWriterPool.Put(bw)
3604 w.bw = nil
3605 return err
3606 }
3607
3608 func http2mustUint31(v int32) uint32 {
3609 if v < 0 || v > 2147483647 {
3610 panic("out of range")
3611 }
3612 return uint32(v)
3613 }
3614
3615
3616
3617 func http2bodyAllowedForStatus(status int) bool {
3618 switch {
3619 case status >= 100 && status <= 199:
3620 return false
3621 case status == 204:
3622 return false
3623 case status == 304:
3624 return false
3625 }
3626 return true
3627 }
3628
3629 type http2httpError struct {
3630 _ http2incomparable
3631 msg string
3632 timeout bool
3633 }
3634
3635 func (e *http2httpError) Error() string { return e.msg }
3636
3637 func (e *http2httpError) Timeout() bool { return e.timeout }
3638
3639 func (e *http2httpError) Temporary() bool { return true }
3640
3641 var http2errTimeout error = &http2httpError{msg: "http2: timeout awaiting response headers", timeout: true}
3642
3643 type http2connectionStater interface {
3644 ConnectionState() tls.ConnectionState
3645 }
3646
3647 var http2sorterPool = sync.Pool{New: func() interface{} { return new(http2sorter) }}
3648
3649 type http2sorter struct {
3650 v []string
3651 }
3652
3653 func (s *http2sorter) Len() int { return len(s.v) }
3654
3655 func (s *http2sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
3656
3657 func (s *http2sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
3658
3659
3660
3661
3662
3663 func (s *http2sorter) Keys(h Header) []string {
3664 keys := s.v[:0]
3665 for k := range h {
3666 keys = append(keys, k)
3667 }
3668 s.v = keys
3669 sort.Sort(s)
3670 return keys
3671 }
3672
3673 func (s *http2sorter) SortStrings(ss []string) {
3674
3675
3676 save := s.v
3677 s.v = ss
3678 sort.Sort(s)
3679 s.v = save
3680 }
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695 func http2validPseudoPath(v string) bool {
3696 return (len(v) > 0 && v[0] == '/') || v == "*"
3697 }
3698
3699
3700
3701
3702 type http2incomparable [0]func()
3703
3704
3705
3706
3707 type http2pipe struct {
3708 mu sync.Mutex
3709 c sync.Cond
3710 b http2pipeBuffer
3711 unread int
3712 err error
3713 breakErr error
3714 donec chan struct{}
3715 readFn func()
3716 }
3717
3718 type http2pipeBuffer interface {
3719 Len() int
3720 io.Writer
3721 io.Reader
3722 }
3723
3724
3725
3726 func (p *http2pipe) setBuffer(b http2pipeBuffer) {
3727 p.mu.Lock()
3728 defer p.mu.Unlock()
3729 if p.err != nil || p.breakErr != nil {
3730 return
3731 }
3732 p.b = b
3733 }
3734
3735 func (p *http2pipe) Len() int {
3736 p.mu.Lock()
3737 defer p.mu.Unlock()
3738 if p.b == nil {
3739 return p.unread
3740 }
3741 return p.b.Len()
3742 }
3743
3744
3745
3746 func (p *http2pipe) Read(d []byte) (n int, err error) {
3747 p.mu.Lock()
3748 defer p.mu.Unlock()
3749 if p.c.L == nil {
3750 p.c.L = &p.mu
3751 }
3752 for {
3753 if p.breakErr != nil {
3754 return 0, p.breakErr
3755 }
3756 if p.b != nil && p.b.Len() > 0 {
3757 return p.b.Read(d)
3758 }
3759 if p.err != nil {
3760 if p.readFn != nil {
3761 p.readFn()
3762 p.readFn = nil
3763 }
3764 p.b = nil
3765 return 0, p.err
3766 }
3767 p.c.Wait()
3768 }
3769 }
3770
3771 var http2errClosedPipeWrite = errors.New("write on closed buffer")
3772
3773
3774
3775 func (p *http2pipe) Write(d []byte) (n int, err error) {
3776 p.mu.Lock()
3777 defer p.mu.Unlock()
3778 if p.c.L == nil {
3779 p.c.L = &p.mu
3780 }
3781 defer p.c.Signal()
3782 if p.err != nil || p.breakErr != nil {
3783 return 0, http2errClosedPipeWrite
3784 }
3785 return p.b.Write(d)
3786 }
3787
3788
3789
3790
3791
3792
3793 func (p *http2pipe) CloseWithError(err error) { p.closeWithError(&p.err, err, nil) }
3794
3795
3796
3797
3798 func (p *http2pipe) BreakWithError(err error) { p.closeWithError(&p.breakErr, err, nil) }
3799
3800
3801
3802 func (p *http2pipe) closeWithErrorAndCode(err error, fn func()) { p.closeWithError(&p.err, err, fn) }
3803
3804 func (p *http2pipe) closeWithError(dst *error, err error, fn func()) {
3805 if err == nil {
3806 panic("err must be non-nil")
3807 }
3808 p.mu.Lock()
3809 defer p.mu.Unlock()
3810 if p.c.L == nil {
3811 p.c.L = &p.mu
3812 }
3813 defer p.c.Signal()
3814 if *dst != nil {
3815
3816 return
3817 }
3818 p.readFn = fn
3819 if dst == &p.breakErr {
3820 if p.b != nil {
3821 p.unread += p.b.Len()
3822 }
3823 p.b = nil
3824 }
3825 *dst = err
3826 p.closeDoneLocked()
3827 }
3828
3829
3830 func (p *http2pipe) closeDoneLocked() {
3831 if p.donec == nil {
3832 return
3833 }
3834
3835
3836 select {
3837 case <-p.donec:
3838 default:
3839 close(p.donec)
3840 }
3841 }
3842
3843
3844 func (p *http2pipe) Err() error {
3845 p.mu.Lock()
3846 defer p.mu.Unlock()
3847 if p.breakErr != nil {
3848 return p.breakErr
3849 }
3850 return p.err
3851 }
3852
3853
3854
3855 func (p *http2pipe) Done() <-chan struct{} {
3856 p.mu.Lock()
3857 defer p.mu.Unlock()
3858 if p.donec == nil {
3859 p.donec = make(chan struct{})
3860 if p.err != nil || p.breakErr != nil {
3861
3862 p.closeDoneLocked()
3863 }
3864 }
3865 return p.donec
3866 }
3867
3868 const (
3869 http2prefaceTimeout = 10 * time.Second
3870 http2firstSettingsTimeout = 2 * time.Second
3871 http2handlerChunkWriteSize = 4 << 10
3872 http2defaultMaxStreams = 250
3873 http2maxQueuedControlFrames = 10000
3874 )
3875
3876 var (
3877 http2errClientDisconnected = errors.New("client disconnected")
3878 http2errClosedBody = errors.New("body closed by handler")
3879 http2errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
3880 http2errStreamClosed = errors.New("http2: stream closed")
3881 )
3882
3883 var http2responseWriterStatePool = sync.Pool{
3884 New: func() interface{} {
3885 rws := &http2responseWriterState{}
3886 rws.bw = bufio.NewWriterSize(http2chunkWriter{rws}, http2handlerChunkWriteSize)
3887 return rws
3888 },
3889 }
3890
3891
3892 var (
3893 http2testHookOnConn func()
3894 http2testHookGetServerConn func(*http2serverConn)
3895 http2testHookOnPanicMu *sync.Mutex
3896 http2testHookOnPanic func(sc *http2serverConn, panicVal interface{}) (rePanic bool)
3897 )
3898
3899
3900 type http2Server struct {
3901
3902
3903
3904
3905 MaxHandlers int
3906
3907
3908
3909
3910
3911
3912
3913 MaxConcurrentStreams uint32
3914
3915
3916
3917
3918
3919
3920 MaxDecoderHeaderTableSize uint32
3921
3922
3923
3924
3925
3926 MaxEncoderHeaderTableSize uint32
3927
3928
3929
3930
3931
3932 MaxReadFrameSize uint32
3933
3934
3935
3936 PermitProhibitedCipherSuites bool
3937
3938
3939
3940
3941 IdleTimeout time.Duration
3942
3943
3944
3945
3946
3947
3948 MaxUploadBufferPerConnection int32
3949
3950
3951
3952
3953
3954 MaxUploadBufferPerStream int32
3955
3956
3957
3958 NewWriteScheduler func() http2WriteScheduler
3959
3960
3961
3962
3963
3964 CountError func(errType string)
3965
3966
3967
3968
3969 state *http2serverInternalState
3970 }
3971
3972 func (s *http2Server) initialConnRecvWindowSize() int32 {
3973 if s.MaxUploadBufferPerConnection >= http2initialWindowSize {
3974 return s.MaxUploadBufferPerConnection
3975 }
3976 return 1 << 20
3977 }
3978
3979 func (s *http2Server) initialStreamRecvWindowSize() int32 {
3980 if s.MaxUploadBufferPerStream > 0 {
3981 return s.MaxUploadBufferPerStream
3982 }
3983 return 1 << 20
3984 }
3985
3986 func (s *http2Server) maxReadFrameSize() uint32 {
3987 if v := s.MaxReadFrameSize; v >= http2minMaxFrameSize && v <= http2maxFrameSize {
3988 return v
3989 }
3990 return http2defaultMaxReadFrameSize
3991 }
3992
3993 func (s *http2Server) maxConcurrentStreams() uint32 {
3994 if v := s.MaxConcurrentStreams; v > 0 {
3995 return v
3996 }
3997 return http2defaultMaxStreams
3998 }
3999
4000 func (s *http2Server) maxDecoderHeaderTableSize() uint32 {
4001 if v := s.MaxDecoderHeaderTableSize; v > 0 {
4002 return v
4003 }
4004 return http2initialHeaderTableSize
4005 }
4006
4007 func (s *http2Server) maxEncoderHeaderTableSize() uint32 {
4008 if v := s.MaxEncoderHeaderTableSize; v > 0 {
4009 return v
4010 }
4011 return http2initialHeaderTableSize
4012 }
4013
4014
4015
4016
4017 func (s *http2Server) maxQueuedControlFrames() int {
4018
4019
4020 return http2maxQueuedControlFrames
4021 }
4022
4023 type http2serverInternalState struct {
4024 mu sync.Mutex
4025 activeConns map[*http2serverConn]struct{}
4026 }
4027
4028 func (s *http2serverInternalState) registerConn(sc *http2serverConn) {
4029 if s == nil {
4030 return
4031 }
4032 s.mu.Lock()
4033 s.activeConns[sc] = struct{}{}
4034 s.mu.Unlock()
4035 }
4036
4037 func (s *http2serverInternalState) unregisterConn(sc *http2serverConn) {
4038 if s == nil {
4039 return
4040 }
4041 s.mu.Lock()
4042 delete(s.activeConns, sc)
4043 s.mu.Unlock()
4044 }
4045
4046 func (s *http2serverInternalState) startGracefulShutdown() {
4047 if s == nil {
4048 return
4049 }
4050 s.mu.Lock()
4051 for sc := range s.activeConns {
4052 sc.startGracefulShutdown()
4053 }
4054 s.mu.Unlock()
4055 }
4056
4057
4058
4059
4060
4061
4062 func http2ConfigureServer(s *Server, conf *http2Server) error {
4063 if s == nil {
4064 panic("nil *http.Server")
4065 }
4066 if conf == nil {
4067 conf = new(http2Server)
4068 }
4069 conf.state = &http2serverInternalState{activeConns: make(map[*http2serverConn]struct{})}
4070 if h1, h2 := s, conf; h2.IdleTimeout == 0 {
4071 if h1.IdleTimeout != 0 {
4072 h2.IdleTimeout = h1.IdleTimeout
4073 } else {
4074 h2.IdleTimeout = h1.ReadTimeout
4075 }
4076 }
4077 s.RegisterOnShutdown(conf.state.startGracefulShutdown)
4078
4079 if s.TLSConfig == nil {
4080 s.TLSConfig = new(tls.Config)
4081 } else if s.TLSConfig.CipherSuites != nil && s.TLSConfig.MinVersion < tls.VersionTLS13 {
4082
4083
4084
4085 haveRequired := false
4086 for _, cs := range s.TLSConfig.CipherSuites {
4087 switch cs {
4088 case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
4089
4090
4091 tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
4092 haveRequired = true
4093 }
4094 }
4095 if !haveRequired {
4096 return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher (need at least one of TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 or TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256)")
4097 }
4098 }
4099
4100
4101
4102
4103
4104
4105
4106
4107 s.TLSConfig.PreferServerCipherSuites = true
4108
4109 if !http2strSliceContains(s.TLSConfig.NextProtos, http2NextProtoTLS) {
4110 s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, http2NextProtoTLS)
4111 }
4112 if !http2strSliceContains(s.TLSConfig.NextProtos, "http/1.1") {
4113 s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "http/1.1")
4114 }
4115
4116 if s.TLSNextProto == nil {
4117 s.TLSNextProto = map[string]func(*Server, *tls.Conn, Handler){}
4118 }
4119 protoHandler := func(hs *Server, c *tls.Conn, h Handler) {
4120 if http2testHookOnConn != nil {
4121 http2testHookOnConn()
4122 }
4123
4124
4125
4126
4127
4128 var ctx context.Context
4129 type baseContexter interface {
4130 BaseContext() context.Context
4131 }
4132 if bc, ok := h.(baseContexter); ok {
4133 ctx = bc.BaseContext()
4134 }
4135 conf.ServeConn(c, &http2ServeConnOpts{
4136 Context: ctx,
4137 Handler: h,
4138 BaseConfig: hs,
4139 })
4140 }
4141 s.TLSNextProto[http2NextProtoTLS] = protoHandler
4142 return nil
4143 }
4144
4145
4146 type http2ServeConnOpts struct {
4147
4148
4149 Context context.Context
4150
4151
4152
4153 BaseConfig *Server
4154
4155
4156
4157
4158 Handler Handler
4159
4160
4161
4162
4163
4164 UpgradeRequest *Request
4165
4166
4167
4168 Settings []byte
4169
4170
4171
4172 SawClientPreface bool
4173 }
4174
4175 func (o *http2ServeConnOpts) context() context.Context {
4176 if o != nil && o.Context != nil {
4177 return o.Context
4178 }
4179 return context.Background()
4180 }
4181
4182 func (o *http2ServeConnOpts) baseConfig() *Server {
4183 if o != nil && o.BaseConfig != nil {
4184 return o.BaseConfig
4185 }
4186 return new(Server)
4187 }
4188
4189 func (o *http2ServeConnOpts) handler() Handler {
4190 if o != nil {
4191 if o.Handler != nil {
4192 return o.Handler
4193 }
4194 if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
4195 return o.BaseConfig.Handler
4196 }
4197 }
4198 return DefaultServeMux
4199 }
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215 func (s *http2Server) ServeConn(c net.Conn, opts *http2ServeConnOpts) {
4216 baseCtx, cancel := http2serverConnBaseContext(c, opts)
4217 defer cancel()
4218
4219 sc := &http2serverConn{
4220 srv: s,
4221 hs: opts.baseConfig(),
4222 conn: c,
4223 baseCtx: baseCtx,
4224 remoteAddrStr: c.RemoteAddr().String(),
4225 bw: http2newBufferedWriter(c),
4226 handler: opts.handler(),
4227 streams: make(map[uint32]*http2stream),
4228 readFrameCh: make(chan http2readFrameResult),
4229 wantWriteFrameCh: make(chan http2FrameWriteRequest, 8),
4230 serveMsgCh: make(chan interface{}, 8),
4231 wroteFrameCh: make(chan http2frameWriteResult, 1),
4232 bodyReadCh: make(chan http2bodyReadMsg),
4233 doneServing: make(chan struct{}),
4234 clientMaxStreams: math.MaxUint32,
4235 advMaxStreams: s.maxConcurrentStreams(),
4236 initialStreamSendWindowSize: http2initialWindowSize,
4237 maxFrameSize: http2initialMaxFrameSize,
4238 serveG: http2newGoroutineLock(),
4239 pushEnabled: true,
4240 sawClientPreface: opts.SawClientPreface,
4241 }
4242
4243 s.state.registerConn(sc)
4244 defer s.state.unregisterConn(sc)
4245
4246
4247
4248
4249
4250
4251 if sc.hs.WriteTimeout != 0 {
4252 sc.conn.SetWriteDeadline(time.Time{})
4253 }
4254
4255 if s.NewWriteScheduler != nil {
4256 sc.writeSched = s.NewWriteScheduler()
4257 } else {
4258 sc.writeSched = http2newRoundRobinWriteScheduler()
4259 }
4260
4261
4262
4263
4264 sc.flow.add(http2initialWindowSize)
4265 sc.inflow.init(http2initialWindowSize)
4266 sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
4267 sc.hpackEncoder.SetMaxDynamicTableSizeLimit(s.maxEncoderHeaderTableSize())
4268
4269 fr := http2NewFramer(sc.bw, c)
4270 if s.CountError != nil {
4271 fr.countError = s.CountError
4272 }
4273 fr.ReadMetaHeaders = hpack.NewDecoder(s.maxDecoderHeaderTableSize(), nil)
4274 fr.MaxHeaderListSize = sc.maxHeaderListSize()
4275 fr.SetMaxReadFrameSize(s.maxReadFrameSize())
4276 sc.framer = fr
4277
4278 if tc, ok := c.(http2connectionStater); ok {
4279 sc.tlsState = new(tls.ConnectionState)
4280 *sc.tlsState = tc.ConnectionState()
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291 if sc.tlsState.Version < tls.VersionTLS12 {
4292 sc.rejectConn(http2ErrCodeInadequateSecurity, "TLS version too low")
4293 return
4294 }
4295
4296 if sc.tlsState.ServerName == "" {
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306 }
4307
4308 if !s.PermitProhibitedCipherSuites && http2isBadCipher(sc.tlsState.CipherSuite) {
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319 sc.rejectConn(http2ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
4320 return
4321 }
4322 }
4323
4324 if opts.Settings != nil {
4325 fr := &http2SettingsFrame{
4326 http2FrameHeader: http2FrameHeader{valid: true},
4327 p: opts.Settings,
4328 }
4329 if err := fr.ForeachSetting(sc.processSetting); err != nil {
4330 sc.rejectConn(http2ErrCodeProtocol, "invalid settings")
4331 return
4332 }
4333 opts.Settings = nil
4334 }
4335
4336 if hook := http2testHookGetServerConn; hook != nil {
4337 hook(sc)
4338 }
4339
4340 if opts.UpgradeRequest != nil {
4341 sc.upgradeRequest(opts.UpgradeRequest)
4342 opts.UpgradeRequest = nil
4343 }
4344
4345 sc.serve()
4346 }
4347
4348 func http2serverConnBaseContext(c net.Conn, opts *http2ServeConnOpts) (ctx context.Context, cancel func()) {
4349 ctx, cancel = context.WithCancel(opts.context())
4350 ctx = context.WithValue(ctx, LocalAddrContextKey, c.LocalAddr())
4351 if hs := opts.baseConfig(); hs != nil {
4352 ctx = context.WithValue(ctx, ServerContextKey, hs)
4353 }
4354 return
4355 }
4356
4357 func (sc *http2serverConn) rejectConn(err http2ErrCode, debug string) {
4358 sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
4359
4360 sc.framer.WriteGoAway(0, err, []byte(debug))
4361 sc.bw.Flush()
4362 sc.conn.Close()
4363 }
4364
4365 type http2serverConn struct {
4366
4367 srv *http2Server
4368 hs *Server
4369 conn net.Conn
4370 bw *http2bufferedWriter
4371 handler Handler
4372 baseCtx context.Context
4373 framer *http2Framer
4374 doneServing chan struct{}
4375 readFrameCh chan http2readFrameResult
4376 wantWriteFrameCh chan http2FrameWriteRequest
4377 wroteFrameCh chan http2frameWriteResult
4378 bodyReadCh chan http2bodyReadMsg
4379 serveMsgCh chan interface{}
4380 flow http2outflow
4381 inflow http2inflow
4382 tlsState *tls.ConnectionState
4383 remoteAddrStr string
4384 writeSched http2WriteScheduler
4385
4386
4387 serveG http2goroutineLock
4388 pushEnabled bool
4389 sawClientPreface bool
4390 sawFirstSettings bool
4391 needToSendSettingsAck bool
4392 unackedSettings int
4393 queuedControlFrames int
4394 clientMaxStreams uint32
4395 advMaxStreams uint32
4396 curClientStreams uint32
4397 curPushedStreams uint32
4398 curHandlers uint32
4399 maxClientStreamID uint32
4400 maxPushPromiseID uint32
4401 streams map[uint32]*http2stream
4402 unstartedHandlers []http2unstartedHandler
4403 initialStreamSendWindowSize int32
4404 maxFrameSize int32
4405 peerMaxHeaderListSize uint32
4406 canonHeader map[string]string
4407 canonHeaderKeysSize int
4408 writingFrame bool
4409 writingFrameAsync bool
4410 needsFrameFlush bool
4411 inGoAway bool
4412 inFrameScheduleLoop bool
4413 needToSendGoAway bool
4414 goAwayCode http2ErrCode
4415 shutdownTimer *time.Timer
4416 idleTimer *time.Timer
4417
4418
4419 headerWriteBuf bytes.Buffer
4420 hpackEncoder *hpack.Encoder
4421
4422
4423 shutdownOnce sync.Once
4424 }
4425
4426 func (sc *http2serverConn) maxHeaderListSize() uint32 {
4427 n := sc.hs.MaxHeaderBytes
4428 if n <= 0 {
4429 n = DefaultMaxHeaderBytes
4430 }
4431
4432
4433 const perFieldOverhead = 32
4434 const typicalHeaders = 10
4435 return uint32(n + typicalHeaders*perFieldOverhead)
4436 }
4437
4438 func (sc *http2serverConn) curOpenStreams() uint32 {
4439 sc.serveG.check()
4440 return sc.curClientStreams + sc.curPushedStreams
4441 }
4442
4443
4444
4445
4446
4447
4448
4449
4450 type http2stream struct {
4451
4452 sc *http2serverConn
4453 id uint32
4454 body *http2pipe
4455 cw http2closeWaiter
4456 ctx context.Context
4457 cancelCtx func()
4458
4459
4460 bodyBytes int64
4461 declBodyBytes int64
4462 flow http2outflow
4463 inflow http2inflow
4464 state http2streamState
4465 resetQueued bool
4466 gotTrailerHeader bool
4467 wroteHeaders bool
4468 readDeadline *time.Timer
4469 writeDeadline *time.Timer
4470 closeErr error
4471
4472 trailer Header
4473 reqTrailer Header
4474 }
4475
4476 func (sc *http2serverConn) Framer() *http2Framer { return sc.framer }
4477
4478 func (sc *http2serverConn) CloseConn() error { return sc.conn.Close() }
4479
4480 func (sc *http2serverConn) Flush() error { return sc.bw.Flush() }
4481
4482 func (sc *http2serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
4483 return sc.hpackEncoder, &sc.headerWriteBuf
4484 }
4485
4486 func (sc *http2serverConn) state(streamID uint32) (http2streamState, *http2stream) {
4487 sc.serveG.check()
4488
4489 if st, ok := sc.streams[streamID]; ok {
4490 return st.state, st
4491 }
4492
4493
4494
4495
4496
4497
4498 if streamID%2 == 1 {
4499 if streamID <= sc.maxClientStreamID {
4500 return http2stateClosed, nil
4501 }
4502 } else {
4503 if streamID <= sc.maxPushPromiseID {
4504 return http2stateClosed, nil
4505 }
4506 }
4507 return http2stateIdle, nil
4508 }
4509
4510
4511
4512
4513 func (sc *http2serverConn) setConnState(state ConnState) {
4514 if sc.hs.ConnState != nil {
4515 sc.hs.ConnState(sc.conn, state)
4516 }
4517 }
4518
4519 func (sc *http2serverConn) vlogf(format string, args ...interface{}) {
4520 if http2VerboseLogs {
4521 sc.logf(format, args...)
4522 }
4523 }
4524
4525 func (sc *http2serverConn) logf(format string, args ...interface{}) {
4526 if lg := sc.hs.ErrorLog; lg != nil {
4527 lg.Printf(format, args...)
4528 } else {
4529 log.Printf(format, args...)
4530 }
4531 }
4532
4533
4534
4535
4536
4537 func http2errno(v error) uintptr {
4538 if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
4539 return uintptr(rv.Uint())
4540 }
4541 return 0
4542 }
4543
4544
4545
4546 func http2isClosedConnError(err error) bool {
4547 if err == nil {
4548 return false
4549 }
4550
4551
4552
4553
4554 str := err.Error()
4555 if strings.Contains(str, "use of closed network connection") {
4556 return true
4557 }
4558
4559
4560
4561
4562
4563 if runtime.GOOS == "windows" {
4564 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
4565 if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
4566 const WSAECONNABORTED = 10053
4567 const WSAECONNRESET = 10054
4568 if n := http2errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
4569 return true
4570 }
4571 }
4572 }
4573 }
4574 return false
4575 }
4576
4577 func (sc *http2serverConn) condlogf(err error, format string, args ...interface{}) {
4578 if err == nil {
4579 return
4580 }
4581 if err == io.EOF || err == io.ErrUnexpectedEOF || http2isClosedConnError(err) || err == http2errPrefaceTimeout {
4582
4583 sc.vlogf(format, args...)
4584 } else {
4585 sc.logf(format, args...)
4586 }
4587 }
4588
4589
4590
4591
4592
4593
4594 const http2maxCachedCanonicalHeadersKeysSize = 2048
4595
4596 func (sc *http2serverConn) canonicalHeader(v string) string {
4597 sc.serveG.check()
4598 http2buildCommonHeaderMapsOnce()
4599 cv, ok := http2commonCanonHeader[v]
4600 if ok {
4601 return cv
4602 }
4603 cv, ok = sc.canonHeader[v]
4604 if ok {
4605 return cv
4606 }
4607 if sc.canonHeader == nil {
4608 sc.canonHeader = make(map[string]string)
4609 }
4610 cv = CanonicalHeaderKey(v)
4611 size := 100 + len(v)*2
4612 if sc.canonHeaderKeysSize+size <= http2maxCachedCanonicalHeadersKeysSize {
4613 sc.canonHeader[v] = cv
4614 sc.canonHeaderKeysSize += size
4615 }
4616 return cv
4617 }
4618
4619 type http2readFrameResult struct {
4620 f http2Frame
4621 err error
4622
4623
4624
4625
4626 readMore func()
4627 }
4628
4629
4630
4631
4632
4633 func (sc *http2serverConn) readFrames() {
4634 gate := make(http2gate)
4635 gateDone := gate.Done
4636 for {
4637 f, err := sc.framer.ReadFrame()
4638 select {
4639 case sc.readFrameCh <- http2readFrameResult{f, err, gateDone}:
4640 case <-sc.doneServing:
4641 return
4642 }
4643 select {
4644 case <-gate:
4645 case <-sc.doneServing:
4646 return
4647 }
4648 if http2terminalReadFrameError(err) {
4649 return
4650 }
4651 }
4652 }
4653
4654
4655 type http2frameWriteResult struct {
4656 _ http2incomparable
4657 wr http2FrameWriteRequest
4658 err error
4659 }
4660
4661
4662
4663
4664
4665 func (sc *http2serverConn) writeFrameAsync(wr http2FrameWriteRequest, wd *http2writeData) {
4666 var err error
4667 if wd == nil {
4668 err = wr.write.writeFrame(sc)
4669 } else {
4670 err = sc.framer.endWrite()
4671 }
4672 sc.wroteFrameCh <- http2frameWriteResult{wr: wr, err: err}
4673 }
4674
4675 func (sc *http2serverConn) closeAllStreamsOnConnClose() {
4676 sc.serveG.check()
4677 for _, st := range sc.streams {
4678 sc.closeStream(st, http2errClientDisconnected)
4679 }
4680 }
4681
4682 func (sc *http2serverConn) stopShutdownTimer() {
4683 sc.serveG.check()
4684 if t := sc.shutdownTimer; t != nil {
4685 t.Stop()
4686 }
4687 }
4688
4689 func (sc *http2serverConn) notePanic() {
4690
4691 if http2testHookOnPanicMu != nil {
4692 http2testHookOnPanicMu.Lock()
4693 defer http2testHookOnPanicMu.Unlock()
4694 }
4695 if http2testHookOnPanic != nil {
4696 if e := recover(); e != nil {
4697 if http2testHookOnPanic(sc, e) {
4698 panic(e)
4699 }
4700 }
4701 }
4702 }
4703
4704 func (sc *http2serverConn) serve() {
4705 sc.serveG.check()
4706 defer sc.notePanic()
4707 defer sc.conn.Close()
4708 defer sc.closeAllStreamsOnConnClose()
4709 defer sc.stopShutdownTimer()
4710 defer close(sc.doneServing)
4711
4712 if http2VerboseLogs {
4713 sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
4714 }
4715
4716 sc.writeFrame(http2FrameWriteRequest{
4717 write: http2writeSettings{
4718 {http2SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
4719 {http2SettingMaxConcurrentStreams, sc.advMaxStreams},
4720 {http2SettingMaxHeaderListSize, sc.maxHeaderListSize()},
4721 {http2SettingHeaderTableSize, sc.srv.maxDecoderHeaderTableSize()},
4722 {http2SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())},
4723 },
4724 })
4725 sc.unackedSettings++
4726
4727
4728
4729 if diff := sc.srv.initialConnRecvWindowSize() - http2initialWindowSize; diff > 0 {
4730 sc.sendWindowUpdate(nil, int(diff))
4731 }
4732
4733 if err := sc.readPreface(); err != nil {
4734 sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
4735 return
4736 }
4737
4738
4739
4740
4741 sc.setConnState(StateActive)
4742 sc.setConnState(StateIdle)
4743
4744 if sc.srv.IdleTimeout != 0 {
4745 sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer)
4746 defer sc.idleTimer.Stop()
4747 }
4748
4749 go sc.readFrames()
4750
4751 settingsTimer := time.AfterFunc(http2firstSettingsTimeout, sc.onSettingsTimer)
4752 defer settingsTimer.Stop()
4753
4754 loopNum := 0
4755 for {
4756 loopNum++
4757 select {
4758 case wr := <-sc.wantWriteFrameCh:
4759 if se, ok := wr.write.(http2StreamError); ok {
4760 sc.resetStream(se)
4761 break
4762 }
4763 sc.writeFrame(wr)
4764 case res := <-sc.wroteFrameCh:
4765 sc.wroteFrame(res)
4766 case res := <-sc.readFrameCh:
4767
4768
4769 if sc.writingFrameAsync {
4770 select {
4771 case wroteRes := <-sc.wroteFrameCh:
4772 sc.wroteFrame(wroteRes)
4773 default:
4774 }
4775 }
4776 if !sc.processFrameFromReader(res) {
4777 return
4778 }
4779 res.readMore()
4780 if settingsTimer != nil {
4781 settingsTimer.Stop()
4782 settingsTimer = nil
4783 }
4784 case m := <-sc.bodyReadCh:
4785 sc.noteBodyRead(m.st, m.n)
4786 case msg := <-sc.serveMsgCh:
4787 switch v := msg.(type) {
4788 case func(int):
4789 v(loopNum)
4790 case *http2serverMessage:
4791 switch v {
4792 case http2settingsTimerMsg:
4793 sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
4794 return
4795 case http2idleTimerMsg:
4796 sc.vlogf("connection is idle")
4797 sc.goAway(http2ErrCodeNo)
4798 case http2shutdownTimerMsg:
4799 sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
4800 return
4801 case http2gracefulShutdownMsg:
4802 sc.startGracefulShutdownInternal()
4803 case http2handlerDoneMsg:
4804 sc.handlerDone()
4805 default:
4806 panic("unknown timer")
4807 }
4808 case *http2startPushRequest:
4809 sc.startPush(v)
4810 case func(*http2serverConn):
4811 v(sc)
4812 default:
4813 panic(fmt.Sprintf("unexpected type %T", v))
4814 }
4815 }
4816
4817
4818
4819
4820 if sc.queuedControlFrames > sc.srv.maxQueuedControlFrames() {
4821 sc.vlogf("http2: too many control frames in send queue, closing connection")
4822 return
4823 }
4824
4825
4826
4827
4828 sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
4829 gracefulShutdownComplete := sc.goAwayCode == http2ErrCodeNo && sc.curOpenStreams() == 0
4830 if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != http2ErrCodeNo || gracefulShutdownComplete) {
4831 sc.shutDownIn(http2goAwayTimeout)
4832 }
4833 }
4834 }
4835
4836 type http2serverMessage int
4837
4838
4839 var (
4840 http2settingsTimerMsg = new(http2serverMessage)
4841 http2idleTimerMsg = new(http2serverMessage)
4842 http2shutdownTimerMsg = new(http2serverMessage)
4843 http2gracefulShutdownMsg = new(http2serverMessage)
4844 http2handlerDoneMsg = new(http2serverMessage)
4845 )
4846
4847 func (sc *http2serverConn) onSettingsTimer() { sc.sendServeMsg(http2settingsTimerMsg) }
4848
4849 func (sc *http2serverConn) onIdleTimer() { sc.sendServeMsg(http2idleTimerMsg) }
4850
4851 func (sc *http2serverConn) onShutdownTimer() { sc.sendServeMsg(http2shutdownTimerMsg) }
4852
4853 func (sc *http2serverConn) sendServeMsg(msg interface{}) {
4854 sc.serveG.checkNotOn()
4855 select {
4856 case sc.serveMsgCh <- msg:
4857 case <-sc.doneServing:
4858 }
4859 }
4860
4861 var http2errPrefaceTimeout = errors.New("timeout waiting for client preface")
4862
4863
4864
4865
4866 func (sc *http2serverConn) readPreface() error {
4867 if sc.sawClientPreface {
4868 return nil
4869 }
4870 errc := make(chan error, 1)
4871 go func() {
4872
4873 buf := make([]byte, len(http2ClientPreface))
4874 if _, err := io.ReadFull(sc.conn, buf); err != nil {
4875 errc <- err
4876 } else if !bytes.Equal(buf, http2clientPreface) {
4877 errc <- fmt.Errorf("bogus greeting %q", buf)
4878 } else {
4879 errc <- nil
4880 }
4881 }()
4882 timer := time.NewTimer(http2prefaceTimeout)
4883 defer timer.Stop()
4884 select {
4885 case <-timer.C:
4886 return http2errPrefaceTimeout
4887 case err := <-errc:
4888 if err == nil {
4889 if http2VerboseLogs {
4890 sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
4891 }
4892 }
4893 return err
4894 }
4895 }
4896
4897 var http2errChanPool = sync.Pool{
4898 New: func() interface{} { return make(chan error, 1) },
4899 }
4900
4901 var http2writeDataPool = sync.Pool{
4902 New: func() interface{} { return new(http2writeData) },
4903 }
4904
4905
4906
4907 func (sc *http2serverConn) writeDataFromHandler(stream *http2stream, data []byte, endStream bool) error {
4908 ch := http2errChanPool.Get().(chan error)
4909 writeArg := http2writeDataPool.Get().(*http2writeData)
4910 *writeArg = http2writeData{stream.id, data, endStream}
4911 err := sc.writeFrameFromHandler(http2FrameWriteRequest{
4912 write: writeArg,
4913 stream: stream,
4914 done: ch,
4915 })
4916 if err != nil {
4917 return err
4918 }
4919 var frameWriteDone bool
4920 select {
4921 case err = <-ch:
4922 frameWriteDone = true
4923 case <-sc.doneServing:
4924 return http2errClientDisconnected
4925 case <-stream.cw:
4926
4927
4928
4929
4930
4931
4932
4933 select {
4934 case err = <-ch:
4935 frameWriteDone = true
4936 default:
4937 return http2errStreamClosed
4938 }
4939 }
4940 http2errChanPool.Put(ch)
4941 if frameWriteDone {
4942 http2writeDataPool.Put(writeArg)
4943 }
4944 return err
4945 }
4946
4947
4948
4949
4950
4951
4952
4953
4954 func (sc *http2serverConn) writeFrameFromHandler(wr http2FrameWriteRequest) error {
4955 sc.serveG.checkNotOn()
4956 select {
4957 case sc.wantWriteFrameCh <- wr:
4958 return nil
4959 case <-sc.doneServing:
4960
4961
4962 return http2errClientDisconnected
4963 }
4964 }
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974 func (sc *http2serverConn) writeFrame(wr http2FrameWriteRequest) {
4975 sc.serveG.check()
4976
4977
4978 var ignoreWrite bool
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998 if wr.StreamID() != 0 {
4999 _, isReset := wr.write.(http2StreamError)
5000 if state, _ := sc.state(wr.StreamID()); state == http2stateClosed && !isReset {
5001 ignoreWrite = true
5002 }
5003 }
5004
5005
5006
5007 switch wr.write.(type) {
5008 case *http2writeResHeaders:
5009 wr.stream.wroteHeaders = true
5010 case http2write100ContinueHeadersFrame:
5011 if wr.stream.wroteHeaders {
5012
5013
5014 if wr.done != nil {
5015 panic("wr.done != nil for write100ContinueHeadersFrame")
5016 }
5017 ignoreWrite = true
5018 }
5019 }
5020
5021 if !ignoreWrite {
5022 if wr.isControl() {
5023 sc.queuedControlFrames++
5024
5025
5026 if sc.queuedControlFrames < 0 {
5027 sc.conn.Close()
5028 }
5029 }
5030 sc.writeSched.Push(wr)
5031 }
5032 sc.scheduleFrameWrite()
5033 }
5034
5035
5036
5037
5038 func (sc *http2serverConn) startFrameWrite(wr http2FrameWriteRequest) {
5039 sc.serveG.check()
5040 if sc.writingFrame {
5041 panic("internal error: can only be writing one frame at a time")
5042 }
5043
5044 st := wr.stream
5045 if st != nil {
5046 switch st.state {
5047 case http2stateHalfClosedLocal:
5048 switch wr.write.(type) {
5049 case http2StreamError, http2handlerPanicRST, http2writeWindowUpdate:
5050
5051
5052 default:
5053 panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
5054 }
5055 case http2stateClosed:
5056 panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
5057 }
5058 }
5059 if wpp, ok := wr.write.(*http2writePushPromise); ok {
5060 var err error
5061 wpp.promisedID, err = wpp.allocatePromisedID()
5062 if err != nil {
5063 sc.writingFrameAsync = false
5064 wr.replyToWriter(err)
5065 return
5066 }
5067 }
5068
5069 sc.writingFrame = true
5070 sc.needsFrameFlush = true
5071 if wr.write.staysWithinBuffer(sc.bw.Available()) {
5072 sc.writingFrameAsync = false
5073 err := wr.write.writeFrame(sc)
5074 sc.wroteFrame(http2frameWriteResult{wr: wr, err: err})
5075 } else if wd, ok := wr.write.(*http2writeData); ok {
5076
5077
5078
5079 sc.framer.startWriteDataPadded(wd.streamID, wd.endStream, wd.p, nil)
5080 sc.writingFrameAsync = true
5081 go sc.writeFrameAsync(wr, wd)
5082 } else {
5083 sc.writingFrameAsync = true
5084 go sc.writeFrameAsync(wr, nil)
5085 }
5086 }
5087
5088
5089
5090
5091 var http2errHandlerPanicked = errors.New("http2: handler panicked")
5092
5093
5094
5095 func (sc *http2serverConn) wroteFrame(res http2frameWriteResult) {
5096 sc.serveG.check()
5097 if !sc.writingFrame {
5098 panic("internal error: expected to be already writing a frame")
5099 }
5100 sc.writingFrame = false
5101 sc.writingFrameAsync = false
5102
5103 wr := res.wr
5104
5105 if http2writeEndsStream(wr.write) {
5106 st := wr.stream
5107 if st == nil {
5108 panic("internal error: expecting non-nil stream")
5109 }
5110 switch st.state {
5111 case http2stateOpen:
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122 st.state = http2stateHalfClosedLocal
5123
5124
5125
5126
5127 sc.resetStream(http2streamError(st.id, http2ErrCodeNo))
5128 case http2stateHalfClosedRemote:
5129 sc.closeStream(st, http2errHandlerComplete)
5130 }
5131 } else {
5132 switch v := wr.write.(type) {
5133 case http2StreamError:
5134
5135 if st, ok := sc.streams[v.StreamID]; ok {
5136 sc.closeStream(st, v)
5137 }
5138 case http2handlerPanicRST:
5139 sc.closeStream(wr.stream, http2errHandlerPanicked)
5140 }
5141 }
5142
5143
5144 wr.replyToWriter(res.err)
5145
5146 sc.scheduleFrameWrite()
5147 }
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159 func (sc *http2serverConn) scheduleFrameWrite() {
5160 sc.serveG.check()
5161 if sc.writingFrame || sc.inFrameScheduleLoop {
5162 return
5163 }
5164 sc.inFrameScheduleLoop = true
5165 for !sc.writingFrameAsync {
5166 if sc.needToSendGoAway {
5167 sc.needToSendGoAway = false
5168 sc.startFrameWrite(http2FrameWriteRequest{
5169 write: &http2writeGoAway{
5170 maxStreamID: sc.maxClientStreamID,
5171 code: sc.goAwayCode,
5172 },
5173 })
5174 continue
5175 }
5176 if sc.needToSendSettingsAck {
5177 sc.needToSendSettingsAck = false
5178 sc.startFrameWrite(http2FrameWriteRequest{write: http2writeSettingsAck{}})
5179 continue
5180 }
5181 if !sc.inGoAway || sc.goAwayCode == http2ErrCodeNo {
5182 if wr, ok := sc.writeSched.Pop(); ok {
5183 if wr.isControl() {
5184 sc.queuedControlFrames--
5185 }
5186 sc.startFrameWrite(wr)
5187 continue
5188 }
5189 }
5190 if sc.needsFrameFlush {
5191 sc.startFrameWrite(http2FrameWriteRequest{write: http2flushFrameWriter{}})
5192 sc.needsFrameFlush = false
5193 continue
5194 }
5195 break
5196 }
5197 sc.inFrameScheduleLoop = false
5198 }
5199
5200
5201
5202
5203
5204
5205
5206
5207 func (sc *http2serverConn) startGracefulShutdown() {
5208 sc.serveG.checkNotOn()
5209 sc.shutdownOnce.Do(func() { sc.sendServeMsg(http2gracefulShutdownMsg) })
5210 }
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228 var http2goAwayTimeout = 1 * time.Second
5229
5230 func (sc *http2serverConn) startGracefulShutdownInternal() {
5231 sc.goAway(http2ErrCodeNo)
5232 }
5233
5234 func (sc *http2serverConn) goAway(code http2ErrCode) {
5235 sc.serveG.check()
5236 if sc.inGoAway {
5237 if sc.goAwayCode == http2ErrCodeNo {
5238 sc.goAwayCode = code
5239 }
5240 return
5241 }
5242 sc.inGoAway = true
5243 sc.needToSendGoAway = true
5244 sc.goAwayCode = code
5245 sc.scheduleFrameWrite()
5246 }
5247
5248 func (sc *http2serverConn) shutDownIn(d time.Duration) {
5249 sc.serveG.check()
5250 sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
5251 }
5252
5253 func (sc *http2serverConn) resetStream(se http2StreamError) {
5254 sc.serveG.check()
5255 sc.writeFrame(http2FrameWriteRequest{write: se})
5256 if st, ok := sc.streams[se.StreamID]; ok {
5257 st.resetQueued = true
5258 }
5259 }
5260
5261
5262
5263
5264 func (sc *http2serverConn) processFrameFromReader(res http2readFrameResult) bool {
5265 sc.serveG.check()
5266 err := res.err
5267 if err != nil {
5268 if err == http2ErrFrameTooLarge {
5269 sc.goAway(http2ErrCodeFrameSize)
5270 return true
5271 }
5272 clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || http2isClosedConnError(err)
5273 if clientGone {
5274
5275
5276
5277
5278
5279
5280
5281
5282 return false
5283 }
5284 } else {
5285 f := res.f
5286 if http2VerboseLogs {
5287 sc.vlogf("http2: server read frame %v", http2summarizeFrame(f))
5288 }
5289 err = sc.processFrame(f)
5290 if err == nil {
5291 return true
5292 }
5293 }
5294
5295 switch ev := err.(type) {
5296 case http2StreamError:
5297 sc.resetStream(ev)
5298 return true
5299 case http2goAwayFlowError:
5300 sc.goAway(http2ErrCodeFlowControl)
5301 return true
5302 case http2ConnectionError:
5303 if res.f != nil {
5304 if id := res.f.Header().StreamID; id > sc.maxClientStreamID {
5305 sc.maxClientStreamID = id
5306 }
5307 }
5308 sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
5309 sc.goAway(http2ErrCode(ev))
5310 return true
5311 default:
5312 if res.err != nil {
5313 sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
5314 } else {
5315 sc.logf("http2: server closing client connection: %v", err)
5316 }
5317 return false
5318 }
5319 }
5320
5321 func (sc *http2serverConn) processFrame(f http2Frame) error {
5322 sc.serveG.check()
5323
5324
5325 if !sc.sawFirstSettings {
5326 if _, ok := f.(*http2SettingsFrame); !ok {
5327 return sc.countError("first_settings", http2ConnectionError(http2ErrCodeProtocol))
5328 }
5329 sc.sawFirstSettings = true
5330 }
5331
5332
5333
5334
5335
5336 if sc.inGoAway && (sc.goAwayCode != http2ErrCodeNo || f.Header().StreamID > sc.maxClientStreamID) {
5337
5338 if f, ok := f.(*http2DataFrame); ok {
5339 if !sc.inflow.take(f.Length) {
5340 return sc.countError("data_flow", http2streamError(f.Header().StreamID, http2ErrCodeFlowControl))
5341 }
5342 sc.sendWindowUpdate(nil, int(f.Length))
5343 }
5344 return nil
5345 }
5346
5347 switch f := f.(type) {
5348 case *http2SettingsFrame:
5349 return sc.processSettings(f)
5350 case *http2MetaHeadersFrame:
5351 return sc.processHeaders(f)
5352 case *http2WindowUpdateFrame:
5353 return sc.processWindowUpdate(f)
5354 case *http2PingFrame:
5355 return sc.processPing(f)
5356 case *http2DataFrame:
5357 return sc.processData(f)
5358 case *http2RSTStreamFrame:
5359 return sc.processResetStream(f)
5360 case *http2PriorityFrame:
5361 return sc.processPriority(f)
5362 case *http2GoAwayFrame:
5363 return sc.processGoAway(f)
5364 case *http2PushPromiseFrame:
5365
5366
5367 return sc.countError("push_promise", http2ConnectionError(http2ErrCodeProtocol))
5368 default:
5369 sc.vlogf("http2: server ignoring frame: %v", f.Header())
5370 return nil
5371 }
5372 }
5373
5374 func (sc *http2serverConn) processPing(f *http2PingFrame) error {
5375 sc.serveG.check()
5376 if f.IsAck() {
5377
5378
5379 return nil
5380 }
5381 if f.StreamID != 0 {
5382
5383
5384
5385
5386
5387 return sc.countError("ping_on_stream", http2ConnectionError(http2ErrCodeProtocol))
5388 }
5389 sc.writeFrame(http2FrameWriteRequest{write: http2writePingAck{f}})
5390 return nil
5391 }
5392
5393 func (sc *http2serverConn) processWindowUpdate(f *http2WindowUpdateFrame) error {
5394 sc.serveG.check()
5395 switch {
5396 case f.StreamID != 0:
5397 state, st := sc.state(f.StreamID)
5398 if state == http2stateIdle {
5399
5400
5401
5402
5403 return sc.countError("stream_idle", http2ConnectionError(http2ErrCodeProtocol))
5404 }
5405 if st == nil {
5406
5407
5408
5409
5410
5411 return nil
5412 }
5413 if !st.flow.add(int32(f.Increment)) {
5414 return sc.countError("bad_flow", http2streamError(f.StreamID, http2ErrCodeFlowControl))
5415 }
5416 default:
5417 if !sc.flow.add(int32(f.Increment)) {
5418 return http2goAwayFlowError{}
5419 }
5420 }
5421 sc.scheduleFrameWrite()
5422 return nil
5423 }
5424
5425 func (sc *http2serverConn) processResetStream(f *http2RSTStreamFrame) error {
5426 sc.serveG.check()
5427
5428 state, st := sc.state(f.StreamID)
5429 if state == http2stateIdle {
5430
5431
5432
5433
5434
5435 return sc.countError("reset_idle_stream", http2ConnectionError(http2ErrCodeProtocol))
5436 }
5437 if st != nil {
5438 st.cancelCtx()
5439 sc.closeStream(st, http2streamError(f.StreamID, f.ErrCode))
5440 }
5441 return nil
5442 }
5443
5444 func (sc *http2serverConn) closeStream(st *http2stream, err error) {
5445 sc.serveG.check()
5446 if st.state == http2stateIdle || st.state == http2stateClosed {
5447 panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
5448 }
5449 st.state = http2stateClosed
5450 if st.readDeadline != nil {
5451 st.readDeadline.Stop()
5452 }
5453 if st.writeDeadline != nil {
5454 st.writeDeadline.Stop()
5455 }
5456 if st.isPushed() {
5457 sc.curPushedStreams--
5458 } else {
5459 sc.curClientStreams--
5460 }
5461 delete(sc.streams, st.id)
5462 if len(sc.streams) == 0 {
5463 sc.setConnState(StateIdle)
5464 if sc.srv.IdleTimeout != 0 {
5465 sc.idleTimer.Reset(sc.srv.IdleTimeout)
5466 }
5467 if http2h1ServerKeepAlivesDisabled(sc.hs) {
5468 sc.startGracefulShutdownInternal()
5469 }
5470 }
5471 if p := st.body; p != nil {
5472
5473
5474 sc.sendWindowUpdate(nil, p.Len())
5475
5476 p.CloseWithError(err)
5477 }
5478 if e, ok := err.(http2StreamError); ok {
5479 if e.Cause != nil {
5480 err = e.Cause
5481 } else {
5482 err = http2errStreamClosed
5483 }
5484 }
5485 st.closeErr = err
5486 st.cw.Close()
5487 sc.writeSched.CloseStream(st.id)
5488 }
5489
5490 func (sc *http2serverConn) processSettings(f *http2SettingsFrame) error {
5491 sc.serveG.check()
5492 if f.IsAck() {
5493 sc.unackedSettings--
5494 if sc.unackedSettings < 0 {
5495
5496
5497
5498 return sc.countError("ack_mystery", http2ConnectionError(http2ErrCodeProtocol))
5499 }
5500 return nil
5501 }
5502 if f.NumSettings() > 100 || f.HasDuplicates() {
5503
5504
5505
5506 return sc.countError("settings_big_or_dups", http2ConnectionError(http2ErrCodeProtocol))
5507 }
5508 if err := f.ForeachSetting(sc.processSetting); err != nil {
5509 return err
5510 }
5511
5512
5513 sc.needToSendSettingsAck = true
5514 sc.scheduleFrameWrite()
5515 return nil
5516 }
5517
5518 func (sc *http2serverConn) processSetting(s http2Setting) error {
5519 sc.serveG.check()
5520 if err := s.Valid(); err != nil {
5521 return err
5522 }
5523 if http2VerboseLogs {
5524 sc.vlogf("http2: server processing setting %v", s)
5525 }
5526 switch s.ID {
5527 case http2SettingHeaderTableSize:
5528 sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
5529 case http2SettingEnablePush:
5530 sc.pushEnabled = s.Val != 0
5531 case http2SettingMaxConcurrentStreams:
5532 sc.clientMaxStreams = s.Val
5533 case http2SettingInitialWindowSize:
5534 return sc.processSettingInitialWindowSize(s.Val)
5535 case http2SettingMaxFrameSize:
5536 sc.maxFrameSize = int32(s.Val)
5537 case http2SettingMaxHeaderListSize:
5538 sc.peerMaxHeaderListSize = s.Val
5539 default:
5540
5541
5542
5543 if http2VerboseLogs {
5544 sc.vlogf("http2: server ignoring unknown setting %v", s)
5545 }
5546 }
5547 return nil
5548 }
5549
5550 func (sc *http2serverConn) processSettingInitialWindowSize(val uint32) error {
5551 sc.serveG.check()
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561 old := sc.initialStreamSendWindowSize
5562 sc.initialStreamSendWindowSize = int32(val)
5563 growth := int32(val) - old
5564 for _, st := range sc.streams {
5565 if !st.flow.add(growth) {
5566
5567
5568
5569
5570
5571
5572 return sc.countError("setting_win_size", http2ConnectionError(http2ErrCodeFlowControl))
5573 }
5574 }
5575 return nil
5576 }
5577
5578 func (sc *http2serverConn) processData(f *http2DataFrame) error {
5579 sc.serveG.check()
5580 id := f.Header().StreamID
5581
5582 data := f.Data()
5583 state, st := sc.state(id)
5584 if id == 0 || state == http2stateIdle {
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595 return sc.countError("data_on_idle", http2ConnectionError(http2ErrCodeProtocol))
5596 }
5597
5598
5599
5600
5601 if st == nil || state != http2stateOpen || st.gotTrailerHeader || st.resetQueued {
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611 if !sc.inflow.take(f.Length) {
5612 return sc.countError("data_flow", http2streamError(id, http2ErrCodeFlowControl))
5613 }
5614 sc.sendWindowUpdate(nil, int(f.Length))
5615
5616 if st != nil && st.resetQueued {
5617
5618 return nil
5619 }
5620 return sc.countError("closed", http2streamError(id, http2ErrCodeStreamClosed))
5621 }
5622 if st.body == nil {
5623 panic("internal error: should have a body in this state")
5624 }
5625
5626
5627 if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
5628 if !sc.inflow.take(f.Length) {
5629 return sc.countError("data_flow", http2streamError(id, http2ErrCodeFlowControl))
5630 }
5631 sc.sendWindowUpdate(nil, int(f.Length))
5632
5633 st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
5634
5635
5636
5637 return sc.countError("send_too_much", http2streamError(id, http2ErrCodeProtocol))
5638 }
5639 if f.Length > 0 {
5640
5641 if !http2takeInflows(&sc.inflow, &st.inflow, f.Length) {
5642 return sc.countError("flow_on_data_length", http2streamError(id, http2ErrCodeFlowControl))
5643 }
5644
5645 if len(data) > 0 {
5646 st.bodyBytes += int64(len(data))
5647 wrote, err := st.body.Write(data)
5648 if err != nil {
5649
5650
5651
5652 sc.sendWindowUpdate(nil, int(f.Length)-wrote)
5653 return nil
5654 }
5655 if wrote != len(data) {
5656 panic("internal error: bad Writer")
5657 }
5658 }
5659
5660
5661
5662
5663
5664
5665 pad := int32(f.Length) - int32(len(data))
5666 sc.sendWindowUpdate32(nil, pad)
5667 sc.sendWindowUpdate32(st, pad)
5668 }
5669 if f.StreamEnded() {
5670 st.endStream()
5671 }
5672 return nil
5673 }
5674
5675 func (sc *http2serverConn) processGoAway(f *http2GoAwayFrame) error {
5676 sc.serveG.check()
5677 if f.ErrCode != http2ErrCodeNo {
5678 sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
5679 } else {
5680 sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
5681 }
5682 sc.startGracefulShutdownInternal()
5683
5684
5685 sc.pushEnabled = false
5686 return nil
5687 }
5688
5689
5690 func (st *http2stream) isPushed() bool {
5691 return st.id%2 == 0
5692 }
5693
5694
5695
5696 func (st *http2stream) endStream() {
5697 sc := st.sc
5698 sc.serveG.check()
5699
5700 if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
5701 st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
5702 st.declBodyBytes, st.bodyBytes))
5703 } else {
5704 st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
5705 st.body.CloseWithError(io.EOF)
5706 }
5707 st.state = http2stateHalfClosedRemote
5708 }
5709
5710
5711
5712 func (st *http2stream) copyTrailersToHandlerRequest() {
5713 for k, vv := range st.trailer {
5714 if _, ok := st.reqTrailer[k]; ok {
5715
5716 st.reqTrailer[k] = vv
5717 }
5718 }
5719 }
5720
5721
5722
5723 func (st *http2stream) onReadTimeout() {
5724 if st.body != nil {
5725
5726
5727 st.body.CloseWithError(fmt.Errorf("%w", os.ErrDeadlineExceeded))
5728 }
5729 }
5730
5731
5732
5733 func (st *http2stream) onWriteTimeout() {
5734 st.sc.writeFrameFromHandler(http2FrameWriteRequest{write: http2StreamError{
5735 StreamID: st.id,
5736 Code: http2ErrCodeInternal,
5737 Cause: os.ErrDeadlineExceeded,
5738 }})
5739 }
5740
5741 func (sc *http2serverConn) processHeaders(f *http2MetaHeadersFrame) error {
5742 sc.serveG.check()
5743 id := f.StreamID
5744
5745
5746
5747
5748
5749 if id%2 != 1 {
5750 return sc.countError("headers_even", http2ConnectionError(http2ErrCodeProtocol))
5751 }
5752
5753
5754
5755
5756 if st := sc.streams[f.StreamID]; st != nil {
5757 if st.resetQueued {
5758
5759
5760 return nil
5761 }
5762
5763
5764
5765
5766 if st.state == http2stateHalfClosedRemote {
5767 return sc.countError("headers_half_closed", http2streamError(id, http2ErrCodeStreamClosed))
5768 }
5769 return st.processTrailerHeaders(f)
5770 }
5771
5772
5773
5774
5775
5776
5777 if id <= sc.maxClientStreamID {
5778 return sc.countError("stream_went_down", http2ConnectionError(http2ErrCodeProtocol))
5779 }
5780 sc.maxClientStreamID = id
5781
5782 if sc.idleTimer != nil {
5783 sc.idleTimer.Stop()
5784 }
5785
5786
5787
5788
5789
5790
5791
5792 if sc.curClientStreams+1 > sc.advMaxStreams {
5793 if sc.unackedSettings == 0 {
5794
5795 return sc.countError("over_max_streams", http2streamError(id, http2ErrCodeProtocol))
5796 }
5797
5798
5799
5800
5801
5802 return sc.countError("over_max_streams_race", http2streamError(id, http2ErrCodeRefusedStream))
5803 }
5804
5805 initialState := http2stateOpen
5806 if f.StreamEnded() {
5807 initialState = http2stateHalfClosedRemote
5808 }
5809 st := sc.newStream(id, 0, initialState)
5810
5811 if f.HasPriority() {
5812 if err := sc.checkPriority(f.StreamID, f.Priority); err != nil {
5813 return err
5814 }
5815 sc.writeSched.AdjustStream(st.id, f.Priority)
5816 }
5817
5818 rw, req, err := sc.newWriterAndRequest(st, f)
5819 if err != nil {
5820 return err
5821 }
5822 st.reqTrailer = req.Trailer
5823 if st.reqTrailer != nil {
5824 st.trailer = make(Header)
5825 }
5826 st.body = req.Body.(*http2requestBody).pipe
5827 st.declBodyBytes = req.ContentLength
5828
5829 handler := sc.handler.ServeHTTP
5830 if f.Truncated {
5831
5832 handler = http2handleHeaderListTooLong
5833 } else if err := http2checkValidHTTP2RequestHeaders(req.Header); err != nil {
5834 handler = http2new400Handler(err)
5835 }
5836
5837
5838
5839
5840
5841
5842
5843
5844 if sc.hs.ReadTimeout != 0 {
5845 sc.conn.SetReadDeadline(time.Time{})
5846 st.readDeadline = time.AfterFunc(sc.hs.ReadTimeout, st.onReadTimeout)
5847 }
5848
5849 return sc.scheduleHandler(id, rw, req, handler)
5850 }
5851
5852 func (sc *http2serverConn) upgradeRequest(req *Request) {
5853 sc.serveG.check()
5854 id := uint32(1)
5855 sc.maxClientStreamID = id
5856 st := sc.newStream(id, 0, http2stateHalfClosedRemote)
5857 st.reqTrailer = req.Trailer
5858 if st.reqTrailer != nil {
5859 st.trailer = make(Header)
5860 }
5861 rw := sc.newResponseWriter(st, req)
5862
5863
5864
5865 if sc.hs.ReadTimeout != 0 {
5866 sc.conn.SetReadDeadline(time.Time{})
5867 }
5868
5869
5870
5871
5872 sc.curHandlers++
5873 go sc.runHandler(rw, req, sc.handler.ServeHTTP)
5874 }
5875
5876 func (st *http2stream) processTrailerHeaders(f *http2MetaHeadersFrame) error {
5877 sc := st.sc
5878 sc.serveG.check()
5879 if st.gotTrailerHeader {
5880 return sc.countError("dup_trailers", http2ConnectionError(http2ErrCodeProtocol))
5881 }
5882 st.gotTrailerHeader = true
5883 if !f.StreamEnded() {
5884 return sc.countError("trailers_not_ended", http2streamError(st.id, http2ErrCodeProtocol))
5885 }
5886
5887 if len(f.PseudoFields()) > 0 {
5888 return sc.countError("trailers_pseudo", http2streamError(st.id, http2ErrCodeProtocol))
5889 }
5890 if st.trailer != nil {
5891 for _, hf := range f.RegularFields() {
5892 key := sc.canonicalHeader(hf.Name)
5893 if !httpguts.ValidTrailerHeader(key) {
5894
5895
5896
5897 return sc.countError("trailers_bogus", http2streamError(st.id, http2ErrCodeProtocol))
5898 }
5899 st.trailer[key] = append(st.trailer[key], hf.Value)
5900 }
5901 }
5902 st.endStream()
5903 return nil
5904 }
5905
5906 func (sc *http2serverConn) checkPriority(streamID uint32, p http2PriorityParam) error {
5907 if streamID == p.StreamDep {
5908
5909
5910
5911
5912 return sc.countError("priority", http2streamError(streamID, http2ErrCodeProtocol))
5913 }
5914 return nil
5915 }
5916
5917 func (sc *http2serverConn) processPriority(f *http2PriorityFrame) error {
5918 if err := sc.checkPriority(f.StreamID, f.http2PriorityParam); err != nil {
5919 return err
5920 }
5921 sc.writeSched.AdjustStream(f.StreamID, f.http2PriorityParam)
5922 return nil
5923 }
5924
5925 func (sc *http2serverConn) newStream(id, pusherID uint32, state http2streamState) *http2stream {
5926 sc.serveG.check()
5927 if id == 0 {
5928 panic("internal error: cannot create stream with id 0")
5929 }
5930
5931 ctx, cancelCtx := context.WithCancel(sc.baseCtx)
5932 st := &http2stream{
5933 sc: sc,
5934 id: id,
5935 state: state,
5936 ctx: ctx,
5937 cancelCtx: cancelCtx,
5938 }
5939 st.cw.Init()
5940 st.flow.conn = &sc.flow
5941 st.flow.add(sc.initialStreamSendWindowSize)
5942 st.inflow.init(sc.srv.initialStreamRecvWindowSize())
5943 if sc.hs.WriteTimeout != 0 {
5944 st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout)
5945 }
5946
5947 sc.streams[id] = st
5948 sc.writeSched.OpenStream(st.id, http2OpenStreamOptions{PusherID: pusherID})
5949 if st.isPushed() {
5950 sc.curPushedStreams++
5951 } else {
5952 sc.curClientStreams++
5953 }
5954 if sc.curOpenStreams() == 1 {
5955 sc.setConnState(StateActive)
5956 }
5957
5958 return st
5959 }
5960
5961 func (sc *http2serverConn) newWriterAndRequest(st *http2stream, f *http2MetaHeadersFrame) (*http2responseWriter, *Request, error) {
5962 sc.serveG.check()
5963
5964 rp := http2requestParam{
5965 method: f.PseudoValue("method"),
5966 scheme: f.PseudoValue("scheme"),
5967 authority: f.PseudoValue("authority"),
5968 path: f.PseudoValue("path"),
5969 }
5970
5971 isConnect := rp.method == "CONNECT"
5972 if isConnect {
5973 if rp.path != "" || rp.scheme != "" || rp.authority == "" {
5974 return nil, nil, sc.countError("bad_connect", http2streamError(f.StreamID, http2ErrCodeProtocol))
5975 }
5976 } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987 return nil, nil, sc.countError("bad_path_method", http2streamError(f.StreamID, http2ErrCodeProtocol))
5988 }
5989
5990 rp.header = make(Header)
5991 for _, hf := range f.RegularFields() {
5992 rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
5993 }
5994 if rp.authority == "" {
5995 rp.authority = rp.header.Get("Host")
5996 }
5997
5998 rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
5999 if err != nil {
6000 return nil, nil, err
6001 }
6002 bodyOpen := !f.StreamEnded()
6003 if bodyOpen {
6004 if vv, ok := rp.header["Content-Length"]; ok {
6005 if cl, err := strconv.ParseUint(vv[0], 10, 63); err == nil {
6006 req.ContentLength = int64(cl)
6007 } else {
6008 req.ContentLength = 0
6009 }
6010 } else {
6011 req.ContentLength = -1
6012 }
6013 req.Body.(*http2requestBody).pipe = &http2pipe{
6014 b: &http2dataBuffer{expected: req.ContentLength},
6015 }
6016 }
6017 return rw, req, nil
6018 }
6019
6020 type http2requestParam struct {
6021 method string
6022 scheme, authority, path string
6023 header Header
6024 }
6025
6026 func (sc *http2serverConn) newWriterAndRequestNoBody(st *http2stream, rp http2requestParam) (*http2responseWriter, *Request, error) {
6027 sc.serveG.check()
6028
6029 var tlsState *tls.ConnectionState
6030 if rp.scheme == "https" {
6031 tlsState = sc.tlsState
6032 }
6033
6034 needsContinue := httpguts.HeaderValuesContainsToken(rp.header["Expect"], "100-continue")
6035 if needsContinue {
6036 rp.header.Del("Expect")
6037 }
6038
6039 if cookies := rp.header["Cookie"]; len(cookies) > 1 {
6040 rp.header.Set("Cookie", strings.Join(cookies, "; "))
6041 }
6042
6043
6044 var trailer Header
6045 for _, v := range rp.header["Trailer"] {
6046 for _, key := range strings.Split(v, ",") {
6047 key = CanonicalHeaderKey(textproto.TrimString(key))
6048 switch key {
6049 case "Transfer-Encoding", "Trailer", "Content-Length":
6050
6051
6052 default:
6053 if trailer == nil {
6054 trailer = make(Header)
6055 }
6056 trailer[key] = nil
6057 }
6058 }
6059 }
6060 delete(rp.header, "Trailer")
6061
6062 var url_ *url.URL
6063 var requestURI string
6064 if rp.method == "CONNECT" {
6065 url_ = &url.URL{Host: rp.authority}
6066 requestURI = rp.authority
6067 } else {
6068 var err error
6069 url_, err = url.ParseRequestURI(rp.path)
6070 if err != nil {
6071 return nil, nil, sc.countError("bad_path", http2streamError(st.id, http2ErrCodeProtocol))
6072 }
6073 requestURI = rp.path
6074 }
6075
6076 body := &http2requestBody{
6077 conn: sc,
6078 stream: st,
6079 needsContinue: needsContinue,
6080 }
6081 req := &Request{
6082 Method: rp.method,
6083 URL: url_,
6084 RemoteAddr: sc.remoteAddrStr,
6085 Header: rp.header,
6086 RequestURI: requestURI,
6087 Proto: "HTTP/2.0",
6088 ProtoMajor: 2,
6089 ProtoMinor: 0,
6090 TLS: tlsState,
6091 Host: rp.authority,
6092 Body: body,
6093 Trailer: trailer,
6094 }
6095 req = req.WithContext(st.ctx)
6096
6097 rw := sc.newResponseWriter(st, req)
6098 return rw, req, nil
6099 }
6100
6101 func (sc *http2serverConn) newResponseWriter(st *http2stream, req *Request) *http2responseWriter {
6102 rws := http2responseWriterStatePool.Get().(*http2responseWriterState)
6103 bwSave := rws.bw
6104 *rws = http2responseWriterState{}
6105 rws.conn = sc
6106 rws.bw = bwSave
6107 rws.bw.Reset(http2chunkWriter{rws})
6108 rws.stream = st
6109 rws.req = req
6110 return &http2responseWriter{rws: rws}
6111 }
6112
6113 type http2unstartedHandler struct {
6114 streamID uint32
6115 rw *http2responseWriter
6116 req *Request
6117 handler func(ResponseWriter, *Request)
6118 }
6119
6120
6121
6122 func (sc *http2serverConn) scheduleHandler(streamID uint32, rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request)) error {
6123 sc.serveG.check()
6124 maxHandlers := sc.advMaxStreams
6125 if sc.curHandlers < maxHandlers {
6126 sc.curHandlers++
6127 go sc.runHandler(rw, req, handler)
6128 return nil
6129 }
6130 if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) {
6131 return sc.countError("too_many_early_resets", http2ConnectionError(http2ErrCodeEnhanceYourCalm))
6132 }
6133 sc.unstartedHandlers = append(sc.unstartedHandlers, http2unstartedHandler{
6134 streamID: streamID,
6135 rw: rw,
6136 req: req,
6137 handler: handler,
6138 })
6139 return nil
6140 }
6141
6142 func (sc *http2serverConn) handlerDone() {
6143 sc.serveG.check()
6144 sc.curHandlers--
6145 i := 0
6146 maxHandlers := sc.advMaxStreams
6147 for ; i < len(sc.unstartedHandlers); i++ {
6148 u := sc.unstartedHandlers[i]
6149 if sc.streams[u.streamID] == nil {
6150
6151 continue
6152 }
6153 if sc.curHandlers >= maxHandlers {
6154 break
6155 }
6156 sc.curHandlers++
6157 go sc.runHandler(u.rw, u.req, u.handler)
6158 sc.unstartedHandlers[i] = http2unstartedHandler{}
6159 }
6160 sc.unstartedHandlers = sc.unstartedHandlers[i:]
6161 if len(sc.unstartedHandlers) == 0 {
6162 sc.unstartedHandlers = nil
6163 }
6164 }
6165
6166
6167 func (sc *http2serverConn) runHandler(rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request)) {
6168 defer sc.sendServeMsg(http2handlerDoneMsg)
6169 didPanic := true
6170 defer func() {
6171 rw.rws.stream.cancelCtx()
6172 if req.MultipartForm != nil {
6173 req.MultipartForm.RemoveAll()
6174 }
6175 if didPanic {
6176 e := recover()
6177 sc.writeFrameFromHandler(http2FrameWriteRequest{
6178 write: http2handlerPanicRST{rw.rws.stream.id},
6179 stream: rw.rws.stream,
6180 })
6181
6182 if e != nil && e != ErrAbortHandler {
6183 const size = 64 << 10
6184 buf := make([]byte, size)
6185 buf = buf[:runtime.Stack(buf, false)]
6186 sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
6187 }
6188 return
6189 }
6190 rw.handlerDone()
6191 }()
6192 handler(rw, req)
6193 didPanic = false
6194 }
6195
6196 func http2handleHeaderListTooLong(w ResponseWriter, r *Request) {
6197
6198
6199
6200
6201 const statusRequestHeaderFieldsTooLarge = 431
6202 w.WriteHeader(statusRequestHeaderFieldsTooLarge)
6203 io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
6204 }
6205
6206
6207
6208 func (sc *http2serverConn) writeHeaders(st *http2stream, headerData *http2writeResHeaders) error {
6209 sc.serveG.checkNotOn()
6210 var errc chan error
6211 if headerData.h != nil {
6212
6213
6214
6215
6216 errc = http2errChanPool.Get().(chan error)
6217 }
6218 if err := sc.writeFrameFromHandler(http2FrameWriteRequest{
6219 write: headerData,
6220 stream: st,
6221 done: errc,
6222 }); err != nil {
6223 return err
6224 }
6225 if errc != nil {
6226 select {
6227 case err := <-errc:
6228 http2errChanPool.Put(errc)
6229 return err
6230 case <-sc.doneServing:
6231 return http2errClientDisconnected
6232 case <-st.cw:
6233 return http2errStreamClosed
6234 }
6235 }
6236 return nil
6237 }
6238
6239
6240 func (sc *http2serverConn) write100ContinueHeaders(st *http2stream) {
6241 sc.writeFrameFromHandler(http2FrameWriteRequest{
6242 write: http2write100ContinueHeadersFrame{st.id},
6243 stream: st,
6244 })
6245 }
6246
6247
6248
6249 type http2bodyReadMsg struct {
6250 st *http2stream
6251 n int
6252 }
6253
6254
6255
6256
6257 func (sc *http2serverConn) noteBodyReadFromHandler(st *http2stream, n int, err error) {
6258 sc.serveG.checkNotOn()
6259 if n > 0 {
6260 select {
6261 case sc.bodyReadCh <- http2bodyReadMsg{st, n}:
6262 case <-sc.doneServing:
6263 }
6264 }
6265 }
6266
6267 func (sc *http2serverConn) noteBodyRead(st *http2stream, n int) {
6268 sc.serveG.check()
6269 sc.sendWindowUpdate(nil, n)
6270 if st.state != http2stateHalfClosedRemote && st.state != http2stateClosed {
6271
6272
6273 sc.sendWindowUpdate(st, n)
6274 }
6275 }
6276
6277
6278 func (sc *http2serverConn) sendWindowUpdate32(st *http2stream, n int32) {
6279 sc.sendWindowUpdate(st, int(n))
6280 }
6281
6282
6283 func (sc *http2serverConn) sendWindowUpdate(st *http2stream, n int) {
6284 sc.serveG.check()
6285 var streamID uint32
6286 var send int32
6287 if st == nil {
6288 send = sc.inflow.add(n)
6289 } else {
6290 streamID = st.id
6291 send = st.inflow.add(n)
6292 }
6293 if send == 0 {
6294 return
6295 }
6296 sc.writeFrame(http2FrameWriteRequest{
6297 write: http2writeWindowUpdate{streamID: streamID, n: uint32(send)},
6298 stream: st,
6299 })
6300 }
6301
6302
6303
6304 type http2requestBody struct {
6305 _ http2incomparable
6306 stream *http2stream
6307 conn *http2serverConn
6308 closeOnce sync.Once
6309 sawEOF bool
6310 pipe *http2pipe
6311 needsContinue bool
6312 }
6313
6314 func (b *http2requestBody) Close() error {
6315 b.closeOnce.Do(func() {
6316 if b.pipe != nil {
6317 b.pipe.BreakWithError(http2errClosedBody)
6318 }
6319 })
6320 return nil
6321 }
6322
6323 func (b *http2requestBody) Read(p []byte) (n int, err error) {
6324 if b.needsContinue {
6325 b.needsContinue = false
6326 b.conn.write100ContinueHeaders(b.stream)
6327 }
6328 if b.pipe == nil || b.sawEOF {
6329 return 0, io.EOF
6330 }
6331 n, err = b.pipe.Read(p)
6332 if err == io.EOF {
6333 b.sawEOF = true
6334 }
6335 if b.conn == nil && http2inTests {
6336 return
6337 }
6338 b.conn.noteBodyReadFromHandler(b.stream, n, err)
6339 return
6340 }
6341
6342
6343
6344
6345
6346
6347
6348 type http2responseWriter struct {
6349 rws *http2responseWriterState
6350 }
6351
6352
6353 var (
6354 _ CloseNotifier = (*http2responseWriter)(nil)
6355 _ Flusher = (*http2responseWriter)(nil)
6356 _ http2stringWriter = (*http2responseWriter)(nil)
6357 )
6358
6359 type http2responseWriterState struct {
6360
6361 stream *http2stream
6362 req *Request
6363 conn *http2serverConn
6364
6365
6366 bw *bufio.Writer
6367
6368
6369 handlerHeader Header
6370 snapHeader Header
6371 trailers []string
6372 status int
6373 wroteHeader bool
6374 sentHeader bool
6375 handlerDone bool
6376
6377 sentContentLen int64
6378 wroteBytes int64
6379
6380 closeNotifierMu sync.Mutex
6381 closeNotifierCh chan bool
6382 }
6383
6384 type http2chunkWriter struct{ rws *http2responseWriterState }
6385
6386 func (cw http2chunkWriter) Write(p []byte) (n int, err error) {
6387 n, err = cw.rws.writeChunk(p)
6388 if err == http2errStreamClosed {
6389
6390
6391 err = cw.rws.stream.closeErr
6392 }
6393 return n, err
6394 }
6395
6396 func (rws *http2responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 }
6397
6398 func (rws *http2responseWriterState) hasNonemptyTrailers() bool {
6399 for _, trailer := range rws.trailers {
6400 if _, ok := rws.handlerHeader[trailer]; ok {
6401 return true
6402 }
6403 }
6404 return false
6405 }
6406
6407
6408
6409
6410 func (rws *http2responseWriterState) declareTrailer(k string) {
6411 k = CanonicalHeaderKey(k)
6412 if !httpguts.ValidTrailerHeader(k) {
6413
6414 rws.conn.logf("ignoring invalid trailer %q", k)
6415 return
6416 }
6417 if !http2strSliceContains(rws.trailers, k) {
6418 rws.trailers = append(rws.trailers, k)
6419 }
6420 }
6421
6422
6423
6424
6425
6426
6427
6428 func (rws *http2responseWriterState) writeChunk(p []byte) (n int, err error) {
6429 if !rws.wroteHeader {
6430 rws.writeHeader(200)
6431 }
6432
6433 if rws.handlerDone {
6434 rws.promoteUndeclaredTrailers()
6435 }
6436
6437 isHeadResp := rws.req.Method == "HEAD"
6438 if !rws.sentHeader {
6439 rws.sentHeader = true
6440 var ctype, clen string
6441 if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
6442 rws.snapHeader.Del("Content-Length")
6443 if cl, err := strconv.ParseUint(clen, 10, 63); err == nil {
6444 rws.sentContentLen = int64(cl)
6445 } else {
6446 clen = ""
6447 }
6448 }
6449 _, hasContentLength := rws.snapHeader["Content-Length"]
6450 if !hasContentLength && clen == "" && rws.handlerDone && http2bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
6451 clen = strconv.Itoa(len(p))
6452 }
6453 _, hasContentType := rws.snapHeader["Content-Type"]
6454
6455
6456 ce := rws.snapHeader.Get("Content-Encoding")
6457 hasCE := len(ce) > 0
6458 if !hasCE && !hasContentType && http2bodyAllowedForStatus(rws.status) && len(p) > 0 {
6459 ctype = DetectContentType(p)
6460 }
6461 var date string
6462 if _, ok := rws.snapHeader["Date"]; !ok {
6463
6464 date = time.Now().UTC().Format(TimeFormat)
6465 }
6466
6467 for _, v := range rws.snapHeader["Trailer"] {
6468 http2foreachHeaderElement(v, rws.declareTrailer)
6469 }
6470
6471
6472
6473
6474
6475
6476 if _, ok := rws.snapHeader["Connection"]; ok {
6477 v := rws.snapHeader.Get("Connection")
6478 delete(rws.snapHeader, "Connection")
6479 if v == "close" {
6480 rws.conn.startGracefulShutdown()
6481 }
6482 }
6483
6484 endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
6485 err = rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
6486 streamID: rws.stream.id,
6487 httpResCode: rws.status,
6488 h: rws.snapHeader,
6489 endStream: endStream,
6490 contentType: ctype,
6491 contentLength: clen,
6492 date: date,
6493 })
6494 if err != nil {
6495 return 0, err
6496 }
6497 if endStream {
6498 return 0, nil
6499 }
6500 }
6501 if isHeadResp {
6502 return len(p), nil
6503 }
6504 if len(p) == 0 && !rws.handlerDone {
6505 return 0, nil
6506 }
6507
6508
6509
6510 hasNonemptyTrailers := rws.hasNonemptyTrailers()
6511 endStream := rws.handlerDone && !hasNonemptyTrailers
6512 if len(p) > 0 || endStream {
6513
6514 if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
6515 return 0, err
6516 }
6517 }
6518
6519 if rws.handlerDone && hasNonemptyTrailers {
6520 err = rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
6521 streamID: rws.stream.id,
6522 h: rws.handlerHeader,
6523 trailers: rws.trailers,
6524 endStream: true,
6525 })
6526 return len(p), err
6527 }
6528 return len(p), nil
6529 }
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544 const http2TrailerPrefix = "Trailer:"
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567 func (rws *http2responseWriterState) promoteUndeclaredTrailers() {
6568 for k, vv := range rws.handlerHeader {
6569 if !strings.HasPrefix(k, http2TrailerPrefix) {
6570 continue
6571 }
6572 trailerKey := strings.TrimPrefix(k, http2TrailerPrefix)
6573 rws.declareTrailer(trailerKey)
6574 rws.handlerHeader[CanonicalHeaderKey(trailerKey)] = vv
6575 }
6576
6577 if len(rws.trailers) > 1 {
6578 sorter := http2sorterPool.Get().(*http2sorter)
6579 sorter.SortStrings(rws.trailers)
6580 http2sorterPool.Put(sorter)
6581 }
6582 }
6583
6584 func (w *http2responseWriter) SetReadDeadline(deadline time.Time) error {
6585 st := w.rws.stream
6586 if !deadline.IsZero() && deadline.Before(time.Now()) {
6587
6588
6589 st.onReadTimeout()
6590 return nil
6591 }
6592 w.rws.conn.sendServeMsg(func(sc *http2serverConn) {
6593 if st.readDeadline != nil {
6594 if !st.readDeadline.Stop() {
6595
6596 return
6597 }
6598 }
6599 if deadline.IsZero() {
6600 st.readDeadline = nil
6601 } else if st.readDeadline == nil {
6602 st.readDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onReadTimeout)
6603 } else {
6604 st.readDeadline.Reset(deadline.Sub(time.Now()))
6605 }
6606 })
6607 return nil
6608 }
6609
6610 func (w *http2responseWriter) SetWriteDeadline(deadline time.Time) error {
6611 st := w.rws.stream
6612 if !deadline.IsZero() && deadline.Before(time.Now()) {
6613
6614
6615 st.onWriteTimeout()
6616 return nil
6617 }
6618 w.rws.conn.sendServeMsg(func(sc *http2serverConn) {
6619 if st.writeDeadline != nil {
6620 if !st.writeDeadline.Stop() {
6621
6622 return
6623 }
6624 }
6625 if deadline.IsZero() {
6626 st.writeDeadline = nil
6627 } else if st.writeDeadline == nil {
6628 st.writeDeadline = time.AfterFunc(deadline.Sub(time.Now()), st.onWriteTimeout)
6629 } else {
6630 st.writeDeadline.Reset(deadline.Sub(time.Now()))
6631 }
6632 })
6633 return nil
6634 }
6635
6636 func (w *http2responseWriter) Flush() {
6637 w.FlushError()
6638 }
6639
6640 func (w *http2responseWriter) FlushError() error {
6641 rws := w.rws
6642 if rws == nil {
6643 panic("Header called after Handler finished")
6644 }
6645 var err error
6646 if rws.bw.Buffered() > 0 {
6647 err = rws.bw.Flush()
6648 } else {
6649
6650
6651
6652
6653 _, err = http2chunkWriter{rws}.Write(nil)
6654 if err == nil {
6655 select {
6656 case <-rws.stream.cw:
6657 err = rws.stream.closeErr
6658 default:
6659 }
6660 }
6661 }
6662 return err
6663 }
6664
6665 func (w *http2responseWriter) CloseNotify() <-chan bool {
6666 rws := w.rws
6667 if rws == nil {
6668 panic("CloseNotify called after Handler finished")
6669 }
6670 rws.closeNotifierMu.Lock()
6671 ch := rws.closeNotifierCh
6672 if ch == nil {
6673 ch = make(chan bool, 1)
6674 rws.closeNotifierCh = ch
6675 cw := rws.stream.cw
6676 go func() {
6677 cw.Wait()
6678 ch <- true
6679 }()
6680 }
6681 rws.closeNotifierMu.Unlock()
6682 return ch
6683 }
6684
6685 func (w *http2responseWriter) Header() Header {
6686 rws := w.rws
6687 if rws == nil {
6688 panic("Header called after Handler finished")
6689 }
6690 if rws.handlerHeader == nil {
6691 rws.handlerHeader = make(Header)
6692 }
6693 return rws.handlerHeader
6694 }
6695
6696
6697 func http2checkWriteHeaderCode(code int) {
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708 if code < 100 || code > 999 {
6709 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
6710 }
6711 }
6712
6713 func (w *http2responseWriter) WriteHeader(code int) {
6714 rws := w.rws
6715 if rws == nil {
6716 panic("WriteHeader called after Handler finished")
6717 }
6718 rws.writeHeader(code)
6719 }
6720
6721 func (rws *http2responseWriterState) writeHeader(code int) {
6722 if rws.wroteHeader {
6723 return
6724 }
6725
6726 http2checkWriteHeaderCode(code)
6727
6728
6729 if code >= 100 && code <= 199 {
6730
6731 h := rws.handlerHeader
6732
6733 _, cl := h["Content-Length"]
6734 _, te := h["Transfer-Encoding"]
6735 if cl || te {
6736 h = h.Clone()
6737 h.Del("Content-Length")
6738 h.Del("Transfer-Encoding")
6739 }
6740
6741 rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
6742 streamID: rws.stream.id,
6743 httpResCode: code,
6744 h: h,
6745 endStream: rws.handlerDone && !rws.hasTrailers(),
6746 })
6747
6748 return
6749 }
6750
6751 rws.wroteHeader = true
6752 rws.status = code
6753 if len(rws.handlerHeader) > 0 {
6754 rws.snapHeader = http2cloneHeader(rws.handlerHeader)
6755 }
6756 }
6757
6758 func http2cloneHeader(h Header) Header {
6759 h2 := make(Header, len(h))
6760 for k, vv := range h {
6761 vv2 := make([]string, len(vv))
6762 copy(vv2, vv)
6763 h2[k] = vv2
6764 }
6765 return h2
6766 }
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776 func (w *http2responseWriter) Write(p []byte) (n int, err error) {
6777 return w.write(len(p), p, "")
6778 }
6779
6780 func (w *http2responseWriter) WriteString(s string) (n int, err error) {
6781 return w.write(len(s), nil, s)
6782 }
6783
6784
6785 func (w *http2responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
6786 rws := w.rws
6787 if rws == nil {
6788 panic("Write called after Handler finished")
6789 }
6790 if !rws.wroteHeader {
6791 w.WriteHeader(200)
6792 }
6793 if !http2bodyAllowedForStatus(rws.status) {
6794 return 0, ErrBodyNotAllowed
6795 }
6796 rws.wroteBytes += int64(len(dataB)) + int64(len(dataS))
6797 if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
6798
6799 return 0, errors.New("http2: handler wrote more than declared Content-Length")
6800 }
6801
6802 if dataB != nil {
6803 return rws.bw.Write(dataB)
6804 } else {
6805 return rws.bw.WriteString(dataS)
6806 }
6807 }
6808
6809 func (w *http2responseWriter) handlerDone() {
6810 rws := w.rws
6811 rws.handlerDone = true
6812 w.Flush()
6813 w.rws = nil
6814 http2responseWriterStatePool.Put(rws)
6815 }
6816
6817
6818 var (
6819 http2ErrRecursivePush = errors.New("http2: recursive push not allowed")
6820 http2ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
6821 )
6822
6823 var _ Pusher = (*http2responseWriter)(nil)
6824
6825 func (w *http2responseWriter) Push(target string, opts *PushOptions) error {
6826 st := w.rws.stream
6827 sc := st.sc
6828 sc.serveG.checkNotOn()
6829
6830
6831
6832 if st.isPushed() {
6833 return http2ErrRecursivePush
6834 }
6835
6836 if opts == nil {
6837 opts = new(PushOptions)
6838 }
6839
6840
6841 if opts.Method == "" {
6842 opts.Method = "GET"
6843 }
6844 if opts.Header == nil {
6845 opts.Header = Header{}
6846 }
6847 wantScheme := "http"
6848 if w.rws.req.TLS != nil {
6849 wantScheme = "https"
6850 }
6851
6852
6853 u, err := url.Parse(target)
6854 if err != nil {
6855 return err
6856 }
6857 if u.Scheme == "" {
6858 if !strings.HasPrefix(target, "/") {
6859 return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
6860 }
6861 u.Scheme = wantScheme
6862 u.Host = w.rws.req.Host
6863 } else {
6864 if u.Scheme != wantScheme {
6865 return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
6866 }
6867 if u.Host == "" {
6868 return errors.New("URL must have a host")
6869 }
6870 }
6871 for k := range opts.Header {
6872 if strings.HasPrefix(k, ":") {
6873 return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
6874 }
6875
6876
6877
6878
6879 if http2asciiEqualFold(k, "content-length") ||
6880 http2asciiEqualFold(k, "content-encoding") ||
6881 http2asciiEqualFold(k, "trailer") ||
6882 http2asciiEqualFold(k, "te") ||
6883 http2asciiEqualFold(k, "expect") ||
6884 http2asciiEqualFold(k, "host") {
6885 return fmt.Errorf("promised request headers cannot include %q", k)
6886 }
6887 }
6888 if err := http2checkValidHTTP2RequestHeaders(opts.Header); err != nil {
6889 return err
6890 }
6891
6892
6893
6894
6895 if opts.Method != "GET" && opts.Method != "HEAD" {
6896 return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
6897 }
6898
6899 msg := &http2startPushRequest{
6900 parent: st,
6901 method: opts.Method,
6902 url: u,
6903 header: http2cloneHeader(opts.Header),
6904 done: http2errChanPool.Get().(chan error),
6905 }
6906
6907 select {
6908 case <-sc.doneServing:
6909 return http2errClientDisconnected
6910 case <-st.cw:
6911 return http2errStreamClosed
6912 case sc.serveMsgCh <- msg:
6913 }
6914
6915 select {
6916 case <-sc.doneServing:
6917 return http2errClientDisconnected
6918 case <-st.cw:
6919 return http2errStreamClosed
6920 case err := <-msg.done:
6921 http2errChanPool.Put(msg.done)
6922 return err
6923 }
6924 }
6925
6926 type http2startPushRequest struct {
6927 parent *http2stream
6928 method string
6929 url *url.URL
6930 header Header
6931 done chan error
6932 }
6933
6934 func (sc *http2serverConn) startPush(msg *http2startPushRequest) {
6935 sc.serveG.check()
6936
6937
6938
6939
6940 if msg.parent.state != http2stateOpen && msg.parent.state != http2stateHalfClosedRemote {
6941
6942 msg.done <- http2errStreamClosed
6943 return
6944 }
6945
6946
6947 if !sc.pushEnabled {
6948 msg.done <- ErrNotSupported
6949 return
6950 }
6951
6952
6953
6954
6955 allocatePromisedID := func() (uint32, error) {
6956 sc.serveG.check()
6957
6958
6959
6960 if !sc.pushEnabled {
6961 return 0, ErrNotSupported
6962 }
6963
6964 if sc.curPushedStreams+1 > sc.clientMaxStreams {
6965 return 0, http2ErrPushLimitReached
6966 }
6967
6968
6969
6970
6971
6972 if sc.maxPushPromiseID+2 >= 1<<31 {
6973 sc.startGracefulShutdownInternal()
6974 return 0, http2ErrPushLimitReached
6975 }
6976 sc.maxPushPromiseID += 2
6977 promisedID := sc.maxPushPromiseID
6978
6979
6980
6981
6982
6983
6984 promised := sc.newStream(promisedID, msg.parent.id, http2stateHalfClosedRemote)
6985 rw, req, err := sc.newWriterAndRequestNoBody(promised, http2requestParam{
6986 method: msg.method,
6987 scheme: msg.url.Scheme,
6988 authority: msg.url.Host,
6989 path: msg.url.RequestURI(),
6990 header: http2cloneHeader(msg.header),
6991 })
6992 if err != nil {
6993
6994 panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
6995 }
6996
6997 sc.curHandlers++
6998 go sc.runHandler(rw, req, sc.handler.ServeHTTP)
6999 return promisedID, nil
7000 }
7001
7002 sc.writeFrame(http2FrameWriteRequest{
7003 write: &http2writePushPromise{
7004 streamID: msg.parent.id,
7005 method: msg.method,
7006 url: msg.url,
7007 h: msg.header,
7008 allocatePromisedID: allocatePromisedID,
7009 },
7010 stream: msg.parent,
7011 done: msg.done,
7012 })
7013 }
7014
7015
7016
7017 func http2foreachHeaderElement(v string, fn func(string)) {
7018 v = textproto.TrimString(v)
7019 if v == "" {
7020 return
7021 }
7022 if !strings.Contains(v, ",") {
7023 fn(v)
7024 return
7025 }
7026 for _, f := range strings.Split(v, ",") {
7027 if f = textproto.TrimString(f); f != "" {
7028 fn(f)
7029 }
7030 }
7031 }
7032
7033
7034 var http2connHeaders = []string{
7035 "Connection",
7036 "Keep-Alive",
7037 "Proxy-Connection",
7038 "Transfer-Encoding",
7039 "Upgrade",
7040 }
7041
7042
7043
7044
7045 func http2checkValidHTTP2RequestHeaders(h Header) error {
7046 for _, k := range http2connHeaders {
7047 if _, ok := h[k]; ok {
7048 return fmt.Errorf("request header %q is not valid in HTTP/2", k)
7049 }
7050 }
7051 te := h["Te"]
7052 if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
7053 return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
7054 }
7055 return nil
7056 }
7057
7058 func http2new400Handler(err error) HandlerFunc {
7059 return func(w ResponseWriter, r *Request) {
7060 Error(w, err.Error(), StatusBadRequest)
7061 }
7062 }
7063
7064
7065
7066
7067 func http2h1ServerKeepAlivesDisabled(hs *Server) bool {
7068 var x interface{} = hs
7069 type I interface {
7070 doKeepAlives() bool
7071 }
7072 if hs, ok := x.(I); ok {
7073 return !hs.doKeepAlives()
7074 }
7075 return false
7076 }
7077
7078 func (sc *http2serverConn) countError(name string, err error) error {
7079 if sc == nil || sc.srv == nil {
7080 return err
7081 }
7082 f := sc.srv.CountError
7083 if f == nil {
7084 return err
7085 }
7086 var typ string
7087 var code http2ErrCode
7088 switch e := err.(type) {
7089 case http2ConnectionError:
7090 typ = "conn"
7091 code = http2ErrCode(e)
7092 case http2StreamError:
7093 typ = "stream"
7094 code = http2ErrCode(e.Code)
7095 default:
7096 return err
7097 }
7098 codeStr := http2errCodeName[code]
7099 if codeStr == "" {
7100 codeStr = strconv.Itoa(int(code))
7101 }
7102 f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
7103 return err
7104 }
7105
7106 const (
7107
7108
7109 http2transportDefaultConnFlow = 1 << 30
7110
7111
7112
7113
7114 http2transportDefaultStreamFlow = 4 << 20
7115
7116 http2defaultUserAgent = "Go-http-client/2.0"
7117
7118
7119
7120
7121 http2initialMaxConcurrentStreams = 100
7122
7123
7124
7125 http2defaultMaxConcurrentStreams = 1000
7126 )
7127
7128
7129
7130
7131
7132 type http2Transport struct {
7133
7134
7135
7136
7137
7138
7139
7140 DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error)
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150 DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
7151
7152
7153
7154 TLSClientConfig *tls.Config
7155
7156
7157
7158 ConnPool http2ClientConnPool
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168 DisableCompression bool
7169
7170
7171
7172 AllowHTTP bool
7173
7174
7175
7176
7177
7178
7179
7180
7181 MaxHeaderListSize uint32
7182
7183
7184
7185
7186
7187
7188
7189
7190 MaxReadFrameSize uint32
7191
7192
7193
7194
7195
7196
7197 MaxDecoderHeaderTableSize uint32
7198
7199
7200
7201
7202
7203 MaxEncoderHeaderTableSize uint32
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213 StrictMaxConcurrentStreams bool
7214
7215
7216
7217
7218
7219
7220
7221 ReadIdleTimeout time.Duration
7222
7223
7224
7225
7226 PingTimeout time.Duration
7227
7228
7229
7230
7231 WriteByteTimeout time.Duration
7232
7233
7234
7235
7236
7237 CountError func(errType string)
7238
7239
7240
7241
7242 t1 *Transport
7243
7244 connPoolOnce sync.Once
7245 connPoolOrDef http2ClientConnPool
7246 }
7247
7248 func (t *http2Transport) maxHeaderListSize() uint32 {
7249 if t.MaxHeaderListSize == 0 {
7250 return 10 << 20
7251 }
7252 if t.MaxHeaderListSize == 0xffffffff {
7253 return 0
7254 }
7255 return t.MaxHeaderListSize
7256 }
7257
7258 func (t *http2Transport) maxFrameReadSize() uint32 {
7259 if t.MaxReadFrameSize == 0 {
7260 return 0
7261 }
7262 if t.MaxReadFrameSize < http2minMaxFrameSize {
7263 return http2minMaxFrameSize
7264 }
7265 if t.MaxReadFrameSize > http2maxFrameSize {
7266 return http2maxFrameSize
7267 }
7268 return t.MaxReadFrameSize
7269 }
7270
7271 func (t *http2Transport) disableCompression() bool {
7272 return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
7273 }
7274
7275 func (t *http2Transport) pingTimeout() time.Duration {
7276 if t.PingTimeout == 0 {
7277 return 15 * time.Second
7278 }
7279 return t.PingTimeout
7280
7281 }
7282
7283
7284
7285
7286
7287 func http2ConfigureTransport(t1 *Transport) error {
7288 _, err := http2ConfigureTransports(t1)
7289 return err
7290 }
7291
7292
7293
7294
7295 func http2ConfigureTransports(t1 *Transport) (*http2Transport, error) {
7296 return http2configureTransports(t1)
7297 }
7298
7299 func http2configureTransports(t1 *Transport) (*http2Transport, error) {
7300 connPool := new(http2clientConnPool)
7301 t2 := &http2Transport{
7302 ConnPool: http2noDialClientConnPool{connPool},
7303 t1: t1,
7304 }
7305 connPool.t = t2
7306 if err := http2registerHTTPSProtocol(t1, http2noDialH2RoundTripper{t2}); err != nil {
7307 return nil, err
7308 }
7309 if t1.TLSClientConfig == nil {
7310 t1.TLSClientConfig = new(tls.Config)
7311 }
7312 if !http2strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
7313 t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
7314 }
7315 if !http2strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
7316 t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
7317 }
7318 upgradeFn := func(authority string, c *tls.Conn) RoundTripper {
7319 addr := http2authorityAddr("https", authority)
7320 if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
7321 go c.Close()
7322 return http2erringRoundTripper{err}
7323 } else if !used {
7324
7325
7326
7327
7328 go c.Close()
7329 }
7330 return t2
7331 }
7332 if m := t1.TLSNextProto; len(m) == 0 {
7333 t1.TLSNextProto = map[string]func(string, *tls.Conn) RoundTripper{
7334 "h2": upgradeFn,
7335 }
7336 } else {
7337 m["h2"] = upgradeFn
7338 }
7339 return t2, nil
7340 }
7341
7342 func (t *http2Transport) connPool() http2ClientConnPool {
7343 t.connPoolOnce.Do(t.initConnPool)
7344 return t.connPoolOrDef
7345 }
7346
7347 func (t *http2Transport) initConnPool() {
7348 if t.ConnPool != nil {
7349 t.connPoolOrDef = t.ConnPool
7350 } else {
7351 t.connPoolOrDef = &http2clientConnPool{t: t}
7352 }
7353 }
7354
7355
7356
7357 type http2ClientConn struct {
7358 t *http2Transport
7359 tconn net.Conn
7360 tlsState *tls.ConnectionState
7361 reused uint32
7362 singleUse bool
7363 getConnCalled bool
7364
7365
7366 readerDone chan struct{}
7367 readerErr error
7368
7369 idleTimeout time.Duration
7370 idleTimer *time.Timer
7371
7372 mu sync.Mutex
7373 cond *sync.Cond
7374 flow http2outflow
7375 inflow http2inflow
7376 doNotReuse bool
7377 closing bool
7378 closed bool
7379 seenSettings bool
7380 wantSettingsAck bool
7381 goAway *http2GoAwayFrame
7382 goAwayDebug string
7383 streams map[uint32]*http2clientStream
7384 streamsReserved int
7385 nextStreamID uint32
7386 pendingRequests int
7387 pings map[[8]byte]chan struct{}
7388 br *bufio.Reader
7389 lastActive time.Time
7390 lastIdle time.Time
7391
7392 maxFrameSize uint32
7393 maxConcurrentStreams uint32
7394 peerMaxHeaderListSize uint64
7395 peerMaxHeaderTableSize uint32
7396 initialWindowSize uint32
7397
7398
7399
7400
7401 reqHeaderMu chan struct{}
7402
7403
7404
7405
7406 wmu sync.Mutex
7407 bw *bufio.Writer
7408 fr *http2Framer
7409 werr error
7410 hbuf bytes.Buffer
7411 henc *hpack.Encoder
7412 }
7413
7414
7415
7416 type http2clientStream struct {
7417 cc *http2ClientConn
7418
7419
7420 ctx context.Context
7421 reqCancel <-chan struct{}
7422
7423 trace *httptrace.ClientTrace
7424 ID uint32
7425 bufPipe http2pipe
7426 requestedGzip bool
7427 isHead bool
7428
7429 abortOnce sync.Once
7430 abort chan struct{}
7431 abortErr error
7432
7433 peerClosed chan struct{}
7434 donec chan struct{}
7435 on100 chan struct{}
7436
7437 respHeaderRecv chan struct{}
7438 res *Response
7439
7440 flow http2outflow
7441 inflow http2inflow
7442 bytesRemain int64
7443 readErr error
7444
7445 reqBody io.ReadCloser
7446 reqBodyContentLength int64
7447 reqBodyClosed chan struct{}
7448
7449
7450 sentEndStream bool
7451 sentHeaders bool
7452
7453
7454 firstByte bool
7455 pastHeaders bool
7456 pastTrailers bool
7457 num1xx uint8
7458 readClosed bool
7459 readAborted bool
7460
7461 trailer Header
7462 resTrailer *Header
7463 }
7464
7465 var http2got1xxFuncForTests func(int, textproto.MIMEHeader) error
7466
7467
7468
7469 func (cs *http2clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
7470 if fn := http2got1xxFuncForTests; fn != nil {
7471 return fn
7472 }
7473 return http2traceGot1xxResponseFunc(cs.trace)
7474 }
7475
7476 func (cs *http2clientStream) abortStream(err error) {
7477 cs.cc.mu.Lock()
7478 defer cs.cc.mu.Unlock()
7479 cs.abortStreamLocked(err)
7480 }
7481
7482 func (cs *http2clientStream) abortStreamLocked(err error) {
7483 cs.abortOnce.Do(func() {
7484 cs.abortErr = err
7485 close(cs.abort)
7486 })
7487 if cs.reqBody != nil {
7488 cs.closeReqBodyLocked()
7489 }
7490
7491 if cs.cc.cond != nil {
7492
7493 cs.cc.cond.Broadcast()
7494 }
7495 }
7496
7497 func (cs *http2clientStream) abortRequestBodyWrite() {
7498 cc := cs.cc
7499 cc.mu.Lock()
7500 defer cc.mu.Unlock()
7501 if cs.reqBody != nil && cs.reqBodyClosed == nil {
7502 cs.closeReqBodyLocked()
7503 cc.cond.Broadcast()
7504 }
7505 }
7506
7507 func (cs *http2clientStream) closeReqBodyLocked() {
7508 if cs.reqBodyClosed != nil {
7509 return
7510 }
7511 cs.reqBodyClosed = make(chan struct{})
7512 reqBodyClosed := cs.reqBodyClosed
7513 go func() {
7514 cs.reqBody.Close()
7515 close(reqBodyClosed)
7516 }()
7517 }
7518
7519 type http2stickyErrWriter struct {
7520 conn net.Conn
7521 timeout time.Duration
7522 err *error
7523 }
7524
7525 func (sew http2stickyErrWriter) Write(p []byte) (n int, err error) {
7526 if *sew.err != nil {
7527 return 0, *sew.err
7528 }
7529 for {
7530 if sew.timeout != 0 {
7531 sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout))
7532 }
7533 nn, err := sew.conn.Write(p[n:])
7534 n += nn
7535 if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) {
7536
7537 continue
7538 }
7539 if sew.timeout != 0 {
7540 sew.conn.SetWriteDeadline(time.Time{})
7541 }
7542 *sew.err = err
7543 return n, err
7544 }
7545 }
7546
7547
7548
7549
7550
7551
7552
7553 type http2noCachedConnError struct{}
7554
7555 func (http2noCachedConnError) IsHTTP2NoCachedConnError() {}
7556
7557 func (http2noCachedConnError) Error() string { return "http2: no cached connection was available" }
7558
7559
7560
7561
7562 func http2isNoCachedConnError(err error) bool {
7563 _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
7564 return ok
7565 }
7566
7567 var http2ErrNoCachedConn error = http2noCachedConnError{}
7568
7569
7570 type http2RoundTripOpt struct {
7571
7572
7573
7574
7575 OnlyCachedConn bool
7576 }
7577
7578 func (t *http2Transport) RoundTrip(req *Request) (*Response, error) {
7579 return t.RoundTripOpt(req, http2RoundTripOpt{})
7580 }
7581
7582
7583
7584 func http2authorityAddr(scheme string, authority string) (addr string) {
7585 host, port, err := net.SplitHostPort(authority)
7586 if err != nil {
7587 host = authority
7588 port = ""
7589 }
7590 if port == "" {
7591 port = "443"
7592 if scheme == "http" {
7593 port = "80"
7594 }
7595 }
7596 if a, err := idna.ToASCII(host); err == nil {
7597 host = a
7598 }
7599
7600 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
7601 return host + ":" + port
7602 }
7603 return net.JoinHostPort(host, port)
7604 }
7605
7606 var http2retryBackoffHook func(time.Duration) *time.Timer
7607
7608 func http2backoffNewTimer(d time.Duration) *time.Timer {
7609 if http2retryBackoffHook != nil {
7610 return http2retryBackoffHook(d)
7611 }
7612 return time.NewTimer(d)
7613 }
7614
7615
7616 func (t *http2Transport) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error) {
7617 if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
7618 return nil, errors.New("http2: unsupported scheme")
7619 }
7620
7621 addr := http2authorityAddr(req.URL.Scheme, req.URL.Host)
7622 for retry := 0; ; retry++ {
7623 cc, err := t.connPool().GetClientConn(req, addr)
7624 if err != nil {
7625 t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
7626 return nil, err
7627 }
7628 reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
7629 http2traceGotConn(req, cc, reused)
7630 res, err := cc.RoundTrip(req)
7631 if err != nil && retry <= 6 {
7632 roundTripErr := err
7633 if req, err = http2shouldRetryRequest(req, err); err == nil {
7634
7635 if retry == 0 {
7636 t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
7637 continue
7638 }
7639 backoff := float64(uint(1) << (uint(retry) - 1))
7640 backoff += backoff * (0.1 * mathrand.Float64())
7641 d := time.Second * time.Duration(backoff)
7642 timer := http2backoffNewTimer(d)
7643 select {
7644 case <-timer.C:
7645 t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
7646 continue
7647 case <-req.Context().Done():
7648 timer.Stop()
7649 err = req.Context().Err()
7650 }
7651 }
7652 }
7653 if err != nil {
7654 t.vlogf("RoundTrip failure: %v", err)
7655 return nil, err
7656 }
7657 return res, nil
7658 }
7659 }
7660
7661
7662
7663
7664 func (t *http2Transport) CloseIdleConnections() {
7665 if cp, ok := t.connPool().(http2clientConnPoolIdleCloser); ok {
7666 cp.closeIdleConnections()
7667 }
7668 }
7669
7670 var (
7671 http2errClientConnClosed = errors.New("http2: client conn is closed")
7672 http2errClientConnUnusable = errors.New("http2: client conn not usable")
7673 http2errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
7674 )
7675
7676
7677
7678
7679
7680 func http2shouldRetryRequest(req *Request, err error) (*Request, error) {
7681 if !http2canRetryError(err) {
7682 return nil, err
7683 }
7684
7685
7686 if req.Body == nil || req.Body == NoBody {
7687 return req, nil
7688 }
7689
7690
7691
7692 if req.GetBody != nil {
7693 body, err := req.GetBody()
7694 if err != nil {
7695 return nil, err
7696 }
7697 newReq := *req
7698 newReq.Body = body
7699 return &newReq, nil
7700 }
7701
7702
7703
7704
7705 if err == http2errClientConnUnusable {
7706 return req, nil
7707 }
7708
7709 return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
7710 }
7711
7712 func http2canRetryError(err error) bool {
7713 if err == http2errClientConnUnusable || err == http2errClientConnGotGoAway {
7714 return true
7715 }
7716 if se, ok := err.(http2StreamError); ok {
7717 if se.Code == http2ErrCodeProtocol && se.Cause == http2errFromPeer {
7718
7719 return true
7720 }
7721 return se.Code == http2ErrCodeRefusedStream
7722 }
7723 return false
7724 }
7725
7726 func (t *http2Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*http2ClientConn, error) {
7727 host, _, err := net.SplitHostPort(addr)
7728 if err != nil {
7729 return nil, err
7730 }
7731 tconn, err := t.dialTLS(ctx, "tcp", addr, t.newTLSConfig(host))
7732 if err != nil {
7733 return nil, err
7734 }
7735 return t.newClientConn(tconn, singleUse)
7736 }
7737
7738 func (t *http2Transport) newTLSConfig(host string) *tls.Config {
7739 cfg := new(tls.Config)
7740 if t.TLSClientConfig != nil {
7741 *cfg = *t.TLSClientConfig.Clone()
7742 }
7743 if !http2strSliceContains(cfg.NextProtos, http2NextProtoTLS) {
7744 cfg.NextProtos = append([]string{http2NextProtoTLS}, cfg.NextProtos...)
7745 }
7746 if cfg.ServerName == "" {
7747 cfg.ServerName = host
7748 }
7749 return cfg
7750 }
7751
7752 func (t *http2Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) {
7753 if t.DialTLSContext != nil {
7754 return t.DialTLSContext(ctx, network, addr, tlsCfg)
7755 } else if t.DialTLS != nil {
7756 return t.DialTLS(network, addr, tlsCfg)
7757 }
7758
7759 tlsCn, err := t.dialTLSWithContext(ctx, network, addr, tlsCfg)
7760 if err != nil {
7761 return nil, err
7762 }
7763 state := tlsCn.ConnectionState()
7764 if p := state.NegotiatedProtocol; p != http2NextProtoTLS {
7765 return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, http2NextProtoTLS)
7766 }
7767 if !state.NegotiatedProtocolIsMutual {
7768 return nil, errors.New("http2: could not negotiate protocol mutually")
7769 }
7770 return tlsCn, nil
7771 }
7772
7773
7774
7775 func (t *http2Transport) disableKeepAlives() bool {
7776 return t.t1 != nil && t.t1.DisableKeepAlives
7777 }
7778
7779 func (t *http2Transport) expectContinueTimeout() time.Duration {
7780 if t.t1 == nil {
7781 return 0
7782 }
7783 return t.t1.ExpectContinueTimeout
7784 }
7785
7786 func (t *http2Transport) maxDecoderHeaderTableSize() uint32 {
7787 if v := t.MaxDecoderHeaderTableSize; v > 0 {
7788 return v
7789 }
7790 return http2initialHeaderTableSize
7791 }
7792
7793 func (t *http2Transport) maxEncoderHeaderTableSize() uint32 {
7794 if v := t.MaxEncoderHeaderTableSize; v > 0 {
7795 return v
7796 }
7797 return http2initialHeaderTableSize
7798 }
7799
7800 func (t *http2Transport) NewClientConn(c net.Conn) (*http2ClientConn, error) {
7801 return t.newClientConn(c, t.disableKeepAlives())
7802 }
7803
7804 func (t *http2Transport) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error) {
7805 cc := &http2ClientConn{
7806 t: t,
7807 tconn: c,
7808 readerDone: make(chan struct{}),
7809 nextStreamID: 1,
7810 maxFrameSize: 16 << 10,
7811 initialWindowSize: 65535,
7812 maxConcurrentStreams: http2initialMaxConcurrentStreams,
7813 peerMaxHeaderListSize: 0xffffffffffffffff,
7814 streams: make(map[uint32]*http2clientStream),
7815 singleUse: singleUse,
7816 wantSettingsAck: true,
7817 pings: make(map[[8]byte]chan struct{}),
7818 reqHeaderMu: make(chan struct{}, 1),
7819 }
7820 if d := t.idleConnTimeout(); d != 0 {
7821 cc.idleTimeout = d
7822 cc.idleTimer = time.AfterFunc(d, cc.onIdleTimeout)
7823 }
7824 if http2VerboseLogs {
7825 t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
7826 }
7827
7828 cc.cond = sync.NewCond(&cc.mu)
7829 cc.flow.add(int32(http2initialWindowSize))
7830
7831
7832
7833 cc.bw = bufio.NewWriter(http2stickyErrWriter{
7834 conn: c,
7835 timeout: t.WriteByteTimeout,
7836 err: &cc.werr,
7837 })
7838 cc.br = bufio.NewReader(c)
7839 cc.fr = http2NewFramer(cc.bw, cc.br)
7840 if t.maxFrameReadSize() != 0 {
7841 cc.fr.SetMaxReadFrameSize(t.maxFrameReadSize())
7842 }
7843 if t.CountError != nil {
7844 cc.fr.countError = t.CountError
7845 }
7846 maxHeaderTableSize := t.maxDecoderHeaderTableSize()
7847 cc.fr.ReadMetaHeaders = hpack.NewDecoder(maxHeaderTableSize, nil)
7848 cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
7849
7850 cc.henc = hpack.NewEncoder(&cc.hbuf)
7851 cc.henc.SetMaxDynamicTableSizeLimit(t.maxEncoderHeaderTableSize())
7852 cc.peerMaxHeaderTableSize = http2initialHeaderTableSize
7853
7854 if t.AllowHTTP {
7855 cc.nextStreamID = 3
7856 }
7857
7858 if cs, ok := c.(http2connectionStater); ok {
7859 state := cs.ConnectionState()
7860 cc.tlsState = &state
7861 }
7862
7863 initialSettings := []http2Setting{
7864 {ID: http2SettingEnablePush, Val: 0},
7865 {ID: http2SettingInitialWindowSize, Val: http2transportDefaultStreamFlow},
7866 }
7867 if max := t.maxFrameReadSize(); max != 0 {
7868 initialSettings = append(initialSettings, http2Setting{ID: http2SettingMaxFrameSize, Val: max})
7869 }
7870 if max := t.maxHeaderListSize(); max != 0 {
7871 initialSettings = append(initialSettings, http2Setting{ID: http2SettingMaxHeaderListSize, Val: max})
7872 }
7873 if maxHeaderTableSize != http2initialHeaderTableSize {
7874 initialSettings = append(initialSettings, http2Setting{ID: http2SettingHeaderTableSize, Val: maxHeaderTableSize})
7875 }
7876
7877 cc.bw.Write(http2clientPreface)
7878 cc.fr.WriteSettings(initialSettings...)
7879 cc.fr.WriteWindowUpdate(0, http2transportDefaultConnFlow)
7880 cc.inflow.init(http2transportDefaultConnFlow + http2initialWindowSize)
7881 cc.bw.Flush()
7882 if cc.werr != nil {
7883 cc.Close()
7884 return nil, cc.werr
7885 }
7886
7887 go cc.readLoop()
7888 return cc, nil
7889 }
7890
7891 func (cc *http2ClientConn) healthCheck() {
7892 pingTimeout := cc.t.pingTimeout()
7893
7894
7895 ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
7896 defer cancel()
7897 cc.vlogf("http2: Transport sending health check")
7898 err := cc.Ping(ctx)
7899 if err != nil {
7900 cc.vlogf("http2: Transport health check failure: %v", err)
7901 cc.closeForLostPing()
7902 } else {
7903 cc.vlogf("http2: Transport health check success")
7904 }
7905 }
7906
7907
7908 func (cc *http2ClientConn) SetDoNotReuse() {
7909 cc.mu.Lock()
7910 defer cc.mu.Unlock()
7911 cc.doNotReuse = true
7912 }
7913
7914 func (cc *http2ClientConn) setGoAway(f *http2GoAwayFrame) {
7915 cc.mu.Lock()
7916 defer cc.mu.Unlock()
7917
7918 old := cc.goAway
7919 cc.goAway = f
7920
7921
7922 if cc.goAwayDebug == "" {
7923 cc.goAwayDebug = string(f.DebugData())
7924 }
7925 if old != nil && old.ErrCode != http2ErrCodeNo {
7926 cc.goAway.ErrCode = old.ErrCode
7927 }
7928 last := f.LastStreamID
7929 for streamID, cs := range cc.streams {
7930 if streamID > last {
7931 cs.abortStreamLocked(http2errClientConnGotGoAway)
7932 }
7933 }
7934 }
7935
7936
7937
7938
7939
7940
7941 func (cc *http2ClientConn) CanTakeNewRequest() bool {
7942 cc.mu.Lock()
7943 defer cc.mu.Unlock()
7944 return cc.canTakeNewRequestLocked()
7945 }
7946
7947
7948
7949
7950 func (cc *http2ClientConn) ReserveNewRequest() bool {
7951 cc.mu.Lock()
7952 defer cc.mu.Unlock()
7953 if st := cc.idleStateLocked(); !st.canTakeNewRequest {
7954 return false
7955 }
7956 cc.streamsReserved++
7957 return true
7958 }
7959
7960
7961 type http2ClientConnState struct {
7962
7963 Closed bool
7964
7965
7966
7967
7968
7969 Closing bool
7970
7971
7972 StreamsActive int
7973
7974
7975
7976 StreamsReserved int
7977
7978
7979
7980
7981 StreamsPending int
7982
7983
7984
7985
7986 MaxConcurrentStreams uint32
7987
7988
7989
7990 LastIdle time.Time
7991 }
7992
7993
7994 func (cc *http2ClientConn) State() http2ClientConnState {
7995 cc.wmu.Lock()
7996 maxConcurrent := cc.maxConcurrentStreams
7997 if !cc.seenSettings {
7998 maxConcurrent = 0
7999 }
8000 cc.wmu.Unlock()
8001
8002 cc.mu.Lock()
8003 defer cc.mu.Unlock()
8004 return http2ClientConnState{
8005 Closed: cc.closed,
8006 Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil,
8007 StreamsActive: len(cc.streams),
8008 StreamsReserved: cc.streamsReserved,
8009 StreamsPending: cc.pendingRequests,
8010 LastIdle: cc.lastIdle,
8011 MaxConcurrentStreams: maxConcurrent,
8012 }
8013 }
8014
8015
8016
8017 type http2clientConnIdleState struct {
8018 canTakeNewRequest bool
8019 }
8020
8021 func (cc *http2ClientConn) idleState() http2clientConnIdleState {
8022 cc.mu.Lock()
8023 defer cc.mu.Unlock()
8024 return cc.idleStateLocked()
8025 }
8026
8027 func (cc *http2ClientConn) idleStateLocked() (st http2clientConnIdleState) {
8028 if cc.singleUse && cc.nextStreamID > 1 {
8029 return
8030 }
8031 var maxConcurrentOkay bool
8032 if cc.t.StrictMaxConcurrentStreams {
8033
8034
8035
8036
8037 maxConcurrentOkay = true
8038 } else {
8039 maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams)
8040 }
8041
8042 st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
8043 !cc.doNotReuse &&
8044 int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
8045 !cc.tooIdleLocked()
8046 return
8047 }
8048
8049 func (cc *http2ClientConn) canTakeNewRequestLocked() bool {
8050 st := cc.idleStateLocked()
8051 return st.canTakeNewRequest
8052 }
8053
8054
8055
8056 func (cc *http2ClientConn) tooIdleLocked() bool {
8057
8058
8059
8060
8061 return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
8062 }
8063
8064
8065
8066
8067
8068
8069
8070 func (cc *http2ClientConn) onIdleTimeout() {
8071 cc.closeIfIdle()
8072 }
8073
8074 func (cc *http2ClientConn) closeConn() {
8075 t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn)
8076 defer t.Stop()
8077 cc.tconn.Close()
8078 }
8079
8080
8081
8082 func (cc *http2ClientConn) forceCloseConn() {
8083 tc, ok := cc.tconn.(*tls.Conn)
8084 if !ok {
8085 return
8086 }
8087 if nc := tc.NetConn(); nc != nil {
8088 nc.Close()
8089 }
8090 }
8091
8092 func (cc *http2ClientConn) closeIfIdle() {
8093 cc.mu.Lock()
8094 if len(cc.streams) > 0 || cc.streamsReserved > 0 {
8095 cc.mu.Unlock()
8096 return
8097 }
8098 cc.closed = true
8099 nextID := cc.nextStreamID
8100
8101 cc.mu.Unlock()
8102
8103 if http2VerboseLogs {
8104 cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
8105 }
8106 cc.closeConn()
8107 }
8108
8109 func (cc *http2ClientConn) isDoNotReuseAndIdle() bool {
8110 cc.mu.Lock()
8111 defer cc.mu.Unlock()
8112 return cc.doNotReuse && len(cc.streams) == 0
8113 }
8114
8115 var http2shutdownEnterWaitStateHook = func() {}
8116
8117
8118 func (cc *http2ClientConn) Shutdown(ctx context.Context) error {
8119 if err := cc.sendGoAway(); err != nil {
8120 return err
8121 }
8122
8123 done := make(chan struct{})
8124 cancelled := false
8125 go func() {
8126 cc.mu.Lock()
8127 defer cc.mu.Unlock()
8128 for {
8129 if len(cc.streams) == 0 || cc.closed {
8130 cc.closed = true
8131 close(done)
8132 break
8133 }
8134 if cancelled {
8135 break
8136 }
8137 cc.cond.Wait()
8138 }
8139 }()
8140 http2shutdownEnterWaitStateHook()
8141 select {
8142 case <-done:
8143 cc.closeConn()
8144 return nil
8145 case <-ctx.Done():
8146 cc.mu.Lock()
8147
8148 cancelled = true
8149 cc.cond.Broadcast()
8150 cc.mu.Unlock()
8151 return ctx.Err()
8152 }
8153 }
8154
8155 func (cc *http2ClientConn) sendGoAway() error {
8156 cc.mu.Lock()
8157 closing := cc.closing
8158 cc.closing = true
8159 maxStreamID := cc.nextStreamID
8160 cc.mu.Unlock()
8161 if closing {
8162
8163 return nil
8164 }
8165
8166 cc.wmu.Lock()
8167 defer cc.wmu.Unlock()
8168
8169 if err := cc.fr.WriteGoAway(maxStreamID, http2ErrCodeNo, nil); err != nil {
8170 return err
8171 }
8172 if err := cc.bw.Flush(); err != nil {
8173 return err
8174 }
8175
8176 return nil
8177 }
8178
8179
8180
8181 func (cc *http2ClientConn) closeForError(err error) {
8182 cc.mu.Lock()
8183 cc.closed = true
8184 for _, cs := range cc.streams {
8185 cs.abortStreamLocked(err)
8186 }
8187 cc.cond.Broadcast()
8188 cc.mu.Unlock()
8189 cc.closeConn()
8190 }
8191
8192
8193
8194
8195 func (cc *http2ClientConn) Close() error {
8196 err := errors.New("http2: client connection force closed via ClientConn.Close")
8197 cc.closeForError(err)
8198 return nil
8199 }
8200
8201
8202 func (cc *http2ClientConn) closeForLostPing() {
8203 err := errors.New("http2: client connection lost")
8204 if f := cc.t.CountError; f != nil {
8205 f("conn_close_lost_ping")
8206 }
8207 cc.closeForError(err)
8208 }
8209
8210
8211
8212 var http2errRequestCanceled = errors.New("net/http: request canceled")
8213
8214 func http2commaSeparatedTrailers(req *Request) (string, error) {
8215 keys := make([]string, 0, len(req.Trailer))
8216 for k := range req.Trailer {
8217 k = http2canonicalHeader(k)
8218 switch k {
8219 case "Transfer-Encoding", "Trailer", "Content-Length":
8220 return "", fmt.Errorf("invalid Trailer key %q", k)
8221 }
8222 keys = append(keys, k)
8223 }
8224 if len(keys) > 0 {
8225 sort.Strings(keys)
8226 return strings.Join(keys, ","), nil
8227 }
8228 return "", nil
8229 }
8230
8231 func (cc *http2ClientConn) responseHeaderTimeout() time.Duration {
8232 if cc.t.t1 != nil {
8233 return cc.t.t1.ResponseHeaderTimeout
8234 }
8235
8236
8237
8238
8239 return 0
8240 }
8241
8242
8243
8244
8245 func http2checkConnHeaders(req *Request) error {
8246 if v := req.Header.Get("Upgrade"); v != "" {
8247 return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
8248 }
8249 if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
8250 return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
8251 }
8252 if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !http2asciiEqualFold(vv[0], "close") && !http2asciiEqualFold(vv[0], "keep-alive")) {
8253 return fmt.Errorf("http2: invalid Connection request header: %q", vv)
8254 }
8255 return nil
8256 }
8257
8258
8259
8260
8261 func http2actualContentLength(req *Request) int64 {
8262 if req.Body == nil || req.Body == NoBody {
8263 return 0
8264 }
8265 if req.ContentLength != 0 {
8266 return req.ContentLength
8267 }
8268 return -1
8269 }
8270
8271 func (cc *http2ClientConn) decrStreamReservations() {
8272 cc.mu.Lock()
8273 defer cc.mu.Unlock()
8274 cc.decrStreamReservationsLocked()
8275 }
8276
8277 func (cc *http2ClientConn) decrStreamReservationsLocked() {
8278 if cc.streamsReserved > 0 {
8279 cc.streamsReserved--
8280 }
8281 }
8282
8283 func (cc *http2ClientConn) RoundTrip(req *Request) (*Response, error) {
8284 ctx := req.Context()
8285 cs := &http2clientStream{
8286 cc: cc,
8287 ctx: ctx,
8288 reqCancel: req.Cancel,
8289 isHead: req.Method == "HEAD",
8290 reqBody: req.Body,
8291 reqBodyContentLength: http2actualContentLength(req),
8292 trace: httptrace.ContextClientTrace(ctx),
8293 peerClosed: make(chan struct{}),
8294 abort: make(chan struct{}),
8295 respHeaderRecv: make(chan struct{}),
8296 donec: make(chan struct{}),
8297 }
8298 go cs.doRequest(req)
8299
8300 waitDone := func() error {
8301 select {
8302 case <-cs.donec:
8303 return nil
8304 case <-ctx.Done():
8305 return ctx.Err()
8306 case <-cs.reqCancel:
8307 return http2errRequestCanceled
8308 }
8309 }
8310
8311 handleResponseHeaders := func() (*Response, error) {
8312 res := cs.res
8313 if res.StatusCode > 299 {
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323 cs.abortRequestBodyWrite()
8324 }
8325 res.Request = req
8326 res.TLS = cc.tlsState
8327 if res.Body == http2noBody && http2actualContentLength(req) == 0 {
8328
8329
8330
8331 if err := waitDone(); err != nil {
8332 return nil, err
8333 }
8334 }
8335 return res, nil
8336 }
8337
8338 cancelRequest := func(cs *http2clientStream, err error) error {
8339 cs.cc.mu.Lock()
8340 bodyClosed := cs.reqBodyClosed
8341 cs.cc.mu.Unlock()
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355 if bodyClosed != nil {
8356 <-bodyClosed
8357 }
8358 return err
8359 }
8360
8361 for {
8362 select {
8363 case <-cs.respHeaderRecv:
8364 return handleResponseHeaders()
8365 case <-cs.abort:
8366 select {
8367 case <-cs.respHeaderRecv:
8368
8369
8370
8371
8372 return handleResponseHeaders()
8373 default:
8374 waitDone()
8375 return nil, cs.abortErr
8376 }
8377 case <-ctx.Done():
8378 err := ctx.Err()
8379 cs.abortStream(err)
8380 return nil, cancelRequest(cs, err)
8381 case <-cs.reqCancel:
8382 cs.abortStream(http2errRequestCanceled)
8383 return nil, cancelRequest(cs, http2errRequestCanceled)
8384 }
8385 }
8386 }
8387
8388
8389
8390
8391 func (cs *http2clientStream) doRequest(req *Request) {
8392 err := cs.writeRequest(req)
8393 cs.cleanupWriteRequest(err)
8394 }
8395
8396
8397
8398
8399
8400
8401
8402
8403 func (cs *http2clientStream) writeRequest(req *Request) (err error) {
8404 cc := cs.cc
8405 ctx := cs.ctx
8406
8407 if err := http2checkConnHeaders(req); err != nil {
8408 return err
8409 }
8410
8411
8412
8413
8414 if cc.reqHeaderMu == nil {
8415 panic("RoundTrip on uninitialized ClientConn")
8416 }
8417 select {
8418 case cc.reqHeaderMu <- struct{}{}:
8419 case <-cs.reqCancel:
8420 return http2errRequestCanceled
8421 case <-ctx.Done():
8422 return ctx.Err()
8423 }
8424
8425 cc.mu.Lock()
8426 if cc.idleTimer != nil {
8427 cc.idleTimer.Stop()
8428 }
8429 cc.decrStreamReservationsLocked()
8430 if err := cc.awaitOpenSlotForStreamLocked(cs); err != nil {
8431 cc.mu.Unlock()
8432 <-cc.reqHeaderMu
8433 return err
8434 }
8435 cc.addStreamLocked(cs)
8436 if http2isConnectionCloseRequest(req) {
8437 cc.doNotReuse = true
8438 }
8439 cc.mu.Unlock()
8440
8441
8442 if !cc.t.disableCompression() &&
8443 req.Header.Get("Accept-Encoding") == "" &&
8444 req.Header.Get("Range") == "" &&
8445 !cs.isHead {
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458 cs.requestedGzip = true
8459 }
8460
8461 continueTimeout := cc.t.expectContinueTimeout()
8462 if continueTimeout != 0 {
8463 if !httpguts.HeaderValuesContainsToken(req.Header["Expect"], "100-continue") {
8464 continueTimeout = 0
8465 } else {
8466 cs.on100 = make(chan struct{}, 1)
8467 }
8468 }
8469
8470
8471
8472
8473
8474 err = cs.encodeAndWriteHeaders(req)
8475 <-cc.reqHeaderMu
8476 if err != nil {
8477 return err
8478 }
8479
8480 hasBody := cs.reqBodyContentLength != 0
8481 if !hasBody {
8482 cs.sentEndStream = true
8483 } else {
8484 if continueTimeout != 0 {
8485 http2traceWait100Continue(cs.trace)
8486 timer := time.NewTimer(continueTimeout)
8487 select {
8488 case <-timer.C:
8489 err = nil
8490 case <-cs.on100:
8491 err = nil
8492 case <-cs.abort:
8493 err = cs.abortErr
8494 case <-ctx.Done():
8495 err = ctx.Err()
8496 case <-cs.reqCancel:
8497 err = http2errRequestCanceled
8498 }
8499 timer.Stop()
8500 if err != nil {
8501 http2traceWroteRequest(cs.trace, err)
8502 return err
8503 }
8504 }
8505
8506 if err = cs.writeRequestBody(req); err != nil {
8507 if err != http2errStopReqBodyWrite {
8508 http2traceWroteRequest(cs.trace, err)
8509 return err
8510 }
8511 } else {
8512 cs.sentEndStream = true
8513 }
8514 }
8515
8516 http2traceWroteRequest(cs.trace, err)
8517
8518 var respHeaderTimer <-chan time.Time
8519 var respHeaderRecv chan struct{}
8520 if d := cc.responseHeaderTimeout(); d != 0 {
8521 timer := time.NewTimer(d)
8522 defer timer.Stop()
8523 respHeaderTimer = timer.C
8524 respHeaderRecv = cs.respHeaderRecv
8525 }
8526
8527
8528
8529 for {
8530 select {
8531 case <-cs.peerClosed:
8532 return nil
8533 case <-respHeaderTimer:
8534 return http2errTimeout
8535 case <-respHeaderRecv:
8536 respHeaderRecv = nil
8537 respHeaderTimer = nil
8538 case <-cs.abort:
8539 return cs.abortErr
8540 case <-ctx.Done():
8541 return ctx.Err()
8542 case <-cs.reqCancel:
8543 return http2errRequestCanceled
8544 }
8545 }
8546 }
8547
8548 func (cs *http2clientStream) encodeAndWriteHeaders(req *Request) error {
8549 cc := cs.cc
8550 ctx := cs.ctx
8551
8552 cc.wmu.Lock()
8553 defer cc.wmu.Unlock()
8554
8555
8556 select {
8557 case <-cs.abort:
8558 return cs.abortErr
8559 case <-ctx.Done():
8560 return ctx.Err()
8561 case <-cs.reqCancel:
8562 return http2errRequestCanceled
8563 default:
8564 }
8565
8566
8567
8568
8569
8570
8571 trailers, err := http2commaSeparatedTrailers(req)
8572 if err != nil {
8573 return err
8574 }
8575 hasTrailers := trailers != ""
8576 contentLen := http2actualContentLength(req)
8577 hasBody := contentLen != 0
8578 hdrs, err := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen)
8579 if err != nil {
8580 return err
8581 }
8582
8583
8584 endStream := !hasBody && !hasTrailers
8585 cs.sentHeaders = true
8586 err = cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
8587 http2traceWroteHeaders(cs.trace)
8588 return err
8589 }
8590
8591
8592
8593
8594
8595 func (cs *http2clientStream) cleanupWriteRequest(err error) {
8596 cc := cs.cc
8597
8598 if cs.ID == 0 {
8599
8600 cc.decrStreamReservations()
8601 }
8602
8603
8604
8605
8606
8607 cc.mu.Lock()
8608 mustCloseBody := false
8609 if cs.reqBody != nil && cs.reqBodyClosed == nil {
8610 mustCloseBody = true
8611 cs.reqBodyClosed = make(chan struct{})
8612 }
8613 bodyClosed := cs.reqBodyClosed
8614 cc.mu.Unlock()
8615 if mustCloseBody {
8616 cs.reqBody.Close()
8617 close(bodyClosed)
8618 }
8619 if bodyClosed != nil {
8620 <-bodyClosed
8621 }
8622
8623 if err != nil && cs.sentEndStream {
8624
8625
8626
8627 select {
8628 case <-cs.peerClosed:
8629 err = nil
8630 default:
8631 }
8632 }
8633 if err != nil {
8634 cs.abortStream(err)
8635 if cs.sentHeaders {
8636 if se, ok := err.(http2StreamError); ok {
8637 if se.Cause != http2errFromPeer {
8638 cc.writeStreamReset(cs.ID, se.Code, err)
8639 }
8640 } else {
8641 cc.writeStreamReset(cs.ID, http2ErrCodeCancel, err)
8642 }
8643 }
8644 cs.bufPipe.CloseWithError(err)
8645 } else {
8646 if cs.sentHeaders && !cs.sentEndStream {
8647 cc.writeStreamReset(cs.ID, http2ErrCodeNo, nil)
8648 }
8649 cs.bufPipe.CloseWithError(http2errRequestCanceled)
8650 }
8651 if cs.ID != 0 {
8652 cc.forgetStreamID(cs.ID)
8653 }
8654
8655 cc.wmu.Lock()
8656 werr := cc.werr
8657 cc.wmu.Unlock()
8658 if werr != nil {
8659 cc.Close()
8660 }
8661
8662 close(cs.donec)
8663 }
8664
8665
8666
8667 func (cc *http2ClientConn) awaitOpenSlotForStreamLocked(cs *http2clientStream) error {
8668 for {
8669 cc.lastActive = time.Now()
8670 if cc.closed || !cc.canTakeNewRequestLocked() {
8671 return http2errClientConnUnusable
8672 }
8673 cc.lastIdle = time.Time{}
8674 if int64(len(cc.streams)) < int64(cc.maxConcurrentStreams) {
8675 return nil
8676 }
8677 cc.pendingRequests++
8678 cc.cond.Wait()
8679 cc.pendingRequests--
8680 select {
8681 case <-cs.abort:
8682 return cs.abortErr
8683 default:
8684 }
8685 }
8686 }
8687
8688
8689 func (cc *http2ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
8690 first := true
8691 for len(hdrs) > 0 && cc.werr == nil {
8692 chunk := hdrs
8693 if len(chunk) > maxFrameSize {
8694 chunk = chunk[:maxFrameSize]
8695 }
8696 hdrs = hdrs[len(chunk):]
8697 endHeaders := len(hdrs) == 0
8698 if first {
8699 cc.fr.WriteHeaders(http2HeadersFrameParam{
8700 StreamID: streamID,
8701 BlockFragment: chunk,
8702 EndStream: endStream,
8703 EndHeaders: endHeaders,
8704 })
8705 first = false
8706 } else {
8707 cc.fr.WriteContinuation(streamID, endHeaders, chunk)
8708 }
8709 }
8710 cc.bw.Flush()
8711 return cc.werr
8712 }
8713
8714
8715 var (
8716
8717 http2errStopReqBodyWrite = errors.New("http2: aborting request body write")
8718
8719
8720 http2errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
8721
8722 http2errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
8723 )
8724
8725
8726
8727
8728
8729
8730 func (cs *http2clientStream) frameScratchBufferLen(maxFrameSize int) int {
8731 const max = 512 << 10
8732 n := int64(maxFrameSize)
8733 if n > max {
8734 n = max
8735 }
8736 if cl := cs.reqBodyContentLength; cl != -1 && cl+1 < n {
8737
8738
8739
8740
8741 n = cl + 1
8742 }
8743 if n < 1 {
8744 return 1
8745 }
8746 return int(n)
8747 }
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757 var http2bufPools [7]sync.Pool
8758
8759 func http2bufPoolIndex(size int) int {
8760 if size <= 16384 {
8761 return 0
8762 }
8763 size -= 1
8764 bits := bits.Len(uint(size))
8765 index := bits - 14
8766 if index >= len(http2bufPools) {
8767 return len(http2bufPools) - 1
8768 }
8769 return index
8770 }
8771
8772 func (cs *http2clientStream) writeRequestBody(req *Request) (err error) {
8773 cc := cs.cc
8774 body := cs.reqBody
8775 sentEnd := false
8776
8777 hasTrailers := req.Trailer != nil
8778 remainLen := cs.reqBodyContentLength
8779 hasContentLen := remainLen != -1
8780
8781 cc.mu.Lock()
8782 maxFrameSize := int(cc.maxFrameSize)
8783 cc.mu.Unlock()
8784
8785
8786 scratchLen := cs.frameScratchBufferLen(maxFrameSize)
8787 var buf []byte
8788 index := http2bufPoolIndex(scratchLen)
8789 if bp, ok := http2bufPools[index].Get().(*[]byte); ok && len(*bp) >= scratchLen {
8790 defer http2bufPools[index].Put(bp)
8791 buf = *bp
8792 } else {
8793 buf = make([]byte, scratchLen)
8794 defer http2bufPools[index].Put(&buf)
8795 }
8796
8797 var sawEOF bool
8798 for !sawEOF {
8799 n, err := body.Read(buf)
8800 if hasContentLen {
8801 remainLen -= int64(n)
8802 if remainLen == 0 && err == nil {
8803
8804
8805
8806
8807
8808
8809
8810 var scratch [1]byte
8811 var n1 int
8812 n1, err = body.Read(scratch[:])
8813 remainLen -= int64(n1)
8814 }
8815 if remainLen < 0 {
8816 err = http2errReqBodyTooLong
8817 return err
8818 }
8819 }
8820 if err != nil {
8821 cc.mu.Lock()
8822 bodyClosed := cs.reqBodyClosed != nil
8823 cc.mu.Unlock()
8824 switch {
8825 case bodyClosed:
8826 return http2errStopReqBodyWrite
8827 case err == io.EOF:
8828 sawEOF = true
8829 err = nil
8830 default:
8831 return err
8832 }
8833 }
8834
8835 remain := buf[:n]
8836 for len(remain) > 0 && err == nil {
8837 var allowed int32
8838 allowed, err = cs.awaitFlowControl(len(remain))
8839 if err != nil {
8840 return err
8841 }
8842 cc.wmu.Lock()
8843 data := remain[:allowed]
8844 remain = remain[allowed:]
8845 sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
8846 err = cc.fr.WriteData(cs.ID, sentEnd, data)
8847 if err == nil {
8848
8849
8850
8851
8852
8853
8854 err = cc.bw.Flush()
8855 }
8856 cc.wmu.Unlock()
8857 }
8858 if err != nil {
8859 return err
8860 }
8861 }
8862
8863 if sentEnd {
8864
8865
8866
8867 return nil
8868 }
8869
8870
8871
8872
8873 cc.mu.Lock()
8874 trailer := req.Trailer
8875 err = cs.abortErr
8876 cc.mu.Unlock()
8877 if err != nil {
8878 return err
8879 }
8880
8881 cc.wmu.Lock()
8882 defer cc.wmu.Unlock()
8883 var trls []byte
8884 if len(trailer) > 0 {
8885 trls, err = cc.encodeTrailers(trailer)
8886 if err != nil {
8887 return err
8888 }
8889 }
8890
8891
8892
8893 if len(trls) > 0 {
8894 err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
8895 } else {
8896 err = cc.fr.WriteData(cs.ID, true, nil)
8897 }
8898 if ferr := cc.bw.Flush(); ferr != nil && err == nil {
8899 err = ferr
8900 }
8901 return err
8902 }
8903
8904
8905
8906
8907
8908 func (cs *http2clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
8909 cc := cs.cc
8910 ctx := cs.ctx
8911 cc.mu.Lock()
8912 defer cc.mu.Unlock()
8913 for {
8914 if cc.closed {
8915 return 0, http2errClientConnClosed
8916 }
8917 if cs.reqBodyClosed != nil {
8918 return 0, http2errStopReqBodyWrite
8919 }
8920 select {
8921 case <-cs.abort:
8922 return 0, cs.abortErr
8923 case <-ctx.Done():
8924 return 0, ctx.Err()
8925 case <-cs.reqCancel:
8926 return 0, http2errRequestCanceled
8927 default:
8928 }
8929 if a := cs.flow.available(); a > 0 {
8930 take := a
8931 if int(take) > maxBytes {
8932
8933 take = int32(maxBytes)
8934 }
8935 if take > int32(cc.maxFrameSize) {
8936 take = int32(cc.maxFrameSize)
8937 }
8938 cs.flow.take(take)
8939 return take, nil
8940 }
8941 cc.cond.Wait()
8942 }
8943 }
8944
8945 var http2errNilRequestURL = errors.New("http2: Request.URI is nil")
8946
8947
8948 func (cc *http2ClientConn) encodeHeaders(req *Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
8949 cc.hbuf.Reset()
8950 if req.URL == nil {
8951 return nil, http2errNilRequestURL
8952 }
8953
8954 host := req.Host
8955 if host == "" {
8956 host = req.URL.Host
8957 }
8958 host, err := httpguts.PunycodeHostPort(host)
8959 if err != nil {
8960 return nil, err
8961 }
8962 if !httpguts.ValidHostHeader(host) {
8963 return nil, errors.New("http2: invalid Host header")
8964 }
8965
8966 var path string
8967 if req.Method != "CONNECT" {
8968 path = req.URL.RequestURI()
8969 if !http2validPseudoPath(path) {
8970 orig := path
8971 path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
8972 if !http2validPseudoPath(path) {
8973 if req.URL.Opaque != "" {
8974 return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
8975 } else {
8976 return nil, fmt.Errorf("invalid request :path %q", orig)
8977 }
8978 }
8979 }
8980 }
8981
8982
8983
8984
8985 for k, vv := range req.Header {
8986 if !httpguts.ValidHeaderFieldName(k) {
8987 return nil, fmt.Errorf("invalid HTTP header name %q", k)
8988 }
8989 for _, v := range vv {
8990 if !httpguts.ValidHeaderFieldValue(v) {
8991
8992 return nil, fmt.Errorf("invalid HTTP header value for header %q", k)
8993 }
8994 }
8995 }
8996
8997 enumerateHeaders := func(f func(name, value string)) {
8998
8999
9000
9001
9002
9003 f(":authority", host)
9004 m := req.Method
9005 if m == "" {
9006 m = MethodGet
9007 }
9008 f(":method", m)
9009 if req.Method != "CONNECT" {
9010 f(":path", path)
9011 f(":scheme", req.URL.Scheme)
9012 }
9013 if trailers != "" {
9014 f("trailer", trailers)
9015 }
9016
9017 var didUA bool
9018 for k, vv := range req.Header {
9019 if http2asciiEqualFold(k, "host") || http2asciiEqualFold(k, "content-length") {
9020
9021
9022 continue
9023 } else if http2asciiEqualFold(k, "connection") ||
9024 http2asciiEqualFold(k, "proxy-connection") ||
9025 http2asciiEqualFold(k, "transfer-encoding") ||
9026 http2asciiEqualFold(k, "upgrade") ||
9027 http2asciiEqualFold(k, "keep-alive") {
9028
9029
9030
9031
9032 continue
9033 } else if http2asciiEqualFold(k, "user-agent") {
9034
9035
9036
9037
9038 didUA = true
9039 if len(vv) < 1 {
9040 continue
9041 }
9042 vv = vv[:1]
9043 if vv[0] == "" {
9044 continue
9045 }
9046 } else if http2asciiEqualFold(k, "cookie") {
9047
9048
9049
9050 for _, v := range vv {
9051 for {
9052 p := strings.IndexByte(v, ';')
9053 if p < 0 {
9054 break
9055 }
9056 f("cookie", v[:p])
9057 p++
9058
9059 for p+1 <= len(v) && v[p] == ' ' {
9060 p++
9061 }
9062 v = v[p:]
9063 }
9064 if len(v) > 0 {
9065 f("cookie", v)
9066 }
9067 }
9068 continue
9069 }
9070
9071 for _, v := range vv {
9072 f(k, v)
9073 }
9074 }
9075 if http2shouldSendReqContentLength(req.Method, contentLength) {
9076 f("content-length", strconv.FormatInt(contentLength, 10))
9077 }
9078 if addGzipHeader {
9079 f("accept-encoding", "gzip")
9080 }
9081 if !didUA {
9082 f("user-agent", http2defaultUserAgent)
9083 }
9084 }
9085
9086
9087
9088
9089
9090 hlSize := uint64(0)
9091 enumerateHeaders(func(name, value string) {
9092 hf := hpack.HeaderField{Name: name, Value: value}
9093 hlSize += uint64(hf.Size())
9094 })
9095
9096 if hlSize > cc.peerMaxHeaderListSize {
9097 return nil, http2errRequestHeaderListSize
9098 }
9099
9100 trace := httptrace.ContextClientTrace(req.Context())
9101 traceHeaders := http2traceHasWroteHeaderField(trace)
9102
9103
9104 enumerateHeaders(func(name, value string) {
9105 name, ascii := http2lowerHeader(name)
9106 if !ascii {
9107
9108
9109 return
9110 }
9111 cc.writeHeader(name, value)
9112 if traceHeaders {
9113 http2traceWroteHeaderField(trace, name, value)
9114 }
9115 })
9116
9117 return cc.hbuf.Bytes(), nil
9118 }
9119
9120
9121
9122
9123
9124
9125 func http2shouldSendReqContentLength(method string, contentLength int64) bool {
9126 if contentLength > 0 {
9127 return true
9128 }
9129 if contentLength < 0 {
9130 return false
9131 }
9132
9133
9134 switch method {
9135 case "POST", "PUT", "PATCH":
9136 return true
9137 default:
9138 return false
9139 }
9140 }
9141
9142
9143 func (cc *http2ClientConn) encodeTrailers(trailer Header) ([]byte, error) {
9144 cc.hbuf.Reset()
9145
9146 hlSize := uint64(0)
9147 for k, vv := range trailer {
9148 for _, v := range vv {
9149 hf := hpack.HeaderField{Name: k, Value: v}
9150 hlSize += uint64(hf.Size())
9151 }
9152 }
9153 if hlSize > cc.peerMaxHeaderListSize {
9154 return nil, http2errRequestHeaderListSize
9155 }
9156
9157 for k, vv := range trailer {
9158 lowKey, ascii := http2lowerHeader(k)
9159 if !ascii {
9160
9161
9162 continue
9163 }
9164
9165
9166 for _, v := range vv {
9167 cc.writeHeader(lowKey, v)
9168 }
9169 }
9170 return cc.hbuf.Bytes(), nil
9171 }
9172
9173 func (cc *http2ClientConn) writeHeader(name, value string) {
9174 if http2VerboseLogs {
9175 log.Printf("http2: Transport encoding header %q = %q", name, value)
9176 }
9177 cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
9178 }
9179
9180 type http2resAndError struct {
9181 _ http2incomparable
9182 res *Response
9183 err error
9184 }
9185
9186
9187 func (cc *http2ClientConn) addStreamLocked(cs *http2clientStream) {
9188 cs.flow.add(int32(cc.initialWindowSize))
9189 cs.flow.setConnFlow(&cc.flow)
9190 cs.inflow.init(http2transportDefaultStreamFlow)
9191 cs.ID = cc.nextStreamID
9192 cc.nextStreamID += 2
9193 cc.streams[cs.ID] = cs
9194 if cs.ID == 0 {
9195 panic("assigned stream ID 0")
9196 }
9197 }
9198
9199 func (cc *http2ClientConn) forgetStreamID(id uint32) {
9200 cc.mu.Lock()
9201 slen := len(cc.streams)
9202 delete(cc.streams, id)
9203 if len(cc.streams) != slen-1 {
9204 panic("forgetting unknown stream id")
9205 }
9206 cc.lastActive = time.Now()
9207 if len(cc.streams) == 0 && cc.idleTimer != nil {
9208 cc.idleTimer.Reset(cc.idleTimeout)
9209 cc.lastIdle = time.Now()
9210 }
9211
9212
9213 cc.cond.Broadcast()
9214
9215 closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil
9216 if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 {
9217 if http2VerboseLogs {
9218 cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, cc.nextStreamID-2)
9219 }
9220 cc.closed = true
9221 defer cc.closeConn()
9222 }
9223
9224 cc.mu.Unlock()
9225 }
9226
9227
9228 type http2clientConnReadLoop struct {
9229 _ http2incomparable
9230 cc *http2ClientConn
9231 }
9232
9233
9234 func (cc *http2ClientConn) readLoop() {
9235 rl := &http2clientConnReadLoop{cc: cc}
9236 defer rl.cleanup()
9237 cc.readerErr = rl.run()
9238 if ce, ok := cc.readerErr.(http2ConnectionError); ok {
9239 cc.wmu.Lock()
9240 cc.fr.WriteGoAway(0, http2ErrCode(ce), nil)
9241 cc.wmu.Unlock()
9242 }
9243 }
9244
9245
9246
9247 type http2GoAwayError struct {
9248 LastStreamID uint32
9249 ErrCode http2ErrCode
9250 DebugData string
9251 }
9252
9253 func (e http2GoAwayError) Error() string {
9254 return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
9255 e.LastStreamID, e.ErrCode, e.DebugData)
9256 }
9257
9258 func http2isEOFOrNetReadError(err error) bool {
9259 if err == io.EOF {
9260 return true
9261 }
9262 ne, ok := err.(*net.OpError)
9263 return ok && ne.Op == "read"
9264 }
9265
9266 func (rl *http2clientConnReadLoop) cleanup() {
9267 cc := rl.cc
9268 cc.t.connPool().MarkDead(cc)
9269 defer cc.closeConn()
9270 defer close(cc.readerDone)
9271
9272 if cc.idleTimer != nil {
9273 cc.idleTimer.Stop()
9274 }
9275
9276
9277
9278
9279 err := cc.readerErr
9280 cc.mu.Lock()
9281 if cc.goAway != nil && http2isEOFOrNetReadError(err) {
9282 err = http2GoAwayError{
9283 LastStreamID: cc.goAway.LastStreamID,
9284 ErrCode: cc.goAway.ErrCode,
9285 DebugData: cc.goAwayDebug,
9286 }
9287 } else if err == io.EOF {
9288 err = io.ErrUnexpectedEOF
9289 }
9290 cc.closed = true
9291
9292 for _, cs := range cc.streams {
9293 select {
9294 case <-cs.peerClosed:
9295
9296
9297 default:
9298 cs.abortStreamLocked(err)
9299 }
9300 }
9301 cc.cond.Broadcast()
9302 cc.mu.Unlock()
9303 }
9304
9305
9306
9307 func (cc *http2ClientConn) countReadFrameError(err error) {
9308 f := cc.t.CountError
9309 if f == nil || err == nil {
9310 return
9311 }
9312 if ce, ok := err.(http2ConnectionError); ok {
9313 errCode := http2ErrCode(ce)
9314 f(fmt.Sprintf("read_frame_conn_error_%s", errCode.stringToken()))
9315 return
9316 }
9317 if errors.Is(err, io.EOF) {
9318 f("read_frame_eof")
9319 return
9320 }
9321 if errors.Is(err, io.ErrUnexpectedEOF) {
9322 f("read_frame_unexpected_eof")
9323 return
9324 }
9325 if errors.Is(err, http2ErrFrameTooLarge) {
9326 f("read_frame_too_large")
9327 return
9328 }
9329 f("read_frame_other")
9330 }
9331
9332 func (rl *http2clientConnReadLoop) run() error {
9333 cc := rl.cc
9334 gotSettings := false
9335 readIdleTimeout := cc.t.ReadIdleTimeout
9336 var t *time.Timer
9337 if readIdleTimeout != 0 {
9338 t = time.AfterFunc(readIdleTimeout, cc.healthCheck)
9339 defer t.Stop()
9340 }
9341 for {
9342 f, err := cc.fr.ReadFrame()
9343 if t != nil {
9344 t.Reset(readIdleTimeout)
9345 }
9346 if err != nil {
9347 cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
9348 }
9349 if se, ok := err.(http2StreamError); ok {
9350 if cs := rl.streamByID(se.StreamID); cs != nil {
9351 if se.Cause == nil {
9352 se.Cause = cc.fr.errDetail
9353 }
9354 rl.endStreamError(cs, se)
9355 }
9356 continue
9357 } else if err != nil {
9358 cc.countReadFrameError(err)
9359 return err
9360 }
9361 if http2VerboseLogs {
9362 cc.vlogf("http2: Transport received %s", http2summarizeFrame(f))
9363 }
9364 if !gotSettings {
9365 if _, ok := f.(*http2SettingsFrame); !ok {
9366 cc.logf("protocol error: received %T before a SETTINGS frame", f)
9367 return http2ConnectionError(http2ErrCodeProtocol)
9368 }
9369 gotSettings = true
9370 }
9371
9372 switch f := f.(type) {
9373 case *http2MetaHeadersFrame:
9374 err = rl.processHeaders(f)
9375 case *http2DataFrame:
9376 err = rl.processData(f)
9377 case *http2GoAwayFrame:
9378 err = rl.processGoAway(f)
9379 case *http2RSTStreamFrame:
9380 err = rl.processResetStream(f)
9381 case *http2SettingsFrame:
9382 err = rl.processSettings(f)
9383 case *http2PushPromiseFrame:
9384 err = rl.processPushPromise(f)
9385 case *http2WindowUpdateFrame:
9386 err = rl.processWindowUpdate(f)
9387 case *http2PingFrame:
9388 err = rl.processPing(f)
9389 default:
9390 cc.logf("Transport: unhandled response frame type %T", f)
9391 }
9392 if err != nil {
9393 if http2VerboseLogs {
9394 cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, http2summarizeFrame(f), err)
9395 }
9396 return err
9397 }
9398 }
9399 }
9400
9401 func (rl *http2clientConnReadLoop) processHeaders(f *http2MetaHeadersFrame) error {
9402 cs := rl.streamByID(f.StreamID)
9403 if cs == nil {
9404
9405
9406
9407 return nil
9408 }
9409 if cs.readClosed {
9410 rl.endStreamError(cs, http2StreamError{
9411 StreamID: f.StreamID,
9412 Code: http2ErrCodeProtocol,
9413 Cause: errors.New("protocol error: headers after END_STREAM"),
9414 })
9415 return nil
9416 }
9417 if !cs.firstByte {
9418 if cs.trace != nil {
9419
9420
9421
9422
9423 http2traceFirstResponseByte(cs.trace)
9424 }
9425 cs.firstByte = true
9426 }
9427 if !cs.pastHeaders {
9428 cs.pastHeaders = true
9429 } else {
9430 return rl.processTrailers(cs, f)
9431 }
9432
9433 res, err := rl.handleResponse(cs, f)
9434 if err != nil {
9435 if _, ok := err.(http2ConnectionError); ok {
9436 return err
9437 }
9438
9439 rl.endStreamError(cs, http2StreamError{
9440 StreamID: f.StreamID,
9441 Code: http2ErrCodeProtocol,
9442 Cause: err,
9443 })
9444 return nil
9445 }
9446 if res == nil {
9447
9448 return nil
9449 }
9450 cs.resTrailer = &res.Trailer
9451 cs.res = res
9452 close(cs.respHeaderRecv)
9453 if f.StreamEnded() {
9454 rl.endStream(cs)
9455 }
9456 return nil
9457 }
9458
9459
9460
9461
9462
9463
9464
9465 func (rl *http2clientConnReadLoop) handleResponse(cs *http2clientStream, f *http2MetaHeadersFrame) (*Response, error) {
9466 if f.Truncated {
9467 return nil, http2errResponseHeaderListSize
9468 }
9469
9470 status := f.PseudoValue("status")
9471 if status == "" {
9472 return nil, errors.New("malformed response from server: missing status pseudo header")
9473 }
9474 statusCode, err := strconv.Atoi(status)
9475 if err != nil {
9476 return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
9477 }
9478
9479 regularFields := f.RegularFields()
9480 strs := make([]string, len(regularFields))
9481 header := make(Header, len(regularFields))
9482 res := &Response{
9483 Proto: "HTTP/2.0",
9484 ProtoMajor: 2,
9485 Header: header,
9486 StatusCode: statusCode,
9487 Status: status + " " + StatusText(statusCode),
9488 }
9489 for _, hf := range regularFields {
9490 key := http2canonicalHeader(hf.Name)
9491 if key == "Trailer" {
9492 t := res.Trailer
9493 if t == nil {
9494 t = make(Header)
9495 res.Trailer = t
9496 }
9497 http2foreachHeaderElement(hf.Value, func(v string) {
9498 t[http2canonicalHeader(v)] = nil
9499 })
9500 } else {
9501 vv := header[key]
9502 if vv == nil && len(strs) > 0 {
9503
9504
9505
9506
9507 vv, strs = strs[:1:1], strs[1:]
9508 vv[0] = hf.Value
9509 header[key] = vv
9510 } else {
9511 header[key] = append(vv, hf.Value)
9512 }
9513 }
9514 }
9515
9516 if statusCode >= 100 && statusCode <= 199 {
9517 if f.StreamEnded() {
9518 return nil, errors.New("1xx informational response with END_STREAM flag")
9519 }
9520 cs.num1xx++
9521 const max1xxResponses = 5
9522 if cs.num1xx > max1xxResponses {
9523 return nil, errors.New("http2: too many 1xx informational responses")
9524 }
9525 if fn := cs.get1xxTraceFunc(); fn != nil {
9526 if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
9527 return nil, err
9528 }
9529 }
9530 if statusCode == 100 {
9531 http2traceGot100Continue(cs.trace)
9532 select {
9533 case cs.on100 <- struct{}{}:
9534 default:
9535 }
9536 }
9537 cs.pastHeaders = false
9538 return nil, nil
9539 }
9540
9541 res.ContentLength = -1
9542 if clens := res.Header["Content-Length"]; len(clens) == 1 {
9543 if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
9544 res.ContentLength = int64(cl)
9545 } else {
9546
9547
9548 }
9549 } else if len(clens) > 1 {
9550
9551
9552 } else if f.StreamEnded() && !cs.isHead {
9553 res.ContentLength = 0
9554 }
9555
9556 if cs.isHead {
9557 res.Body = http2noBody
9558 return res, nil
9559 }
9560
9561 if f.StreamEnded() {
9562 if res.ContentLength > 0 {
9563 res.Body = http2missingBody{}
9564 } else {
9565 res.Body = http2noBody
9566 }
9567 return res, nil
9568 }
9569
9570 cs.bufPipe.setBuffer(&http2dataBuffer{expected: res.ContentLength})
9571 cs.bytesRemain = res.ContentLength
9572 res.Body = http2transportResponseBody{cs}
9573
9574 if cs.requestedGzip && http2asciiEqualFold(res.Header.Get("Content-Encoding"), "gzip") {
9575 res.Header.Del("Content-Encoding")
9576 res.Header.Del("Content-Length")
9577 res.ContentLength = -1
9578 res.Body = &http2gzipReader{body: res.Body}
9579 res.Uncompressed = true
9580 }
9581 return res, nil
9582 }
9583
9584 func (rl *http2clientConnReadLoop) processTrailers(cs *http2clientStream, f *http2MetaHeadersFrame) error {
9585 if cs.pastTrailers {
9586
9587 return http2ConnectionError(http2ErrCodeProtocol)
9588 }
9589 cs.pastTrailers = true
9590 if !f.StreamEnded() {
9591
9592
9593 return http2ConnectionError(http2ErrCodeProtocol)
9594 }
9595 if len(f.PseudoFields()) > 0 {
9596
9597
9598 return http2ConnectionError(http2ErrCodeProtocol)
9599 }
9600
9601 trailer := make(Header)
9602 for _, hf := range f.RegularFields() {
9603 key := http2canonicalHeader(hf.Name)
9604 trailer[key] = append(trailer[key], hf.Value)
9605 }
9606 cs.trailer = trailer
9607
9608 rl.endStream(cs)
9609 return nil
9610 }
9611
9612
9613
9614 type http2transportResponseBody struct {
9615 cs *http2clientStream
9616 }
9617
9618 func (b http2transportResponseBody) Read(p []byte) (n int, err error) {
9619 cs := b.cs
9620 cc := cs.cc
9621
9622 if cs.readErr != nil {
9623 return 0, cs.readErr
9624 }
9625 n, err = b.cs.bufPipe.Read(p)
9626 if cs.bytesRemain != -1 {
9627 if int64(n) > cs.bytesRemain {
9628 n = int(cs.bytesRemain)
9629 if err == nil {
9630 err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
9631 cs.abortStream(err)
9632 }
9633 cs.readErr = err
9634 return int(cs.bytesRemain), err
9635 }
9636 cs.bytesRemain -= int64(n)
9637 if err == io.EOF && cs.bytesRemain > 0 {
9638 err = io.ErrUnexpectedEOF
9639 cs.readErr = err
9640 return n, err
9641 }
9642 }
9643 if n == 0 {
9644
9645 return
9646 }
9647
9648 cc.mu.Lock()
9649 connAdd := cc.inflow.add(n)
9650 var streamAdd int32
9651 if err == nil {
9652 streamAdd = cs.inflow.add(n)
9653 }
9654 cc.mu.Unlock()
9655
9656 if connAdd != 0 || streamAdd != 0 {
9657 cc.wmu.Lock()
9658 defer cc.wmu.Unlock()
9659 if connAdd != 0 {
9660 cc.fr.WriteWindowUpdate(0, http2mustUint31(connAdd))
9661 }
9662 if streamAdd != 0 {
9663 cc.fr.WriteWindowUpdate(cs.ID, http2mustUint31(streamAdd))
9664 }
9665 cc.bw.Flush()
9666 }
9667 return
9668 }
9669
9670 var http2errClosedResponseBody = errors.New("http2: response body closed")
9671
9672 func (b http2transportResponseBody) Close() error {
9673 cs := b.cs
9674 cc := cs.cc
9675
9676 cs.bufPipe.BreakWithError(http2errClosedResponseBody)
9677 cs.abortStream(http2errClosedResponseBody)
9678
9679 unread := cs.bufPipe.Len()
9680 if unread > 0 {
9681 cc.mu.Lock()
9682
9683 connAdd := cc.inflow.add(unread)
9684 cc.mu.Unlock()
9685
9686
9687
9688 cc.wmu.Lock()
9689
9690 if connAdd > 0 {
9691 cc.fr.WriteWindowUpdate(0, uint32(connAdd))
9692 }
9693 cc.bw.Flush()
9694 cc.wmu.Unlock()
9695 }
9696
9697 select {
9698 case <-cs.donec:
9699 case <-cs.ctx.Done():
9700
9701
9702
9703 return nil
9704 case <-cs.reqCancel:
9705 return http2errRequestCanceled
9706 }
9707 return nil
9708 }
9709
9710 func (rl *http2clientConnReadLoop) processData(f *http2DataFrame) error {
9711 cc := rl.cc
9712 cs := rl.streamByID(f.StreamID)
9713 data := f.Data()
9714 if cs == nil {
9715 cc.mu.Lock()
9716 neverSent := cc.nextStreamID
9717 cc.mu.Unlock()
9718 if f.StreamID >= neverSent {
9719
9720 cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
9721 return http2ConnectionError(http2ErrCodeProtocol)
9722 }
9723
9724
9725
9726
9727
9728
9729 if f.Length > 0 {
9730 cc.mu.Lock()
9731 ok := cc.inflow.take(f.Length)
9732 connAdd := cc.inflow.add(int(f.Length))
9733 cc.mu.Unlock()
9734 if !ok {
9735 return http2ConnectionError(http2ErrCodeFlowControl)
9736 }
9737 if connAdd > 0 {
9738 cc.wmu.Lock()
9739 cc.fr.WriteWindowUpdate(0, uint32(connAdd))
9740 cc.bw.Flush()
9741 cc.wmu.Unlock()
9742 }
9743 }
9744 return nil
9745 }
9746 if cs.readClosed {
9747 cc.logf("protocol error: received DATA after END_STREAM")
9748 rl.endStreamError(cs, http2StreamError{
9749 StreamID: f.StreamID,
9750 Code: http2ErrCodeProtocol,
9751 })
9752 return nil
9753 }
9754 if !cs.pastHeaders {
9755 cc.logf("protocol error: received DATA before a HEADERS frame")
9756 rl.endStreamError(cs, http2StreamError{
9757 StreamID: f.StreamID,
9758 Code: http2ErrCodeProtocol,
9759 })
9760 return nil
9761 }
9762 if f.Length > 0 {
9763 if cs.isHead && len(data) > 0 {
9764 cc.logf("protocol error: received DATA on a HEAD request")
9765 rl.endStreamError(cs, http2StreamError{
9766 StreamID: f.StreamID,
9767 Code: http2ErrCodeProtocol,
9768 })
9769 return nil
9770 }
9771
9772 cc.mu.Lock()
9773 if !http2takeInflows(&cc.inflow, &cs.inflow, f.Length) {
9774 cc.mu.Unlock()
9775 return http2ConnectionError(http2ErrCodeFlowControl)
9776 }
9777
9778
9779 var refund int
9780 if pad := int(f.Length) - len(data); pad > 0 {
9781 refund += pad
9782 }
9783
9784 didReset := false
9785 var err error
9786 if len(data) > 0 {
9787 if _, err = cs.bufPipe.Write(data); err != nil {
9788
9789
9790 didReset = true
9791 refund += len(data)
9792 }
9793 }
9794
9795 sendConn := cc.inflow.add(refund)
9796 var sendStream int32
9797 if !didReset {
9798 sendStream = cs.inflow.add(refund)
9799 }
9800 cc.mu.Unlock()
9801
9802 if sendConn > 0 || sendStream > 0 {
9803 cc.wmu.Lock()
9804 if sendConn > 0 {
9805 cc.fr.WriteWindowUpdate(0, uint32(sendConn))
9806 }
9807 if sendStream > 0 {
9808 cc.fr.WriteWindowUpdate(cs.ID, uint32(sendStream))
9809 }
9810 cc.bw.Flush()
9811 cc.wmu.Unlock()
9812 }
9813
9814 if err != nil {
9815 rl.endStreamError(cs, err)
9816 return nil
9817 }
9818 }
9819
9820 if f.StreamEnded() {
9821 rl.endStream(cs)
9822 }
9823 return nil
9824 }
9825
9826 func (rl *http2clientConnReadLoop) endStream(cs *http2clientStream) {
9827
9828
9829 if !cs.readClosed {
9830 cs.readClosed = true
9831
9832
9833
9834
9835 rl.cc.mu.Lock()
9836 defer rl.cc.mu.Unlock()
9837 cs.bufPipe.closeWithErrorAndCode(io.EOF, cs.copyTrailers)
9838 close(cs.peerClosed)
9839 }
9840 }
9841
9842 func (rl *http2clientConnReadLoop) endStreamError(cs *http2clientStream, err error) {
9843 cs.readAborted = true
9844 cs.abortStream(err)
9845 }
9846
9847 func (rl *http2clientConnReadLoop) streamByID(id uint32) *http2clientStream {
9848 rl.cc.mu.Lock()
9849 defer rl.cc.mu.Unlock()
9850 cs := rl.cc.streams[id]
9851 if cs != nil && !cs.readAborted {
9852 return cs
9853 }
9854 return nil
9855 }
9856
9857 func (cs *http2clientStream) copyTrailers() {
9858 for k, vv := range cs.trailer {
9859 t := cs.resTrailer
9860 if *t == nil {
9861 *t = make(Header)
9862 }
9863 (*t)[k] = vv
9864 }
9865 }
9866
9867 func (rl *http2clientConnReadLoop) processGoAway(f *http2GoAwayFrame) error {
9868 cc := rl.cc
9869 cc.t.connPool().MarkDead(cc)
9870 if f.ErrCode != 0 {
9871
9872 cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
9873 if fn := cc.t.CountError; fn != nil {
9874 fn("recv_goaway_" + f.ErrCode.stringToken())
9875 }
9876 }
9877 cc.setGoAway(f)
9878 return nil
9879 }
9880
9881 func (rl *http2clientConnReadLoop) processSettings(f *http2SettingsFrame) error {
9882 cc := rl.cc
9883
9884
9885 cc.wmu.Lock()
9886 defer cc.wmu.Unlock()
9887
9888 if err := rl.processSettingsNoWrite(f); err != nil {
9889 return err
9890 }
9891 if !f.IsAck() {
9892 cc.fr.WriteSettingsAck()
9893 cc.bw.Flush()
9894 }
9895 return nil
9896 }
9897
9898 func (rl *http2clientConnReadLoop) processSettingsNoWrite(f *http2SettingsFrame) error {
9899 cc := rl.cc
9900 cc.mu.Lock()
9901 defer cc.mu.Unlock()
9902
9903 if f.IsAck() {
9904 if cc.wantSettingsAck {
9905 cc.wantSettingsAck = false
9906 return nil
9907 }
9908 return http2ConnectionError(http2ErrCodeProtocol)
9909 }
9910
9911 var seenMaxConcurrentStreams bool
9912 err := f.ForeachSetting(func(s http2Setting) error {
9913 switch s.ID {
9914 case http2SettingMaxFrameSize:
9915 cc.maxFrameSize = s.Val
9916 case http2SettingMaxConcurrentStreams:
9917 cc.maxConcurrentStreams = s.Val
9918 seenMaxConcurrentStreams = true
9919 case http2SettingMaxHeaderListSize:
9920 cc.peerMaxHeaderListSize = uint64(s.Val)
9921 case http2SettingInitialWindowSize:
9922
9923
9924
9925
9926 if s.Val > math.MaxInt32 {
9927 return http2ConnectionError(http2ErrCodeFlowControl)
9928 }
9929
9930
9931
9932
9933 delta := int32(s.Val) - int32(cc.initialWindowSize)
9934 for _, cs := range cc.streams {
9935 cs.flow.add(delta)
9936 }
9937 cc.cond.Broadcast()
9938
9939 cc.initialWindowSize = s.Val
9940 case http2SettingHeaderTableSize:
9941 cc.henc.SetMaxDynamicTableSize(s.Val)
9942 cc.peerMaxHeaderTableSize = s.Val
9943 default:
9944 cc.vlogf("Unhandled Setting: %v", s)
9945 }
9946 return nil
9947 })
9948 if err != nil {
9949 return err
9950 }
9951
9952 if !cc.seenSettings {
9953 if !seenMaxConcurrentStreams {
9954
9955
9956
9957
9958 cc.maxConcurrentStreams = http2defaultMaxConcurrentStreams
9959 }
9960 cc.seenSettings = true
9961 }
9962
9963 return nil
9964 }
9965
9966 func (rl *http2clientConnReadLoop) processWindowUpdate(f *http2WindowUpdateFrame) error {
9967 cc := rl.cc
9968 cs := rl.streamByID(f.StreamID)
9969 if f.StreamID != 0 && cs == nil {
9970 return nil
9971 }
9972
9973 cc.mu.Lock()
9974 defer cc.mu.Unlock()
9975
9976 fl := &cc.flow
9977 if cs != nil {
9978 fl = &cs.flow
9979 }
9980 if !fl.add(int32(f.Increment)) {
9981 return http2ConnectionError(http2ErrCodeFlowControl)
9982 }
9983 cc.cond.Broadcast()
9984 return nil
9985 }
9986
9987 func (rl *http2clientConnReadLoop) processResetStream(f *http2RSTStreamFrame) error {
9988 cs := rl.streamByID(f.StreamID)
9989 if cs == nil {
9990
9991 return nil
9992 }
9993 serr := http2streamError(cs.ID, f.ErrCode)
9994 serr.Cause = http2errFromPeer
9995 if f.ErrCode == http2ErrCodeProtocol {
9996 rl.cc.SetDoNotReuse()
9997 }
9998 if fn := cs.cc.t.CountError; fn != nil {
9999 fn("recv_rststream_" + f.ErrCode.stringToken())
10000 }
10001 cs.abortStream(serr)
10002
10003 cs.bufPipe.CloseWithError(serr)
10004 return nil
10005 }
10006
10007
10008 func (cc *http2ClientConn) Ping(ctx context.Context) error {
10009 c := make(chan struct{})
10010
10011 var p [8]byte
10012 for {
10013 if _, err := rand.Read(p[:]); err != nil {
10014 return err
10015 }
10016 cc.mu.Lock()
10017
10018 if _, found := cc.pings[p]; !found {
10019 cc.pings[p] = c
10020 cc.mu.Unlock()
10021 break
10022 }
10023 cc.mu.Unlock()
10024 }
10025 errc := make(chan error, 1)
10026 go func() {
10027 cc.wmu.Lock()
10028 defer cc.wmu.Unlock()
10029 if err := cc.fr.WritePing(false, p); err != nil {
10030 errc <- err
10031 return
10032 }
10033 if err := cc.bw.Flush(); err != nil {
10034 errc <- err
10035 return
10036 }
10037 }()
10038 select {
10039 case <-c:
10040 return nil
10041 case err := <-errc:
10042 return err
10043 case <-ctx.Done():
10044 return ctx.Err()
10045 case <-cc.readerDone:
10046
10047 return cc.readerErr
10048 }
10049 }
10050
10051 func (rl *http2clientConnReadLoop) processPing(f *http2PingFrame) error {
10052 if f.IsAck() {
10053 cc := rl.cc
10054 cc.mu.Lock()
10055 defer cc.mu.Unlock()
10056
10057 if c, ok := cc.pings[f.Data]; ok {
10058 close(c)
10059 delete(cc.pings, f.Data)
10060 }
10061 return nil
10062 }
10063 cc := rl.cc
10064 cc.wmu.Lock()
10065 defer cc.wmu.Unlock()
10066 if err := cc.fr.WritePing(true, f.Data); err != nil {
10067 return err
10068 }
10069 return cc.bw.Flush()
10070 }
10071
10072 func (rl *http2clientConnReadLoop) processPushPromise(f *http2PushPromiseFrame) error {
10073
10074
10075
10076
10077
10078
10079
10080 return http2ConnectionError(http2ErrCodeProtocol)
10081 }
10082
10083 func (cc *http2ClientConn) writeStreamReset(streamID uint32, code http2ErrCode, err error) {
10084
10085
10086
10087
10088 cc.wmu.Lock()
10089 cc.fr.WriteRSTStream(streamID, code)
10090 cc.bw.Flush()
10091 cc.wmu.Unlock()
10092 }
10093
10094 var (
10095 http2errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
10096 http2errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
10097 )
10098
10099 func (cc *http2ClientConn) logf(format string, args ...interface{}) {
10100 cc.t.logf(format, args...)
10101 }
10102
10103 func (cc *http2ClientConn) vlogf(format string, args ...interface{}) {
10104 cc.t.vlogf(format, args...)
10105 }
10106
10107 func (t *http2Transport) vlogf(format string, args ...interface{}) {
10108 if http2VerboseLogs {
10109 t.logf(format, args...)
10110 }
10111 }
10112
10113 func (t *http2Transport) logf(format string, args ...interface{}) {
10114 log.Printf(format, args...)
10115 }
10116
10117 var http2noBody io.ReadCloser = http2noBodyReader{}
10118
10119 type http2noBodyReader struct{}
10120
10121 func (http2noBodyReader) Close() error { return nil }
10122
10123 func (http2noBodyReader) Read([]byte) (int, error) { return 0, io.EOF }
10124
10125 type http2missingBody struct{}
10126
10127 func (http2missingBody) Close() error { return nil }
10128
10129 func (http2missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
10130
10131 func http2strSliceContains(ss []string, s string) bool {
10132 for _, v := range ss {
10133 if v == s {
10134 return true
10135 }
10136 }
10137 return false
10138 }
10139
10140 type http2erringRoundTripper struct{ err error }
10141
10142 func (rt http2erringRoundTripper) RoundTripErr() error { return rt.err }
10143
10144 func (rt http2erringRoundTripper) RoundTrip(*Request) (*Response, error) { return nil, rt.err }
10145
10146
10147
10148 type http2gzipReader struct {
10149 _ http2incomparable
10150 body io.ReadCloser
10151 zr *gzip.Reader
10152 zerr error
10153 }
10154
10155 func (gz *http2gzipReader) Read(p []byte) (n int, err error) {
10156 if gz.zerr != nil {
10157 return 0, gz.zerr
10158 }
10159 if gz.zr == nil {
10160 gz.zr, err = gzip.NewReader(gz.body)
10161 if err != nil {
10162 gz.zerr = err
10163 return 0, err
10164 }
10165 }
10166 return gz.zr.Read(p)
10167 }
10168
10169 func (gz *http2gzipReader) Close() error {
10170 if err := gz.body.Close(); err != nil {
10171 return err
10172 }
10173 gz.zerr = fs.ErrClosed
10174 return nil
10175 }
10176
10177 type http2errorReader struct{ err error }
10178
10179 func (r http2errorReader) Read(p []byte) (int, error) { return 0, r.err }
10180
10181
10182
10183 func http2isConnectionCloseRequest(req *Request) bool {
10184 return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
10185 }
10186
10187
10188
10189 func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error) {
10190 defer func() {
10191 if e := recover(); e != nil {
10192 err = fmt.Errorf("%v", e)
10193 }
10194 }()
10195 t.RegisterProtocol("https", rt)
10196 return nil
10197 }
10198
10199
10200
10201
10202
10203 type http2noDialH2RoundTripper struct{ *http2Transport }
10204
10205 func (rt http2noDialH2RoundTripper) RoundTrip(req *Request) (*Response, error) {
10206 res, err := rt.http2Transport.RoundTrip(req)
10207 if http2isNoCachedConnError(err) {
10208 return nil, ErrSkipAltProtocol
10209 }
10210 return res, err
10211 }
10212
10213 func (t *http2Transport) idleConnTimeout() time.Duration {
10214 if t.t1 != nil {
10215 return t.t1.IdleConnTimeout
10216 }
10217 return 0
10218 }
10219
10220 func http2traceGetConn(req *Request, hostPort string) {
10221 trace := httptrace.ContextClientTrace(req.Context())
10222 if trace == nil || trace.GetConn == nil {
10223 return
10224 }
10225 trace.GetConn(hostPort)
10226 }
10227
10228 func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool) {
10229 trace := httptrace.ContextClientTrace(req.Context())
10230 if trace == nil || trace.GotConn == nil {
10231 return
10232 }
10233 ci := httptrace.GotConnInfo{Conn: cc.tconn}
10234 ci.Reused = reused
10235 cc.mu.Lock()
10236 ci.WasIdle = len(cc.streams) == 0 && reused
10237 if ci.WasIdle && !cc.lastActive.IsZero() {
10238 ci.IdleTime = time.Since(cc.lastActive)
10239 }
10240 cc.mu.Unlock()
10241
10242 trace.GotConn(ci)
10243 }
10244
10245 func http2traceWroteHeaders(trace *httptrace.ClientTrace) {
10246 if trace != nil && trace.WroteHeaders != nil {
10247 trace.WroteHeaders()
10248 }
10249 }
10250
10251 func http2traceGot100Continue(trace *httptrace.ClientTrace) {
10252 if trace != nil && trace.Got100Continue != nil {
10253 trace.Got100Continue()
10254 }
10255 }
10256
10257 func http2traceWait100Continue(trace *httptrace.ClientTrace) {
10258 if trace != nil && trace.Wait100Continue != nil {
10259 trace.Wait100Continue()
10260 }
10261 }
10262
10263 func http2traceWroteRequest(trace *httptrace.ClientTrace, err error) {
10264 if trace != nil && trace.WroteRequest != nil {
10265 trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
10266 }
10267 }
10268
10269 func http2traceFirstResponseByte(trace *httptrace.ClientTrace) {
10270 if trace != nil && trace.GotFirstResponseByte != nil {
10271 trace.GotFirstResponseByte()
10272 }
10273 }
10274
10275 func http2traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool {
10276 return trace != nil && trace.WroteHeaderField != nil
10277 }
10278
10279 func http2traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string) {
10280 if trace != nil && trace.WroteHeaderField != nil {
10281 trace.WroteHeaderField(k, []string{v})
10282 }
10283 }
10284
10285 func http2traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error {
10286 if trace != nil {
10287 return trace.Got1xxResponse
10288 }
10289 return nil
10290 }
10291
10292
10293
10294 func (t *http2Transport) dialTLSWithContext(ctx context.Context, network, addr string, cfg *tls.Config) (*tls.Conn, error) {
10295 dialer := &tls.Dialer{
10296 Config: cfg,
10297 }
10298 cn, err := dialer.DialContext(ctx, network, addr)
10299 if err != nil {
10300 return nil, err
10301 }
10302 tlsCn := cn.(*tls.Conn)
10303 return tlsCn, nil
10304 }
10305
10306
10307 type http2writeFramer interface {
10308 writeFrame(http2writeContext) error
10309
10310
10311
10312
10313 staysWithinBuffer(size int) bool
10314 }
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326 type http2writeContext interface {
10327 Framer() *http2Framer
10328 Flush() error
10329 CloseConn() error
10330
10331
10332 HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
10333 }
10334
10335
10336
10337
10338 func http2writeEndsStream(w http2writeFramer) bool {
10339 switch v := w.(type) {
10340 case *http2writeData:
10341 return v.endStream
10342 case *http2writeResHeaders:
10343 return v.endStream
10344 case nil:
10345
10346
10347
10348 panic("writeEndsStream called on nil writeFramer")
10349 }
10350 return false
10351 }
10352
10353 type http2flushFrameWriter struct{}
10354
10355 func (http2flushFrameWriter) writeFrame(ctx http2writeContext) error {
10356 return ctx.Flush()
10357 }
10358
10359 func (http2flushFrameWriter) staysWithinBuffer(max int) bool { return false }
10360
10361 type http2writeSettings []http2Setting
10362
10363 func (s http2writeSettings) staysWithinBuffer(max int) bool {
10364 const settingSize = 6
10365 return http2frameHeaderLen+settingSize*len(s) <= max
10366
10367 }
10368
10369 func (s http2writeSettings) writeFrame(ctx http2writeContext) error {
10370 return ctx.Framer().WriteSettings([]http2Setting(s)...)
10371 }
10372
10373 type http2writeGoAway struct {
10374 maxStreamID uint32
10375 code http2ErrCode
10376 }
10377
10378 func (p *http2writeGoAway) writeFrame(ctx http2writeContext) error {
10379 err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
10380 ctx.Flush()
10381 return err
10382 }
10383
10384 func (*http2writeGoAway) staysWithinBuffer(max int) bool { return false }
10385
10386 type http2writeData struct {
10387 streamID uint32
10388 p []byte
10389 endStream bool
10390 }
10391
10392 func (w *http2writeData) String() string {
10393 return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
10394 }
10395
10396 func (w *http2writeData) writeFrame(ctx http2writeContext) error {
10397 return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
10398 }
10399
10400 func (w *http2writeData) staysWithinBuffer(max int) bool {
10401 return http2frameHeaderLen+len(w.p) <= max
10402 }
10403
10404
10405
10406 type http2handlerPanicRST struct {
10407 StreamID uint32
10408 }
10409
10410 func (hp http2handlerPanicRST) writeFrame(ctx http2writeContext) error {
10411 return ctx.Framer().WriteRSTStream(hp.StreamID, http2ErrCodeInternal)
10412 }
10413
10414 func (hp http2handlerPanicRST) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
10415
10416 func (se http2StreamError) writeFrame(ctx http2writeContext) error {
10417 return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
10418 }
10419
10420 func (se http2StreamError) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
10421
10422 type http2writePingAck struct{ pf *http2PingFrame }
10423
10424 func (w http2writePingAck) writeFrame(ctx http2writeContext) error {
10425 return ctx.Framer().WritePing(true, w.pf.Data)
10426 }
10427
10428 func (w http2writePingAck) staysWithinBuffer(max int) bool {
10429 return http2frameHeaderLen+len(w.pf.Data) <= max
10430 }
10431
10432 type http2writeSettingsAck struct{}
10433
10434 func (http2writeSettingsAck) writeFrame(ctx http2writeContext) error {
10435 return ctx.Framer().WriteSettingsAck()
10436 }
10437
10438 func (http2writeSettingsAck) staysWithinBuffer(max int) bool { return http2frameHeaderLen <= max }
10439
10440
10441
10442
10443 func http2splitHeaderBlock(ctx http2writeContext, headerBlock []byte, fn func(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error) error {
10444
10445
10446
10447
10448
10449
10450 const maxFrameSize = 16384
10451
10452 first := true
10453 for len(headerBlock) > 0 {
10454 frag := headerBlock
10455 if len(frag) > maxFrameSize {
10456 frag = frag[:maxFrameSize]
10457 }
10458 headerBlock = headerBlock[len(frag):]
10459 if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil {
10460 return err
10461 }
10462 first = false
10463 }
10464 return nil
10465 }
10466
10467
10468
10469 type http2writeResHeaders struct {
10470 streamID uint32
10471 httpResCode int
10472 h Header
10473 trailers []string
10474 endStream bool
10475
10476 date string
10477 contentType string
10478 contentLength string
10479 }
10480
10481 func http2encKV(enc *hpack.Encoder, k, v string) {
10482 if http2VerboseLogs {
10483 log.Printf("http2: server encoding header %q = %q", k, v)
10484 }
10485 enc.WriteField(hpack.HeaderField{Name: k, Value: v})
10486 }
10487
10488 func (w *http2writeResHeaders) staysWithinBuffer(max int) bool {
10489
10490
10491
10492
10493
10494
10495
10496 return false
10497 }
10498
10499 func (w *http2writeResHeaders) writeFrame(ctx http2writeContext) error {
10500 enc, buf := ctx.HeaderEncoder()
10501 buf.Reset()
10502
10503 if w.httpResCode != 0 {
10504 http2encKV(enc, ":status", http2httpCodeString(w.httpResCode))
10505 }
10506
10507 http2encodeHeaders(enc, w.h, w.trailers)
10508
10509 if w.contentType != "" {
10510 http2encKV(enc, "content-type", w.contentType)
10511 }
10512 if w.contentLength != "" {
10513 http2encKV(enc, "content-length", w.contentLength)
10514 }
10515 if w.date != "" {
10516 http2encKV(enc, "date", w.date)
10517 }
10518
10519 headerBlock := buf.Bytes()
10520 if len(headerBlock) == 0 && w.trailers == nil {
10521 panic("unexpected empty hpack")
10522 }
10523
10524 return http2splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
10525 }
10526
10527 func (w *http2writeResHeaders) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error {
10528 if firstFrag {
10529 return ctx.Framer().WriteHeaders(http2HeadersFrameParam{
10530 StreamID: w.streamID,
10531 BlockFragment: frag,
10532 EndStream: w.endStream,
10533 EndHeaders: lastFrag,
10534 })
10535 } else {
10536 return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
10537 }
10538 }
10539
10540
10541 type http2writePushPromise struct {
10542 streamID uint32
10543 method string
10544 url *url.URL
10545 h Header
10546
10547
10548
10549 allocatePromisedID func() (uint32, error)
10550 promisedID uint32
10551 }
10552
10553 func (w *http2writePushPromise) staysWithinBuffer(max int) bool {
10554
10555 return false
10556 }
10557
10558 func (w *http2writePushPromise) writeFrame(ctx http2writeContext) error {
10559 enc, buf := ctx.HeaderEncoder()
10560 buf.Reset()
10561
10562 http2encKV(enc, ":method", w.method)
10563 http2encKV(enc, ":scheme", w.url.Scheme)
10564 http2encKV(enc, ":authority", w.url.Host)
10565 http2encKV(enc, ":path", w.url.RequestURI())
10566 http2encodeHeaders(enc, w.h, nil)
10567
10568 headerBlock := buf.Bytes()
10569 if len(headerBlock) == 0 {
10570 panic("unexpected empty hpack")
10571 }
10572
10573 return http2splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
10574 }
10575
10576 func (w *http2writePushPromise) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error {
10577 if firstFrag {
10578 return ctx.Framer().WritePushPromise(http2PushPromiseParam{
10579 StreamID: w.streamID,
10580 PromiseID: w.promisedID,
10581 BlockFragment: frag,
10582 EndHeaders: lastFrag,
10583 })
10584 } else {
10585 return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
10586 }
10587 }
10588
10589 type http2write100ContinueHeadersFrame struct {
10590 streamID uint32
10591 }
10592
10593 func (w http2write100ContinueHeadersFrame) writeFrame(ctx http2writeContext) error {
10594 enc, buf := ctx.HeaderEncoder()
10595 buf.Reset()
10596 http2encKV(enc, ":status", "100")
10597 return ctx.Framer().WriteHeaders(http2HeadersFrameParam{
10598 StreamID: w.streamID,
10599 BlockFragment: buf.Bytes(),
10600 EndStream: false,
10601 EndHeaders: true,
10602 })
10603 }
10604
10605 func (w http2write100ContinueHeadersFrame) staysWithinBuffer(max int) bool {
10606
10607 return 9+2*(len(":status")+len("100")) <= max
10608 }
10609
10610 type http2writeWindowUpdate struct {
10611 streamID uint32
10612 n uint32
10613 }
10614
10615 func (wu http2writeWindowUpdate) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
10616
10617 func (wu http2writeWindowUpdate) writeFrame(ctx http2writeContext) error {
10618 return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
10619 }
10620
10621
10622
10623 func http2encodeHeaders(enc *hpack.Encoder, h Header, keys []string) {
10624 if keys == nil {
10625 sorter := http2sorterPool.Get().(*http2sorter)
10626
10627
10628
10629 defer http2sorterPool.Put(sorter)
10630 keys = sorter.Keys(h)
10631 }
10632 for _, k := range keys {
10633 vv := h[k]
10634 k, ascii := http2lowerHeader(k)
10635 if !ascii {
10636
10637
10638 continue
10639 }
10640 if !http2validWireHeaderFieldName(k) {
10641
10642
10643
10644 continue
10645 }
10646 isTE := k == "transfer-encoding"
10647 for _, v := range vv {
10648 if !httpguts.ValidHeaderFieldValue(v) {
10649
10650
10651 continue
10652 }
10653
10654 if isTE && v != "trailers" {
10655 continue
10656 }
10657 http2encKV(enc, k, v)
10658 }
10659 }
10660 }
10661
10662
10663
10664 type http2WriteScheduler interface {
10665
10666
10667
10668 OpenStream(streamID uint32, options http2OpenStreamOptions)
10669
10670
10671
10672
10673 CloseStream(streamID uint32)
10674
10675
10676
10677
10678
10679 AdjustStream(streamID uint32, priority http2PriorityParam)
10680
10681
10682
10683
10684 Push(wr http2FrameWriteRequest)
10685
10686
10687
10688
10689
10690 Pop() (wr http2FrameWriteRequest, ok bool)
10691 }
10692
10693
10694 type http2OpenStreamOptions struct {
10695
10696
10697 PusherID uint32
10698 }
10699
10700
10701 type http2FrameWriteRequest struct {
10702
10703
10704
10705 write http2writeFramer
10706
10707
10708
10709
10710 stream *http2stream
10711
10712
10713
10714
10715 done chan error
10716 }
10717
10718
10719
10720 func (wr http2FrameWriteRequest) StreamID() uint32 {
10721 if wr.stream == nil {
10722 if se, ok := wr.write.(http2StreamError); ok {
10723
10724
10725
10726
10727 return se.StreamID
10728 }
10729 return 0
10730 }
10731 return wr.stream.id
10732 }
10733
10734
10735
10736 func (wr http2FrameWriteRequest) isControl() bool {
10737 return wr.stream == nil
10738 }
10739
10740
10741
10742 func (wr http2FrameWriteRequest) DataSize() int {
10743 if wd, ok := wr.write.(*http2writeData); ok {
10744 return len(wd.p)
10745 }
10746 return 0
10747 }
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759 func (wr http2FrameWriteRequest) Consume(n int32) (http2FrameWriteRequest, http2FrameWriteRequest, int) {
10760 var empty http2FrameWriteRequest
10761
10762
10763 wd, ok := wr.write.(*http2writeData)
10764 if !ok || len(wd.p) == 0 {
10765 return wr, empty, 1
10766 }
10767
10768
10769 allowed := wr.stream.flow.available()
10770 if n < allowed {
10771 allowed = n
10772 }
10773 if wr.stream.sc.maxFrameSize < allowed {
10774 allowed = wr.stream.sc.maxFrameSize
10775 }
10776 if allowed <= 0 {
10777 return empty, empty, 0
10778 }
10779 if len(wd.p) > int(allowed) {
10780 wr.stream.flow.take(allowed)
10781 consumed := http2FrameWriteRequest{
10782 stream: wr.stream,
10783 write: &http2writeData{
10784 streamID: wd.streamID,
10785 p: wd.p[:allowed],
10786
10787
10788
10789 endStream: false,
10790 },
10791
10792
10793 done: nil,
10794 }
10795 rest := http2FrameWriteRequest{
10796 stream: wr.stream,
10797 write: &http2writeData{
10798 streamID: wd.streamID,
10799 p: wd.p[allowed:],
10800 endStream: wd.endStream,
10801 },
10802 done: wr.done,
10803 }
10804 return consumed, rest, 2
10805 }
10806
10807
10808
10809 wr.stream.flow.take(int32(len(wd.p)))
10810 return wr, empty, 1
10811 }
10812
10813
10814 func (wr http2FrameWriteRequest) String() string {
10815 var des string
10816 if s, ok := wr.write.(fmt.Stringer); ok {
10817 des = s.String()
10818 } else {
10819 des = fmt.Sprintf("%T", wr.write)
10820 }
10821 return fmt.Sprintf("[FrameWriteRequest stream=%d, ch=%v, writer=%v]", wr.StreamID(), wr.done != nil, des)
10822 }
10823
10824
10825
10826 func (wr *http2FrameWriteRequest) replyToWriter(err error) {
10827 if wr.done == nil {
10828 return
10829 }
10830 select {
10831 case wr.done <- err:
10832 default:
10833 panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write))
10834 }
10835 wr.write = nil
10836 }
10837
10838
10839 type http2writeQueue struct {
10840 s []http2FrameWriteRequest
10841 prev, next *http2writeQueue
10842 }
10843
10844 func (q *http2writeQueue) empty() bool { return len(q.s) == 0 }
10845
10846 func (q *http2writeQueue) push(wr http2FrameWriteRequest) {
10847 q.s = append(q.s, wr)
10848 }
10849
10850 func (q *http2writeQueue) shift() http2FrameWriteRequest {
10851 if len(q.s) == 0 {
10852 panic("invalid use of queue")
10853 }
10854 wr := q.s[0]
10855
10856 copy(q.s, q.s[1:])
10857 q.s[len(q.s)-1] = http2FrameWriteRequest{}
10858 q.s = q.s[:len(q.s)-1]
10859 return wr
10860 }
10861
10862
10863
10864
10865
10866 func (q *http2writeQueue) consume(n int32) (http2FrameWriteRequest, bool) {
10867 if len(q.s) == 0 {
10868 return http2FrameWriteRequest{}, false
10869 }
10870 consumed, rest, numresult := q.s[0].Consume(n)
10871 switch numresult {
10872 case 0:
10873 return http2FrameWriteRequest{}, false
10874 case 1:
10875 q.shift()
10876 case 2:
10877 q.s[0] = rest
10878 }
10879 return consumed, true
10880 }
10881
10882 type http2writeQueuePool []*http2writeQueue
10883
10884
10885
10886
10887 func (p *http2writeQueuePool) put(q *http2writeQueue) {
10888 for i := range q.s {
10889 q.s[i] = http2FrameWriteRequest{}
10890 }
10891 q.s = q.s[:0]
10892 *p = append(*p, q)
10893 }
10894
10895
10896 func (p *http2writeQueuePool) get() *http2writeQueue {
10897 ln := len(*p)
10898 if ln == 0 {
10899 return new(http2writeQueue)
10900 }
10901 x := ln - 1
10902 q := (*p)[x]
10903 (*p)[x] = nil
10904 *p = (*p)[:x]
10905 return q
10906 }
10907
10908
10909 const http2priorityDefaultWeight = 15
10910
10911
10912 type http2PriorityWriteSchedulerConfig struct {
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925 MaxClosedNodesInTree int
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937 MaxIdleNodesInTree int
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947 ThrottleOutOfOrderWrites bool
10948 }
10949
10950
10951
10952
10953 func http2NewPriorityWriteScheduler(cfg *http2PriorityWriteSchedulerConfig) http2WriteScheduler {
10954 if cfg == nil {
10955
10956
10957 cfg = &http2PriorityWriteSchedulerConfig{
10958 MaxClosedNodesInTree: 10,
10959 MaxIdleNodesInTree: 10,
10960 ThrottleOutOfOrderWrites: false,
10961 }
10962 }
10963
10964 ws := &http2priorityWriteScheduler{
10965 nodes: make(map[uint32]*http2priorityNode),
10966 maxClosedNodesInTree: cfg.MaxClosedNodesInTree,
10967 maxIdleNodesInTree: cfg.MaxIdleNodesInTree,
10968 enableWriteThrottle: cfg.ThrottleOutOfOrderWrites,
10969 }
10970 ws.nodes[0] = &ws.root
10971 if cfg.ThrottleOutOfOrderWrites {
10972 ws.writeThrottleLimit = 1024
10973 } else {
10974 ws.writeThrottleLimit = math.MaxInt32
10975 }
10976 return ws
10977 }
10978
10979 type http2priorityNodeState int
10980
10981 const (
10982 http2priorityNodeOpen http2priorityNodeState = iota
10983 http2priorityNodeClosed
10984 http2priorityNodeIdle
10985 )
10986
10987
10988
10989
10990 type http2priorityNode struct {
10991 q http2writeQueue
10992 id uint32
10993 weight uint8
10994 state http2priorityNodeState
10995 bytes int64
10996 subtreeBytes int64
10997
10998
10999 parent *http2priorityNode
11000 kids *http2priorityNode
11001 prev, next *http2priorityNode
11002 }
11003
11004 func (n *http2priorityNode) setParent(parent *http2priorityNode) {
11005 if n == parent {
11006 panic("setParent to self")
11007 }
11008 if n.parent == parent {
11009 return
11010 }
11011
11012 if parent := n.parent; parent != nil {
11013 if n.prev == nil {
11014 parent.kids = n.next
11015 } else {
11016 n.prev.next = n.next
11017 }
11018 if n.next != nil {
11019 n.next.prev = n.prev
11020 }
11021 }
11022
11023
11024
11025 n.parent = parent
11026 if parent == nil {
11027 n.next = nil
11028 n.prev = nil
11029 } else {
11030 n.next = parent.kids
11031 n.prev = nil
11032 if n.next != nil {
11033 n.next.prev = n
11034 }
11035 parent.kids = n
11036 }
11037 }
11038
11039 func (n *http2priorityNode) addBytes(b int64) {
11040 n.bytes += b
11041 for ; n != nil; n = n.parent {
11042 n.subtreeBytes += b
11043 }
11044 }
11045
11046
11047
11048
11049
11050
11051
11052 func (n *http2priorityNode) walkReadyInOrder(openParent bool, tmp *[]*http2priorityNode, f func(*http2priorityNode, bool) bool) bool {
11053 if !n.q.empty() && f(n, openParent) {
11054 return true
11055 }
11056 if n.kids == nil {
11057 return false
11058 }
11059
11060
11061
11062 if n.id != 0 {
11063 openParent = openParent || (n.state == http2priorityNodeOpen)
11064 }
11065
11066
11067
11068
11069 w := n.kids.weight
11070 needSort := false
11071 for k := n.kids.next; k != nil; k = k.next {
11072 if k.weight != w {
11073 needSort = true
11074 break
11075 }
11076 }
11077 if !needSort {
11078 for k := n.kids; k != nil; k = k.next {
11079 if k.walkReadyInOrder(openParent, tmp, f) {
11080 return true
11081 }
11082 }
11083 return false
11084 }
11085
11086
11087
11088 *tmp = (*tmp)[:0]
11089 for n.kids != nil {
11090 *tmp = append(*tmp, n.kids)
11091 n.kids.setParent(nil)
11092 }
11093 sort.Sort(http2sortPriorityNodeSiblings(*tmp))
11094 for i := len(*tmp) - 1; i >= 0; i-- {
11095 (*tmp)[i].setParent(n)
11096 }
11097 for k := n.kids; k != nil; k = k.next {
11098 if k.walkReadyInOrder(openParent, tmp, f) {
11099 return true
11100 }
11101 }
11102 return false
11103 }
11104
11105 type http2sortPriorityNodeSiblings []*http2priorityNode
11106
11107 func (z http2sortPriorityNodeSiblings) Len() int { return len(z) }
11108
11109 func (z http2sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] }
11110
11111 func (z http2sortPriorityNodeSiblings) Less(i, k int) bool {
11112
11113
11114 wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes)
11115 wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes)
11116 if bi == 0 && bk == 0 {
11117 return wi >= wk
11118 }
11119 if bk == 0 {
11120 return false
11121 }
11122 return bi/bk <= wi/wk
11123 }
11124
11125 type http2priorityWriteScheduler struct {
11126
11127
11128 root http2priorityNode
11129
11130
11131 nodes map[uint32]*http2priorityNode
11132
11133
11134 maxID uint32
11135
11136
11137
11138
11139 closedNodes, idleNodes []*http2priorityNode
11140
11141
11142 maxClosedNodesInTree int
11143 maxIdleNodesInTree int
11144 writeThrottleLimit int32
11145 enableWriteThrottle bool
11146
11147
11148 tmp []*http2priorityNode
11149
11150
11151 queuePool http2writeQueuePool
11152 }
11153
11154 func (ws *http2priorityWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
11155
11156 if curr := ws.nodes[streamID]; curr != nil {
11157 if curr.state != http2priorityNodeIdle {
11158 panic(fmt.Sprintf("stream %d already opened", streamID))
11159 }
11160 curr.state = http2priorityNodeOpen
11161 return
11162 }
11163
11164
11165
11166
11167
11168 parent := ws.nodes[options.PusherID]
11169 if parent == nil {
11170 parent = &ws.root
11171 }
11172 n := &http2priorityNode{
11173 q: *ws.queuePool.get(),
11174 id: streamID,
11175 weight: http2priorityDefaultWeight,
11176 state: http2priorityNodeOpen,
11177 }
11178 n.setParent(parent)
11179 ws.nodes[streamID] = n
11180 if streamID > ws.maxID {
11181 ws.maxID = streamID
11182 }
11183 }
11184
11185 func (ws *http2priorityWriteScheduler) CloseStream(streamID uint32) {
11186 if streamID == 0 {
11187 panic("violation of WriteScheduler interface: cannot close stream 0")
11188 }
11189 if ws.nodes[streamID] == nil {
11190 panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID))
11191 }
11192 if ws.nodes[streamID].state != http2priorityNodeOpen {
11193 panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID))
11194 }
11195
11196 n := ws.nodes[streamID]
11197 n.state = http2priorityNodeClosed
11198 n.addBytes(-n.bytes)
11199
11200 q := n.q
11201 ws.queuePool.put(&q)
11202 n.q.s = nil
11203 if ws.maxClosedNodesInTree > 0 {
11204 ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n)
11205 } else {
11206 ws.removeNode(n)
11207 }
11208 }
11209
11210 func (ws *http2priorityWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {
11211 if streamID == 0 {
11212 panic("adjustPriority on root")
11213 }
11214
11215
11216
11217
11218 n := ws.nodes[streamID]
11219 if n == nil {
11220 if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 {
11221 return
11222 }
11223 ws.maxID = streamID
11224 n = &http2priorityNode{
11225 q: *ws.queuePool.get(),
11226 id: streamID,
11227 weight: http2priorityDefaultWeight,
11228 state: http2priorityNodeIdle,
11229 }
11230 n.setParent(&ws.root)
11231 ws.nodes[streamID] = n
11232 ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n)
11233 }
11234
11235
11236
11237 parent := ws.nodes[priority.StreamDep]
11238 if parent == nil {
11239 n.setParent(&ws.root)
11240 n.weight = http2priorityDefaultWeight
11241 return
11242 }
11243
11244
11245 if n == parent {
11246 return
11247 }
11248
11249
11250
11251
11252
11253
11254
11255
11256 for x := parent.parent; x != nil; x = x.parent {
11257 if x == n {
11258 parent.setParent(n.parent)
11259 break
11260 }
11261 }
11262
11263
11264
11265
11266 if priority.Exclusive {
11267 k := parent.kids
11268 for k != nil {
11269 next := k.next
11270 if k != n {
11271 k.setParent(n)
11272 }
11273 k = next
11274 }
11275 }
11276
11277 n.setParent(parent)
11278 n.weight = priority.Weight
11279 }
11280
11281 func (ws *http2priorityWriteScheduler) Push(wr http2FrameWriteRequest) {
11282 var n *http2priorityNode
11283 if wr.isControl() {
11284 n = &ws.root
11285 } else {
11286 id := wr.StreamID()
11287 n = ws.nodes[id]
11288 if n == nil {
11289
11290
11291
11292 if wr.DataSize() > 0 {
11293 panic("add DATA on non-open stream")
11294 }
11295 n = &ws.root
11296 }
11297 }
11298 n.q.push(wr)
11299 }
11300
11301 func (ws *http2priorityWriteScheduler) Pop() (wr http2FrameWriteRequest, ok bool) {
11302 ws.root.walkReadyInOrder(false, &ws.tmp, func(n *http2priorityNode, openParent bool) bool {
11303 limit := int32(math.MaxInt32)
11304 if openParent {
11305 limit = ws.writeThrottleLimit
11306 }
11307 wr, ok = n.q.consume(limit)
11308 if !ok {
11309 return false
11310 }
11311 n.addBytes(int64(wr.DataSize()))
11312
11313
11314
11315 if openParent {
11316 ws.writeThrottleLimit += 1024
11317 if ws.writeThrottleLimit < 0 {
11318 ws.writeThrottleLimit = math.MaxInt32
11319 }
11320 } else if ws.enableWriteThrottle {
11321 ws.writeThrottleLimit = 1024
11322 }
11323 return true
11324 })
11325 return wr, ok
11326 }
11327
11328 func (ws *http2priorityWriteScheduler) addClosedOrIdleNode(list *[]*http2priorityNode, maxSize int, n *http2priorityNode) {
11329 if maxSize == 0 {
11330 return
11331 }
11332 if len(*list) == maxSize {
11333
11334 ws.removeNode((*list)[0])
11335 x := (*list)[1:]
11336 copy(*list, x)
11337 *list = (*list)[:len(x)]
11338 }
11339 *list = append(*list, n)
11340 }
11341
11342 func (ws *http2priorityWriteScheduler) removeNode(n *http2priorityNode) {
11343 for k := n.kids; k != nil; k = k.next {
11344 k.setParent(n.parent)
11345 }
11346 n.setParent(nil)
11347 delete(ws.nodes, n.id)
11348 }
11349
11350
11351
11352
11353
11354 func http2NewRandomWriteScheduler() http2WriteScheduler {
11355 return &http2randomWriteScheduler{sq: make(map[uint32]*http2writeQueue)}
11356 }
11357
11358 type http2randomWriteScheduler struct {
11359
11360 zero http2writeQueue
11361
11362
11363
11364
11365 sq map[uint32]*http2writeQueue
11366
11367
11368 queuePool http2writeQueuePool
11369 }
11370
11371 func (ws *http2randomWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
11372
11373 }
11374
11375 func (ws *http2randomWriteScheduler) CloseStream(streamID uint32) {
11376 q, ok := ws.sq[streamID]
11377 if !ok {
11378 return
11379 }
11380 delete(ws.sq, streamID)
11381 ws.queuePool.put(q)
11382 }
11383
11384 func (ws *http2randomWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {
11385
11386 }
11387
11388 func (ws *http2randomWriteScheduler) Push(wr http2FrameWriteRequest) {
11389 if wr.isControl() {
11390 ws.zero.push(wr)
11391 return
11392 }
11393 id := wr.StreamID()
11394 q, ok := ws.sq[id]
11395 if !ok {
11396 q = ws.queuePool.get()
11397 ws.sq[id] = q
11398 }
11399 q.push(wr)
11400 }
11401
11402 func (ws *http2randomWriteScheduler) Pop() (http2FrameWriteRequest, bool) {
11403
11404 if !ws.zero.empty() {
11405 return ws.zero.shift(), true
11406 }
11407
11408 for streamID, q := range ws.sq {
11409 if wr, ok := q.consume(math.MaxInt32); ok {
11410 if q.empty() {
11411 delete(ws.sq, streamID)
11412 ws.queuePool.put(q)
11413 }
11414 return wr, true
11415 }
11416 }
11417 return http2FrameWriteRequest{}, false
11418 }
11419
11420 type http2roundRobinWriteScheduler struct {
11421
11422 control http2writeQueue
11423
11424
11425 streams map[uint32]*http2writeQueue
11426
11427
11428
11429 head *http2writeQueue
11430
11431
11432 queuePool http2writeQueuePool
11433 }
11434
11435
11436
11437
11438
11439
11440 func http2newRoundRobinWriteScheduler() http2WriteScheduler {
11441 ws := &http2roundRobinWriteScheduler{
11442 streams: make(map[uint32]*http2writeQueue),
11443 }
11444 return ws
11445 }
11446
11447 func (ws *http2roundRobinWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
11448 if ws.streams[streamID] != nil {
11449 panic(fmt.Errorf("stream %d already opened", streamID))
11450 }
11451 q := ws.queuePool.get()
11452 ws.streams[streamID] = q
11453 if ws.head == nil {
11454 ws.head = q
11455 q.next = q
11456 q.prev = q
11457 } else {
11458
11459
11460 q.prev = ws.head.prev
11461 q.next = ws.head
11462 q.prev.next = q
11463 q.next.prev = q
11464 }
11465 }
11466
11467 func (ws *http2roundRobinWriteScheduler) CloseStream(streamID uint32) {
11468 q := ws.streams[streamID]
11469 if q == nil {
11470 return
11471 }
11472 if q.next == q {
11473
11474 ws.head = nil
11475 } else {
11476 q.prev.next = q.next
11477 q.next.prev = q.prev
11478 if ws.head == q {
11479 ws.head = q.next
11480 }
11481 }
11482 delete(ws.streams, streamID)
11483 ws.queuePool.put(q)
11484 }
11485
11486 func (ws *http2roundRobinWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {}
11487
11488 func (ws *http2roundRobinWriteScheduler) Push(wr http2FrameWriteRequest) {
11489 if wr.isControl() {
11490 ws.control.push(wr)
11491 return
11492 }
11493 q := ws.streams[wr.StreamID()]
11494 if q == nil {
11495
11496
11497
11498 if wr.DataSize() > 0 {
11499 panic("add DATA on non-open stream")
11500 }
11501 ws.control.push(wr)
11502 return
11503 }
11504 q.push(wr)
11505 }
11506
11507 func (ws *http2roundRobinWriteScheduler) Pop() (http2FrameWriteRequest, bool) {
11508
11509 if !ws.control.empty() {
11510 return ws.control.shift(), true
11511 }
11512 if ws.head == nil {
11513 return http2FrameWriteRequest{}, false
11514 }
11515 q := ws.head
11516 for {
11517 if wr, ok := q.consume(math.MaxInt32); ok {
11518 ws.head = q.next
11519 return wr, true
11520 }
11521 q = q.next
11522 if q == ws.head {
11523 break
11524 }
11525 }
11526 return http2FrameWriteRequest{}, false
11527 }
11528
View as plain text