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