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