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