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