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