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