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