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 http2closeWaiter chan struct{}
3530
3531
3532
3533
3534
3535 func (cw *http2closeWaiter) Init() {
3536 *cw = make(chan struct{})
3537 }
3538
3539
3540 func (cw http2closeWaiter) Close() {
3541 close(cw)
3542 }
3543
3544
3545 func (cw http2closeWaiter) Wait() {
3546 <-cw
3547 }
3548
3549
3550
3551
3552 type http2bufferedWriter struct {
3553 _ http2incomparable
3554 w io.Writer
3555 bw *bufio.Writer
3556 }
3557
3558 func http2newBufferedWriter(w io.Writer) *http2bufferedWriter {
3559 return &http2bufferedWriter{w: w}
3560 }
3561
3562
3563
3564
3565
3566
3567
3568 const http2bufWriterPoolBufferSize = 4 << 10
3569
3570 var http2bufWriterPool = sync.Pool{
3571 New: func() interface{} {
3572 return bufio.NewWriterSize(nil, http2bufWriterPoolBufferSize)
3573 },
3574 }
3575
3576 func (w *http2bufferedWriter) Available() int {
3577 if w.bw == nil {
3578 return http2bufWriterPoolBufferSize
3579 }
3580 return w.bw.Available()
3581 }
3582
3583 func (w *http2bufferedWriter) Write(p []byte) (n int, err error) {
3584 if w.bw == nil {
3585 bw := http2bufWriterPool.Get().(*bufio.Writer)
3586 bw.Reset(w.w)
3587 w.bw = bw
3588 }
3589 return w.bw.Write(p)
3590 }
3591
3592 func (w *http2bufferedWriter) Flush() error {
3593 bw := w.bw
3594 if bw == nil {
3595 return nil
3596 }
3597 err := bw.Flush()
3598 bw.Reset(nil)
3599 http2bufWriterPool.Put(bw)
3600 w.bw = nil
3601 return err
3602 }
3603
3604 func http2mustUint31(v int32) uint32 {
3605 if v < 0 || v > 2147483647 {
3606 panic("out of range")
3607 }
3608 return uint32(v)
3609 }
3610
3611
3612
3613 func http2bodyAllowedForStatus(status int) bool {
3614 switch {
3615 case status >= 100 && status <= 199:
3616 return false
3617 case status == 204:
3618 return false
3619 case status == 304:
3620 return false
3621 }
3622 return true
3623 }
3624
3625 type http2httpError struct {
3626 _ http2incomparable
3627 msg string
3628 timeout bool
3629 }
3630
3631 func (e *http2httpError) Error() string { return e.msg }
3632
3633 func (e *http2httpError) Timeout() bool { return e.timeout }
3634
3635 func (e *http2httpError) Temporary() bool { return true }
3636
3637 var http2errTimeout error = &http2httpError{msg: "http2: timeout awaiting response headers", timeout: true}
3638
3639 type http2connectionStater interface {
3640 ConnectionState() tls.ConnectionState
3641 }
3642
3643 var http2sorterPool = sync.Pool{New: func() interface{} { return new(http2sorter) }}
3644
3645 type http2sorter struct {
3646 v []string
3647 }
3648
3649 func (s *http2sorter) Len() int { return len(s.v) }
3650
3651 func (s *http2sorter) Swap(i, j int) { s.v[i], s.v[j] = s.v[j], s.v[i] }
3652
3653 func (s *http2sorter) Less(i, j int) bool { return s.v[i] < s.v[j] }
3654
3655
3656
3657
3658
3659 func (s *http2sorter) Keys(h Header) []string {
3660 keys := s.v[:0]
3661 for k := range h {
3662 keys = append(keys, k)
3663 }
3664 s.v = keys
3665 sort.Sort(s)
3666 return keys
3667 }
3668
3669 func (s *http2sorter) SortStrings(ss []string) {
3670
3671
3672 save := s.v
3673 s.v = ss
3674 sort.Sort(s)
3675 s.v = save
3676 }
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691 func http2validPseudoPath(v string) bool {
3692 return (len(v) > 0 && v[0] == '/') || v == "*"
3693 }
3694
3695
3696
3697
3698 type http2incomparable [0]func()
3699
3700
3701
3702
3703 type http2synctestGroupInterface interface {
3704 Join()
3705 Now() time.Time
3706 NewTimer(d time.Duration) http2timer
3707 AfterFunc(d time.Duration, f func()) http2timer
3708 ContextWithTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc)
3709 }
3710
3711
3712
3713
3714 type http2pipe struct {
3715 mu sync.Mutex
3716 c sync.Cond
3717 b http2pipeBuffer
3718 unread int
3719 err error
3720 breakErr error
3721 donec chan struct{}
3722 readFn func()
3723 }
3724
3725 type http2pipeBuffer interface {
3726 Len() int
3727 io.Writer
3728 io.Reader
3729 }
3730
3731
3732
3733 func (p *http2pipe) setBuffer(b http2pipeBuffer) {
3734 p.mu.Lock()
3735 defer p.mu.Unlock()
3736 if p.err != nil || p.breakErr != nil {
3737 return
3738 }
3739 p.b = b
3740 }
3741
3742 func (p *http2pipe) Len() int {
3743 p.mu.Lock()
3744 defer p.mu.Unlock()
3745 if p.b == nil {
3746 return p.unread
3747 }
3748 return p.b.Len()
3749 }
3750
3751
3752
3753 func (p *http2pipe) Read(d []byte) (n int, err error) {
3754 p.mu.Lock()
3755 defer p.mu.Unlock()
3756 if p.c.L == nil {
3757 p.c.L = &p.mu
3758 }
3759 for {
3760 if p.breakErr != nil {
3761 return 0, p.breakErr
3762 }
3763 if p.b != nil && p.b.Len() > 0 {
3764 return p.b.Read(d)
3765 }
3766 if p.err != nil {
3767 if p.readFn != nil {
3768 p.readFn()
3769 p.readFn = nil
3770 }
3771 p.b = nil
3772 return 0, p.err
3773 }
3774 p.c.Wait()
3775 }
3776 }
3777
3778 var (
3779 http2errClosedPipeWrite = errors.New("write on closed buffer")
3780 http2errUninitializedPipeWrite = errors.New("write on uninitialized buffer")
3781 )
3782
3783
3784
3785 func (p *http2pipe) Write(d []byte) (n int, err error) {
3786 p.mu.Lock()
3787 defer p.mu.Unlock()
3788 if p.c.L == nil {
3789 p.c.L = &p.mu
3790 }
3791 defer p.c.Signal()
3792 if p.err != nil || p.breakErr != nil {
3793 return 0, http2errClosedPipeWrite
3794 }
3795
3796
3797
3798 if p.b == nil {
3799 return 0, http2errUninitializedPipeWrite
3800 }
3801 return p.b.Write(d)
3802 }
3803
3804
3805
3806
3807
3808
3809 func (p *http2pipe) CloseWithError(err error) { p.closeWithError(&p.err, err, nil) }
3810
3811
3812
3813
3814 func (p *http2pipe) BreakWithError(err error) { p.closeWithError(&p.breakErr, err, nil) }
3815
3816
3817
3818 func (p *http2pipe) closeWithErrorAndCode(err error, fn func()) { p.closeWithError(&p.err, err, fn) }
3819
3820 func (p *http2pipe) closeWithError(dst *error, err error, fn func()) {
3821 if err == nil {
3822 panic("err must be non-nil")
3823 }
3824 p.mu.Lock()
3825 defer p.mu.Unlock()
3826 if p.c.L == nil {
3827 p.c.L = &p.mu
3828 }
3829 defer p.c.Signal()
3830 if *dst != nil {
3831
3832 return
3833 }
3834 p.readFn = fn
3835 if dst == &p.breakErr {
3836 if p.b != nil {
3837 p.unread += p.b.Len()
3838 }
3839 p.b = nil
3840 }
3841 *dst = err
3842 p.closeDoneLocked()
3843 }
3844
3845
3846 func (p *http2pipe) closeDoneLocked() {
3847 if p.donec == nil {
3848 return
3849 }
3850
3851
3852 select {
3853 case <-p.donec:
3854 default:
3855 close(p.donec)
3856 }
3857 }
3858
3859
3860 func (p *http2pipe) Err() error {
3861 p.mu.Lock()
3862 defer p.mu.Unlock()
3863 if p.breakErr != nil {
3864 return p.breakErr
3865 }
3866 return p.err
3867 }
3868
3869
3870
3871 func (p *http2pipe) Done() <-chan struct{} {
3872 p.mu.Lock()
3873 defer p.mu.Unlock()
3874 if p.donec == nil {
3875 p.donec = make(chan struct{})
3876 if p.err != nil || p.breakErr != nil {
3877
3878 p.closeDoneLocked()
3879 }
3880 }
3881 return p.donec
3882 }
3883
3884 const (
3885 http2prefaceTimeout = 10 * time.Second
3886 http2firstSettingsTimeout = 2 * time.Second
3887 http2handlerChunkWriteSize = 4 << 10
3888 http2defaultMaxStreams = 250
3889 http2maxQueuedControlFrames = 10000
3890 )
3891
3892 var (
3893 http2errClientDisconnected = errors.New("client disconnected")
3894 http2errClosedBody = errors.New("body closed by handler")
3895 http2errHandlerComplete = errors.New("http2: request body closed due to handler exiting")
3896 http2errStreamClosed = errors.New("http2: stream closed")
3897 )
3898
3899 var http2responseWriterStatePool = sync.Pool{
3900 New: func() interface{} {
3901 rws := &http2responseWriterState{}
3902 rws.bw = bufio.NewWriterSize(http2chunkWriter{rws}, http2handlerChunkWriteSize)
3903 return rws
3904 },
3905 }
3906
3907
3908 var (
3909 http2testHookOnConn func()
3910 http2testHookGetServerConn func(*http2serverConn)
3911 http2testHookOnPanicMu *sync.Mutex
3912 http2testHookOnPanic func(sc *http2serverConn, panicVal interface{}) (rePanic bool)
3913 )
3914
3915
3916 type http2Server struct {
3917
3918
3919
3920
3921 MaxHandlers int
3922
3923
3924
3925
3926
3927
3928
3929 MaxConcurrentStreams uint32
3930
3931
3932
3933
3934
3935
3936 MaxDecoderHeaderTableSize uint32
3937
3938
3939
3940
3941
3942 MaxEncoderHeaderTableSize uint32
3943
3944
3945
3946
3947
3948 MaxReadFrameSize uint32
3949
3950
3951
3952 PermitProhibitedCipherSuites bool
3953
3954
3955
3956
3957
3958 IdleTimeout time.Duration
3959
3960
3961
3962
3963
3964
3965 MaxUploadBufferPerConnection int32
3966
3967
3968
3969
3970
3971 MaxUploadBufferPerStream int32
3972
3973
3974
3975 NewWriteScheduler func() http2WriteScheduler
3976
3977
3978
3979
3980
3981 CountError func(errType string)
3982
3983
3984
3985
3986 state *http2serverInternalState
3987
3988
3989
3990 group http2synctestGroupInterface
3991 }
3992
3993 func (s *http2Server) markNewGoroutine() {
3994 if s.group != nil {
3995 s.group.Join()
3996 }
3997 }
3998
3999 func (s *http2Server) now() time.Time {
4000 if s.group != nil {
4001 return s.group.Now()
4002 }
4003 return time.Now()
4004 }
4005
4006
4007 func (s *http2Server) newTimer(d time.Duration) http2timer {
4008 if s.group != nil {
4009 return s.group.NewTimer(d)
4010 }
4011 return http2timeTimer{time.NewTimer(d)}
4012 }
4013
4014
4015 func (s *http2Server) afterFunc(d time.Duration, f func()) http2timer {
4016 if s.group != nil {
4017 return s.group.AfterFunc(d, f)
4018 }
4019 return http2timeTimer{time.AfterFunc(d, f)}
4020 }
4021
4022 func (s *http2Server) initialConnRecvWindowSize() int32 {
4023 if s.MaxUploadBufferPerConnection >= http2initialWindowSize {
4024 return s.MaxUploadBufferPerConnection
4025 }
4026 return 1 << 20
4027 }
4028
4029 func (s *http2Server) initialStreamRecvWindowSize() int32 {
4030 if s.MaxUploadBufferPerStream > 0 {
4031 return s.MaxUploadBufferPerStream
4032 }
4033 return 1 << 20
4034 }
4035
4036 func (s *http2Server) maxReadFrameSize() uint32 {
4037 if v := s.MaxReadFrameSize; v >= http2minMaxFrameSize && v <= http2maxFrameSize {
4038 return v
4039 }
4040 return http2defaultMaxReadFrameSize
4041 }
4042
4043 func (s *http2Server) maxConcurrentStreams() uint32 {
4044 if v := s.MaxConcurrentStreams; v > 0 {
4045 return v
4046 }
4047 return http2defaultMaxStreams
4048 }
4049
4050 func (s *http2Server) maxDecoderHeaderTableSize() uint32 {
4051 if v := s.MaxDecoderHeaderTableSize; v > 0 {
4052 return v
4053 }
4054 return http2initialHeaderTableSize
4055 }
4056
4057 func (s *http2Server) maxEncoderHeaderTableSize() uint32 {
4058 if v := s.MaxEncoderHeaderTableSize; v > 0 {
4059 return v
4060 }
4061 return http2initialHeaderTableSize
4062 }
4063
4064
4065
4066
4067 func (s *http2Server) maxQueuedControlFrames() int {
4068
4069
4070 return http2maxQueuedControlFrames
4071 }
4072
4073 type http2serverInternalState struct {
4074 mu sync.Mutex
4075 activeConns map[*http2serverConn]struct{}
4076 }
4077
4078 func (s *http2serverInternalState) registerConn(sc *http2serverConn) {
4079 if s == nil {
4080 return
4081 }
4082 s.mu.Lock()
4083 s.activeConns[sc] = struct{}{}
4084 s.mu.Unlock()
4085 }
4086
4087 func (s *http2serverInternalState) unregisterConn(sc *http2serverConn) {
4088 if s == nil {
4089 return
4090 }
4091 s.mu.Lock()
4092 delete(s.activeConns, sc)
4093 s.mu.Unlock()
4094 }
4095
4096 func (s *http2serverInternalState) startGracefulShutdown() {
4097 if s == nil {
4098 return
4099 }
4100 s.mu.Lock()
4101 for sc := range s.activeConns {
4102 sc.startGracefulShutdown()
4103 }
4104 s.mu.Unlock()
4105 }
4106
4107
4108
4109
4110
4111
4112 func http2ConfigureServer(s *Server, conf *http2Server) error {
4113 if s == nil {
4114 panic("nil *http.Server")
4115 }
4116 if conf == nil {
4117 conf = new(http2Server)
4118 }
4119 conf.state = &http2serverInternalState{activeConns: make(map[*http2serverConn]struct{})}
4120 if h1, h2 := s, conf; h2.IdleTimeout == 0 {
4121 if h1.IdleTimeout != 0 {
4122 h2.IdleTimeout = h1.IdleTimeout
4123 } else {
4124 h2.IdleTimeout = h1.ReadTimeout
4125 }
4126 }
4127 s.RegisterOnShutdown(conf.state.startGracefulShutdown)
4128
4129 if s.TLSConfig == nil {
4130 s.TLSConfig = new(tls.Config)
4131 } else if s.TLSConfig.CipherSuites != nil && s.TLSConfig.MinVersion < tls.VersionTLS13 {
4132
4133
4134
4135 haveRequired := false
4136 for _, cs := range s.TLSConfig.CipherSuites {
4137 switch cs {
4138 case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
4139
4140
4141 tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
4142 haveRequired = true
4143 }
4144 }
4145 if !haveRequired {
4146 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)")
4147 }
4148 }
4149
4150
4151
4152
4153
4154
4155
4156
4157 s.TLSConfig.PreferServerCipherSuites = true
4158
4159 if !http2strSliceContains(s.TLSConfig.NextProtos, http2NextProtoTLS) {
4160 s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, http2NextProtoTLS)
4161 }
4162 if !http2strSliceContains(s.TLSConfig.NextProtos, "http/1.1") {
4163 s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "http/1.1")
4164 }
4165
4166 if s.TLSNextProto == nil {
4167 s.TLSNextProto = map[string]func(*Server, *tls.Conn, Handler){}
4168 }
4169 protoHandler := func(hs *Server, c *tls.Conn, h Handler) {
4170 if http2testHookOnConn != nil {
4171 http2testHookOnConn()
4172 }
4173
4174
4175
4176
4177
4178 var ctx context.Context
4179 type baseContexter interface {
4180 BaseContext() context.Context
4181 }
4182 if bc, ok := h.(baseContexter); ok {
4183 ctx = bc.BaseContext()
4184 }
4185 conf.ServeConn(c, &http2ServeConnOpts{
4186 Context: ctx,
4187 Handler: h,
4188 BaseConfig: hs,
4189 })
4190 }
4191 s.TLSNextProto[http2NextProtoTLS] = protoHandler
4192 return nil
4193 }
4194
4195
4196 type http2ServeConnOpts struct {
4197
4198
4199 Context context.Context
4200
4201
4202
4203 BaseConfig *Server
4204
4205
4206
4207
4208 Handler Handler
4209
4210
4211
4212
4213
4214 UpgradeRequest *Request
4215
4216
4217
4218 Settings []byte
4219
4220
4221
4222 SawClientPreface bool
4223 }
4224
4225 func (o *http2ServeConnOpts) context() context.Context {
4226 if o != nil && o.Context != nil {
4227 return o.Context
4228 }
4229 return context.Background()
4230 }
4231
4232 func (o *http2ServeConnOpts) baseConfig() *Server {
4233 if o != nil && o.BaseConfig != nil {
4234 return o.BaseConfig
4235 }
4236 return new(Server)
4237 }
4238
4239 func (o *http2ServeConnOpts) handler() Handler {
4240 if o != nil {
4241 if o.Handler != nil {
4242 return o.Handler
4243 }
4244 if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
4245 return o.BaseConfig.Handler
4246 }
4247 }
4248 return DefaultServeMux
4249 }
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265 func (s *http2Server) ServeConn(c net.Conn, opts *http2ServeConnOpts) {
4266 s.serveConn(c, opts, nil)
4267 }
4268
4269 func (s *http2Server) serveConn(c net.Conn, opts *http2ServeConnOpts, newf func(*http2serverConn)) {
4270 baseCtx, cancel := http2serverConnBaseContext(c, opts)
4271 defer cancel()
4272
4273 sc := &http2serverConn{
4274 srv: s,
4275 hs: opts.baseConfig(),
4276 conn: c,
4277 baseCtx: baseCtx,
4278 remoteAddrStr: c.RemoteAddr().String(),
4279 bw: http2newBufferedWriter(c),
4280 handler: opts.handler(),
4281 streams: make(map[uint32]*http2stream),
4282 readFrameCh: make(chan http2readFrameResult),
4283 wantWriteFrameCh: make(chan http2FrameWriteRequest, 8),
4284 serveMsgCh: make(chan interface{}, 8),
4285 wroteFrameCh: make(chan http2frameWriteResult, 1),
4286 bodyReadCh: make(chan http2bodyReadMsg),
4287 doneServing: make(chan struct{}),
4288 clientMaxStreams: math.MaxUint32,
4289 advMaxStreams: s.maxConcurrentStreams(),
4290 initialStreamSendWindowSize: http2initialWindowSize,
4291 maxFrameSize: http2initialMaxFrameSize,
4292 serveG: http2newGoroutineLock(),
4293 pushEnabled: true,
4294 sawClientPreface: opts.SawClientPreface,
4295 }
4296 if newf != nil {
4297 newf(sc)
4298 }
4299
4300 s.state.registerConn(sc)
4301 defer s.state.unregisterConn(sc)
4302
4303
4304
4305
4306
4307
4308 if sc.hs.WriteTimeout > 0 {
4309 sc.conn.SetWriteDeadline(time.Time{})
4310 }
4311
4312 if s.NewWriteScheduler != nil {
4313 sc.writeSched = s.NewWriteScheduler()
4314 } else {
4315 sc.writeSched = http2newRoundRobinWriteScheduler()
4316 }
4317
4318
4319
4320
4321 sc.flow.add(http2initialWindowSize)
4322 sc.inflow.init(http2initialWindowSize)
4323 sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
4324 sc.hpackEncoder.SetMaxDynamicTableSizeLimit(s.maxEncoderHeaderTableSize())
4325
4326 fr := http2NewFramer(sc.bw, c)
4327 if s.CountError != nil {
4328 fr.countError = s.CountError
4329 }
4330 fr.ReadMetaHeaders = hpack.NewDecoder(s.maxDecoderHeaderTableSize(), nil)
4331 fr.MaxHeaderListSize = sc.maxHeaderListSize()
4332 fr.SetMaxReadFrameSize(s.maxReadFrameSize())
4333 sc.framer = fr
4334
4335 if tc, ok := c.(http2connectionStater); ok {
4336 sc.tlsState = new(tls.ConnectionState)
4337 *sc.tlsState = tc.ConnectionState()
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348 if sc.tlsState.Version < tls.VersionTLS12 {
4349 sc.rejectConn(http2ErrCodeInadequateSecurity, "TLS version too low")
4350 return
4351 }
4352
4353 if sc.tlsState.ServerName == "" {
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363 }
4364
4365 if !s.PermitProhibitedCipherSuites && http2isBadCipher(sc.tlsState.CipherSuite) {
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376 sc.rejectConn(http2ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
4377 return
4378 }
4379 }
4380
4381 if opts.Settings != nil {
4382 fr := &http2SettingsFrame{
4383 http2FrameHeader: http2FrameHeader{valid: true},
4384 p: opts.Settings,
4385 }
4386 if err := fr.ForeachSetting(sc.processSetting); err != nil {
4387 sc.rejectConn(http2ErrCodeProtocol, "invalid settings")
4388 return
4389 }
4390 opts.Settings = nil
4391 }
4392
4393 if hook := http2testHookGetServerConn; hook != nil {
4394 hook(sc)
4395 }
4396
4397 if opts.UpgradeRequest != nil {
4398 sc.upgradeRequest(opts.UpgradeRequest)
4399 opts.UpgradeRequest = nil
4400 }
4401
4402 sc.serve()
4403 }
4404
4405 func http2serverConnBaseContext(c net.Conn, opts *http2ServeConnOpts) (ctx context.Context, cancel func()) {
4406 ctx, cancel = context.WithCancel(opts.context())
4407 ctx = context.WithValue(ctx, LocalAddrContextKey, c.LocalAddr())
4408 if hs := opts.baseConfig(); hs != nil {
4409 ctx = context.WithValue(ctx, ServerContextKey, hs)
4410 }
4411 return
4412 }
4413
4414 func (sc *http2serverConn) rejectConn(err http2ErrCode, debug string) {
4415 sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
4416
4417 sc.framer.WriteGoAway(0, err, []byte(debug))
4418 sc.bw.Flush()
4419 sc.conn.Close()
4420 }
4421
4422 type http2serverConn struct {
4423
4424 srv *http2Server
4425 hs *Server
4426 conn net.Conn
4427 bw *http2bufferedWriter
4428 handler Handler
4429 baseCtx context.Context
4430 framer *http2Framer
4431 doneServing chan struct{}
4432 readFrameCh chan http2readFrameResult
4433 wantWriteFrameCh chan http2FrameWriteRequest
4434 wroteFrameCh chan http2frameWriteResult
4435 bodyReadCh chan http2bodyReadMsg
4436 serveMsgCh chan interface{}
4437 flow http2outflow
4438 inflow http2inflow
4439 tlsState *tls.ConnectionState
4440 remoteAddrStr string
4441 writeSched http2WriteScheduler
4442
4443
4444 serveG http2goroutineLock
4445 pushEnabled bool
4446 sawClientPreface bool
4447 sawFirstSettings bool
4448 needToSendSettingsAck bool
4449 unackedSettings int
4450 queuedControlFrames int
4451 clientMaxStreams uint32
4452 advMaxStreams uint32
4453 curClientStreams uint32
4454 curPushedStreams uint32
4455 curHandlers uint32
4456 maxClientStreamID uint32
4457 maxPushPromiseID uint32
4458 streams map[uint32]*http2stream
4459 unstartedHandlers []http2unstartedHandler
4460 initialStreamSendWindowSize int32
4461 maxFrameSize int32
4462 peerMaxHeaderListSize uint32
4463 canonHeader map[string]string
4464 canonHeaderKeysSize int
4465 writingFrame bool
4466 writingFrameAsync bool
4467 needsFrameFlush bool
4468 inGoAway bool
4469 inFrameScheduleLoop bool
4470 needToSendGoAway bool
4471 goAwayCode http2ErrCode
4472 shutdownTimer http2timer
4473 idleTimer http2timer
4474
4475
4476 headerWriteBuf bytes.Buffer
4477 hpackEncoder *hpack.Encoder
4478
4479
4480 shutdownOnce sync.Once
4481 }
4482
4483 func (sc *http2serverConn) maxHeaderListSize() uint32 {
4484 n := sc.hs.MaxHeaderBytes
4485 if n <= 0 {
4486 n = DefaultMaxHeaderBytes
4487 }
4488
4489
4490 const perFieldOverhead = 32
4491 const typicalHeaders = 10
4492 return uint32(n + typicalHeaders*perFieldOverhead)
4493 }
4494
4495 func (sc *http2serverConn) curOpenStreams() uint32 {
4496 sc.serveG.check()
4497 return sc.curClientStreams + sc.curPushedStreams
4498 }
4499
4500
4501
4502
4503
4504
4505
4506
4507 type http2stream struct {
4508
4509 sc *http2serverConn
4510 id uint32
4511 body *http2pipe
4512 cw http2closeWaiter
4513 ctx context.Context
4514 cancelCtx func()
4515
4516
4517 bodyBytes int64
4518 declBodyBytes int64
4519 flow http2outflow
4520 inflow http2inflow
4521 state http2streamState
4522 resetQueued bool
4523 gotTrailerHeader bool
4524 wroteHeaders bool
4525 readDeadline http2timer
4526 writeDeadline http2timer
4527 closeErr error
4528
4529 trailer Header
4530 reqTrailer Header
4531 }
4532
4533 func (sc *http2serverConn) Framer() *http2Framer { return sc.framer }
4534
4535 func (sc *http2serverConn) CloseConn() error { return sc.conn.Close() }
4536
4537 func (sc *http2serverConn) Flush() error { return sc.bw.Flush() }
4538
4539 func (sc *http2serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
4540 return sc.hpackEncoder, &sc.headerWriteBuf
4541 }
4542
4543 func (sc *http2serverConn) state(streamID uint32) (http2streamState, *http2stream) {
4544 sc.serveG.check()
4545
4546 if st, ok := sc.streams[streamID]; ok {
4547 return st.state, st
4548 }
4549
4550
4551
4552
4553
4554
4555 if streamID%2 == 1 {
4556 if streamID <= sc.maxClientStreamID {
4557 return http2stateClosed, nil
4558 }
4559 } else {
4560 if streamID <= sc.maxPushPromiseID {
4561 return http2stateClosed, nil
4562 }
4563 }
4564 return http2stateIdle, nil
4565 }
4566
4567
4568
4569
4570 func (sc *http2serverConn) setConnState(state ConnState) {
4571 if sc.hs.ConnState != nil {
4572 sc.hs.ConnState(sc.conn, state)
4573 }
4574 }
4575
4576 func (sc *http2serverConn) vlogf(format string, args ...interface{}) {
4577 if http2VerboseLogs {
4578 sc.logf(format, args...)
4579 }
4580 }
4581
4582 func (sc *http2serverConn) logf(format string, args ...interface{}) {
4583 if lg := sc.hs.ErrorLog; lg != nil {
4584 lg.Printf(format, args...)
4585 } else {
4586 log.Printf(format, args...)
4587 }
4588 }
4589
4590
4591
4592
4593
4594 func http2errno(v error) uintptr {
4595 if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
4596 return uintptr(rv.Uint())
4597 }
4598 return 0
4599 }
4600
4601
4602
4603 func http2isClosedConnError(err error) bool {
4604 if err == nil {
4605 return false
4606 }
4607
4608 if errors.Is(err, net.ErrClosed) {
4609 return true
4610 }
4611
4612
4613
4614
4615
4616 if runtime.GOOS == "windows" {
4617 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
4618 if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
4619 const WSAECONNABORTED = 10053
4620 const WSAECONNRESET = 10054
4621 if n := http2errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
4622 return true
4623 }
4624 }
4625 }
4626 }
4627 return false
4628 }
4629
4630 func (sc *http2serverConn) condlogf(err error, format string, args ...interface{}) {
4631 if err == nil {
4632 return
4633 }
4634 if err == io.EOF || err == io.ErrUnexpectedEOF || http2isClosedConnError(err) || err == http2errPrefaceTimeout {
4635
4636 sc.vlogf(format, args...)
4637 } else {
4638 sc.logf(format, args...)
4639 }
4640 }
4641
4642
4643
4644
4645
4646
4647 const http2maxCachedCanonicalHeadersKeysSize = 2048
4648
4649 func (sc *http2serverConn) canonicalHeader(v string) string {
4650 sc.serveG.check()
4651 http2buildCommonHeaderMapsOnce()
4652 cv, ok := http2commonCanonHeader[v]
4653 if ok {
4654 return cv
4655 }
4656 cv, ok = sc.canonHeader[v]
4657 if ok {
4658 return cv
4659 }
4660 if sc.canonHeader == nil {
4661 sc.canonHeader = make(map[string]string)
4662 }
4663 cv = CanonicalHeaderKey(v)
4664 size := 100 + len(v)*2
4665 if sc.canonHeaderKeysSize+size <= http2maxCachedCanonicalHeadersKeysSize {
4666 sc.canonHeader[v] = cv
4667 sc.canonHeaderKeysSize += size
4668 }
4669 return cv
4670 }
4671
4672 type http2readFrameResult struct {
4673 f http2Frame
4674 err error
4675
4676
4677
4678
4679 readMore func()
4680 }
4681
4682
4683
4684
4685
4686 func (sc *http2serverConn) readFrames() {
4687 sc.srv.markNewGoroutine()
4688 gate := make(chan struct{})
4689 gateDone := func() { gate <- struct{}{} }
4690 for {
4691 f, err := sc.framer.ReadFrame()
4692 select {
4693 case sc.readFrameCh <- http2readFrameResult{f, err, gateDone}:
4694 case <-sc.doneServing:
4695 return
4696 }
4697 select {
4698 case <-gate:
4699 case <-sc.doneServing:
4700 return
4701 }
4702 if http2terminalReadFrameError(err) {
4703 return
4704 }
4705 }
4706 }
4707
4708
4709 type http2frameWriteResult struct {
4710 _ http2incomparable
4711 wr http2FrameWriteRequest
4712 err error
4713 }
4714
4715
4716
4717
4718
4719 func (sc *http2serverConn) writeFrameAsync(wr http2FrameWriteRequest, wd *http2writeData) {
4720 sc.srv.markNewGoroutine()
4721 var err error
4722 if wd == nil {
4723 err = wr.write.writeFrame(sc)
4724 } else {
4725 err = sc.framer.endWrite()
4726 }
4727 sc.wroteFrameCh <- http2frameWriteResult{wr: wr, err: err}
4728 }
4729
4730 func (sc *http2serverConn) closeAllStreamsOnConnClose() {
4731 sc.serveG.check()
4732 for _, st := range sc.streams {
4733 sc.closeStream(st, http2errClientDisconnected)
4734 }
4735 }
4736
4737 func (sc *http2serverConn) stopShutdownTimer() {
4738 sc.serveG.check()
4739 if t := sc.shutdownTimer; t != nil {
4740 t.Stop()
4741 }
4742 }
4743
4744 func (sc *http2serverConn) notePanic() {
4745
4746 if http2testHookOnPanicMu != nil {
4747 http2testHookOnPanicMu.Lock()
4748 defer http2testHookOnPanicMu.Unlock()
4749 }
4750 if http2testHookOnPanic != nil {
4751 if e := recover(); e != nil {
4752 if http2testHookOnPanic(sc, e) {
4753 panic(e)
4754 }
4755 }
4756 }
4757 }
4758
4759 func (sc *http2serverConn) serve() {
4760 sc.serveG.check()
4761 defer sc.notePanic()
4762 defer sc.conn.Close()
4763 defer sc.closeAllStreamsOnConnClose()
4764 defer sc.stopShutdownTimer()
4765 defer close(sc.doneServing)
4766
4767 if http2VerboseLogs {
4768 sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
4769 }
4770
4771 sc.writeFrame(http2FrameWriteRequest{
4772 write: http2writeSettings{
4773 {http2SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
4774 {http2SettingMaxConcurrentStreams, sc.advMaxStreams},
4775 {http2SettingMaxHeaderListSize, sc.maxHeaderListSize()},
4776 {http2SettingHeaderTableSize, sc.srv.maxDecoderHeaderTableSize()},
4777 {http2SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())},
4778 },
4779 })
4780 sc.unackedSettings++
4781
4782
4783
4784 if diff := sc.srv.initialConnRecvWindowSize() - http2initialWindowSize; diff > 0 {
4785 sc.sendWindowUpdate(nil, int(diff))
4786 }
4787
4788 if err := sc.readPreface(); err != nil {
4789 sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
4790 return
4791 }
4792
4793
4794
4795
4796 sc.setConnState(StateActive)
4797 sc.setConnState(StateIdle)
4798
4799 if sc.srv.IdleTimeout > 0 {
4800 sc.idleTimer = sc.srv.afterFunc(sc.srv.IdleTimeout, sc.onIdleTimer)
4801 defer sc.idleTimer.Stop()
4802 }
4803
4804 go sc.readFrames()
4805
4806 settingsTimer := sc.srv.afterFunc(http2firstSettingsTimeout, sc.onSettingsTimer)
4807 defer settingsTimer.Stop()
4808
4809 loopNum := 0
4810 for {
4811 loopNum++
4812 select {
4813 case wr := <-sc.wantWriteFrameCh:
4814 if se, ok := wr.write.(http2StreamError); ok {
4815 sc.resetStream(se)
4816 break
4817 }
4818 sc.writeFrame(wr)
4819 case res := <-sc.wroteFrameCh:
4820 sc.wroteFrame(res)
4821 case res := <-sc.readFrameCh:
4822
4823
4824 if sc.writingFrameAsync {
4825 select {
4826 case wroteRes := <-sc.wroteFrameCh:
4827 sc.wroteFrame(wroteRes)
4828 default:
4829 }
4830 }
4831 if !sc.processFrameFromReader(res) {
4832 return
4833 }
4834 res.readMore()
4835 if settingsTimer != nil {
4836 settingsTimer.Stop()
4837 settingsTimer = nil
4838 }
4839 case m := <-sc.bodyReadCh:
4840 sc.noteBodyRead(m.st, m.n)
4841 case msg := <-sc.serveMsgCh:
4842 switch v := msg.(type) {
4843 case func(int):
4844 v(loopNum)
4845 case *http2serverMessage:
4846 switch v {
4847 case http2settingsTimerMsg:
4848 sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
4849 return
4850 case http2idleTimerMsg:
4851 sc.vlogf("connection is idle")
4852 sc.goAway(http2ErrCodeNo)
4853 case http2shutdownTimerMsg:
4854 sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
4855 return
4856 case http2gracefulShutdownMsg:
4857 sc.startGracefulShutdownInternal()
4858 case http2handlerDoneMsg:
4859 sc.handlerDone()
4860 default:
4861 panic("unknown timer")
4862 }
4863 case *http2startPushRequest:
4864 sc.startPush(v)
4865 case func(*http2serverConn):
4866 v(sc)
4867 default:
4868 panic(fmt.Sprintf("unexpected type %T", v))
4869 }
4870 }
4871
4872
4873
4874
4875 if sc.queuedControlFrames > sc.srv.maxQueuedControlFrames() {
4876 sc.vlogf("http2: too many control frames in send queue, closing connection")
4877 return
4878 }
4879
4880
4881
4882
4883 sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
4884 gracefulShutdownComplete := sc.goAwayCode == http2ErrCodeNo && sc.curOpenStreams() == 0
4885 if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != http2ErrCodeNo || gracefulShutdownComplete) {
4886 sc.shutDownIn(http2goAwayTimeout)
4887 }
4888 }
4889 }
4890
4891 type http2serverMessage int
4892
4893
4894 var (
4895 http2settingsTimerMsg = new(http2serverMessage)
4896 http2idleTimerMsg = new(http2serverMessage)
4897 http2shutdownTimerMsg = new(http2serverMessage)
4898 http2gracefulShutdownMsg = new(http2serverMessage)
4899 http2handlerDoneMsg = new(http2serverMessage)
4900 )
4901
4902 func (sc *http2serverConn) onSettingsTimer() { sc.sendServeMsg(http2settingsTimerMsg) }
4903
4904 func (sc *http2serverConn) onIdleTimer() { sc.sendServeMsg(http2idleTimerMsg) }
4905
4906 func (sc *http2serverConn) onShutdownTimer() { sc.sendServeMsg(http2shutdownTimerMsg) }
4907
4908 func (sc *http2serverConn) sendServeMsg(msg interface{}) {
4909 sc.serveG.checkNotOn()
4910 select {
4911 case sc.serveMsgCh <- msg:
4912 case <-sc.doneServing:
4913 }
4914 }
4915
4916 var http2errPrefaceTimeout = errors.New("timeout waiting for client preface")
4917
4918
4919
4920
4921 func (sc *http2serverConn) readPreface() error {
4922 if sc.sawClientPreface {
4923 return nil
4924 }
4925 errc := make(chan error, 1)
4926 go func() {
4927
4928 buf := make([]byte, len(http2ClientPreface))
4929 if _, err := io.ReadFull(sc.conn, buf); err != nil {
4930 errc <- err
4931 } else if !bytes.Equal(buf, http2clientPreface) {
4932 errc <- fmt.Errorf("bogus greeting %q", buf)
4933 } else {
4934 errc <- nil
4935 }
4936 }()
4937 timer := sc.srv.newTimer(http2prefaceTimeout)
4938 defer timer.Stop()
4939 select {
4940 case <-timer.C():
4941 return http2errPrefaceTimeout
4942 case err := <-errc:
4943 if err == nil {
4944 if http2VerboseLogs {
4945 sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
4946 }
4947 }
4948 return err
4949 }
4950 }
4951
4952 var http2errChanPool = sync.Pool{
4953 New: func() interface{} { return make(chan error, 1) },
4954 }
4955
4956 var http2writeDataPool = sync.Pool{
4957 New: func() interface{} { return new(http2writeData) },
4958 }
4959
4960
4961
4962 func (sc *http2serverConn) writeDataFromHandler(stream *http2stream, data []byte, endStream bool) error {
4963 ch := http2errChanPool.Get().(chan error)
4964 writeArg := http2writeDataPool.Get().(*http2writeData)
4965 *writeArg = http2writeData{stream.id, data, endStream}
4966 err := sc.writeFrameFromHandler(http2FrameWriteRequest{
4967 write: writeArg,
4968 stream: stream,
4969 done: ch,
4970 })
4971 if err != nil {
4972 return err
4973 }
4974 var frameWriteDone bool
4975 select {
4976 case err = <-ch:
4977 frameWriteDone = true
4978 case <-sc.doneServing:
4979 return http2errClientDisconnected
4980 case <-stream.cw:
4981
4982
4983
4984
4985
4986
4987
4988 select {
4989 case err = <-ch:
4990 frameWriteDone = true
4991 default:
4992 return http2errStreamClosed
4993 }
4994 }
4995 http2errChanPool.Put(ch)
4996 if frameWriteDone {
4997 http2writeDataPool.Put(writeArg)
4998 }
4999 return err
5000 }
5001
5002
5003
5004
5005
5006
5007
5008
5009 func (sc *http2serverConn) writeFrameFromHandler(wr http2FrameWriteRequest) error {
5010 sc.serveG.checkNotOn()
5011 select {
5012 case sc.wantWriteFrameCh <- wr:
5013 return nil
5014 case <-sc.doneServing:
5015
5016
5017 return http2errClientDisconnected
5018 }
5019 }
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029 func (sc *http2serverConn) writeFrame(wr http2FrameWriteRequest) {
5030 sc.serveG.check()
5031
5032
5033 var ignoreWrite bool
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053 if wr.StreamID() != 0 {
5054 _, isReset := wr.write.(http2StreamError)
5055 if state, _ := sc.state(wr.StreamID()); state == http2stateClosed && !isReset {
5056 ignoreWrite = true
5057 }
5058 }
5059
5060
5061
5062 switch wr.write.(type) {
5063 case *http2writeResHeaders:
5064 wr.stream.wroteHeaders = true
5065 case http2write100ContinueHeadersFrame:
5066 if wr.stream.wroteHeaders {
5067
5068
5069 if wr.done != nil {
5070 panic("wr.done != nil for write100ContinueHeadersFrame")
5071 }
5072 ignoreWrite = true
5073 }
5074 }
5075
5076 if !ignoreWrite {
5077 if wr.isControl() {
5078 sc.queuedControlFrames++
5079
5080
5081 if sc.queuedControlFrames < 0 {
5082 sc.conn.Close()
5083 }
5084 }
5085 sc.writeSched.Push(wr)
5086 }
5087 sc.scheduleFrameWrite()
5088 }
5089
5090
5091
5092
5093 func (sc *http2serverConn) startFrameWrite(wr http2FrameWriteRequest) {
5094 sc.serveG.check()
5095 if sc.writingFrame {
5096 panic("internal error: can only be writing one frame at a time")
5097 }
5098
5099 st := wr.stream
5100 if st != nil {
5101 switch st.state {
5102 case http2stateHalfClosedLocal:
5103 switch wr.write.(type) {
5104 case http2StreamError, http2handlerPanicRST, http2writeWindowUpdate:
5105
5106
5107 default:
5108 panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
5109 }
5110 case http2stateClosed:
5111 panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
5112 }
5113 }
5114 if wpp, ok := wr.write.(*http2writePushPromise); ok {
5115 var err error
5116 wpp.promisedID, err = wpp.allocatePromisedID()
5117 if err != nil {
5118 sc.writingFrameAsync = false
5119 wr.replyToWriter(err)
5120 return
5121 }
5122 }
5123
5124 sc.writingFrame = true
5125 sc.needsFrameFlush = true
5126 if wr.write.staysWithinBuffer(sc.bw.Available()) {
5127 sc.writingFrameAsync = false
5128 err := wr.write.writeFrame(sc)
5129 sc.wroteFrame(http2frameWriteResult{wr: wr, err: err})
5130 } else if wd, ok := wr.write.(*http2writeData); ok {
5131
5132
5133
5134 sc.framer.startWriteDataPadded(wd.streamID, wd.endStream, wd.p, nil)
5135 sc.writingFrameAsync = true
5136 go sc.writeFrameAsync(wr, wd)
5137 } else {
5138 sc.writingFrameAsync = true
5139 go sc.writeFrameAsync(wr, nil)
5140 }
5141 }
5142
5143
5144
5145
5146 var http2errHandlerPanicked = errors.New("http2: handler panicked")
5147
5148
5149
5150 func (sc *http2serverConn) wroteFrame(res http2frameWriteResult) {
5151 sc.serveG.check()
5152 if !sc.writingFrame {
5153 panic("internal error: expected to be already writing a frame")
5154 }
5155 sc.writingFrame = false
5156 sc.writingFrameAsync = false
5157
5158 wr := res.wr
5159
5160 if http2writeEndsStream(wr.write) {
5161 st := wr.stream
5162 if st == nil {
5163 panic("internal error: expecting non-nil stream")
5164 }
5165 switch st.state {
5166 case http2stateOpen:
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177 st.state = http2stateHalfClosedLocal
5178
5179
5180
5181
5182 sc.resetStream(http2streamError(st.id, http2ErrCodeNo))
5183 case http2stateHalfClosedRemote:
5184 sc.closeStream(st, http2errHandlerComplete)
5185 }
5186 } else {
5187 switch v := wr.write.(type) {
5188 case http2StreamError:
5189
5190 if st, ok := sc.streams[v.StreamID]; ok {
5191 sc.closeStream(st, v)
5192 }
5193 case http2handlerPanicRST:
5194 sc.closeStream(wr.stream, http2errHandlerPanicked)
5195 }
5196 }
5197
5198
5199 wr.replyToWriter(res.err)
5200
5201 sc.scheduleFrameWrite()
5202 }
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214 func (sc *http2serverConn) scheduleFrameWrite() {
5215 sc.serveG.check()
5216 if sc.writingFrame || sc.inFrameScheduleLoop {
5217 return
5218 }
5219 sc.inFrameScheduleLoop = true
5220 for !sc.writingFrameAsync {
5221 if sc.needToSendGoAway {
5222 sc.needToSendGoAway = false
5223 sc.startFrameWrite(http2FrameWriteRequest{
5224 write: &http2writeGoAway{
5225 maxStreamID: sc.maxClientStreamID,
5226 code: sc.goAwayCode,
5227 },
5228 })
5229 continue
5230 }
5231 if sc.needToSendSettingsAck {
5232 sc.needToSendSettingsAck = false
5233 sc.startFrameWrite(http2FrameWriteRequest{write: http2writeSettingsAck{}})
5234 continue
5235 }
5236 if !sc.inGoAway || sc.goAwayCode == http2ErrCodeNo {
5237 if wr, ok := sc.writeSched.Pop(); ok {
5238 if wr.isControl() {
5239 sc.queuedControlFrames--
5240 }
5241 sc.startFrameWrite(wr)
5242 continue
5243 }
5244 }
5245 if sc.needsFrameFlush {
5246 sc.startFrameWrite(http2FrameWriteRequest{write: http2flushFrameWriter{}})
5247 sc.needsFrameFlush = false
5248 continue
5249 }
5250 break
5251 }
5252 sc.inFrameScheduleLoop = false
5253 }
5254
5255
5256
5257
5258
5259
5260
5261
5262 func (sc *http2serverConn) startGracefulShutdown() {
5263 sc.serveG.checkNotOn()
5264 sc.shutdownOnce.Do(func() { sc.sendServeMsg(http2gracefulShutdownMsg) })
5265 }
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283 var http2goAwayTimeout = 1 * time.Second
5284
5285 func (sc *http2serverConn) startGracefulShutdownInternal() {
5286 sc.goAway(http2ErrCodeNo)
5287 }
5288
5289 func (sc *http2serverConn) goAway(code http2ErrCode) {
5290 sc.serveG.check()
5291 if sc.inGoAway {
5292 if sc.goAwayCode == http2ErrCodeNo {
5293 sc.goAwayCode = code
5294 }
5295 return
5296 }
5297 sc.inGoAway = true
5298 sc.needToSendGoAway = true
5299 sc.goAwayCode = code
5300 sc.scheduleFrameWrite()
5301 }
5302
5303 func (sc *http2serverConn) shutDownIn(d time.Duration) {
5304 sc.serveG.check()
5305 sc.shutdownTimer = sc.srv.afterFunc(d, sc.onShutdownTimer)
5306 }
5307
5308 func (sc *http2serverConn) resetStream(se http2StreamError) {
5309 sc.serveG.check()
5310 sc.writeFrame(http2FrameWriteRequest{write: se})
5311 if st, ok := sc.streams[se.StreamID]; ok {
5312 st.resetQueued = true
5313 }
5314 }
5315
5316
5317
5318
5319 func (sc *http2serverConn) processFrameFromReader(res http2readFrameResult) bool {
5320 sc.serveG.check()
5321 err := res.err
5322 if err != nil {
5323 if err == http2ErrFrameTooLarge {
5324 sc.goAway(http2ErrCodeFrameSize)
5325 return true
5326 }
5327 clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || http2isClosedConnError(err)
5328 if clientGone {
5329
5330
5331
5332
5333
5334
5335
5336
5337 return false
5338 }
5339 } else {
5340 f := res.f
5341 if http2VerboseLogs {
5342 sc.vlogf("http2: server read frame %v", http2summarizeFrame(f))
5343 }
5344 err = sc.processFrame(f)
5345 if err == nil {
5346 return true
5347 }
5348 }
5349
5350 switch ev := err.(type) {
5351 case http2StreamError:
5352 sc.resetStream(ev)
5353 return true
5354 case http2goAwayFlowError:
5355 sc.goAway(http2ErrCodeFlowControl)
5356 return true
5357 case http2ConnectionError:
5358 if res.f != nil {
5359 if id := res.f.Header().StreamID; id > sc.maxClientStreamID {
5360 sc.maxClientStreamID = id
5361 }
5362 }
5363 sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
5364 sc.goAway(http2ErrCode(ev))
5365 return true
5366 default:
5367 if res.err != nil {
5368 sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
5369 } else {
5370 sc.logf("http2: server closing client connection: %v", err)
5371 }
5372 return false
5373 }
5374 }
5375
5376 func (sc *http2serverConn) processFrame(f http2Frame) error {
5377 sc.serveG.check()
5378
5379
5380 if !sc.sawFirstSettings {
5381 if _, ok := f.(*http2SettingsFrame); !ok {
5382 return sc.countError("first_settings", http2ConnectionError(http2ErrCodeProtocol))
5383 }
5384 sc.sawFirstSettings = true
5385 }
5386
5387
5388
5389
5390
5391 if sc.inGoAway && (sc.goAwayCode != http2ErrCodeNo || f.Header().StreamID > sc.maxClientStreamID) {
5392
5393 if f, ok := f.(*http2DataFrame); ok {
5394 if !sc.inflow.take(f.Length) {
5395 return sc.countError("data_flow", http2streamError(f.Header().StreamID, http2ErrCodeFlowControl))
5396 }
5397 sc.sendWindowUpdate(nil, int(f.Length))
5398 }
5399 return nil
5400 }
5401
5402 switch f := f.(type) {
5403 case *http2SettingsFrame:
5404 return sc.processSettings(f)
5405 case *http2MetaHeadersFrame:
5406 return sc.processHeaders(f)
5407 case *http2WindowUpdateFrame:
5408 return sc.processWindowUpdate(f)
5409 case *http2PingFrame:
5410 return sc.processPing(f)
5411 case *http2DataFrame:
5412 return sc.processData(f)
5413 case *http2RSTStreamFrame:
5414 return sc.processResetStream(f)
5415 case *http2PriorityFrame:
5416 return sc.processPriority(f)
5417 case *http2GoAwayFrame:
5418 return sc.processGoAway(f)
5419 case *http2PushPromiseFrame:
5420
5421
5422 return sc.countError("push_promise", http2ConnectionError(http2ErrCodeProtocol))
5423 default:
5424 sc.vlogf("http2: server ignoring frame: %v", f.Header())
5425 return nil
5426 }
5427 }
5428
5429 func (sc *http2serverConn) processPing(f *http2PingFrame) error {
5430 sc.serveG.check()
5431 if f.IsAck() {
5432
5433
5434 return nil
5435 }
5436 if f.StreamID != 0 {
5437
5438
5439
5440
5441
5442 return sc.countError("ping_on_stream", http2ConnectionError(http2ErrCodeProtocol))
5443 }
5444 sc.writeFrame(http2FrameWriteRequest{write: http2writePingAck{f}})
5445 return nil
5446 }
5447
5448 func (sc *http2serverConn) processWindowUpdate(f *http2WindowUpdateFrame) error {
5449 sc.serveG.check()
5450 switch {
5451 case f.StreamID != 0:
5452 state, st := sc.state(f.StreamID)
5453 if state == http2stateIdle {
5454
5455
5456
5457
5458 return sc.countError("stream_idle", http2ConnectionError(http2ErrCodeProtocol))
5459 }
5460 if st == nil {
5461
5462
5463
5464
5465
5466 return nil
5467 }
5468 if !st.flow.add(int32(f.Increment)) {
5469 return sc.countError("bad_flow", http2streamError(f.StreamID, http2ErrCodeFlowControl))
5470 }
5471 default:
5472 if !sc.flow.add(int32(f.Increment)) {
5473 return http2goAwayFlowError{}
5474 }
5475 }
5476 sc.scheduleFrameWrite()
5477 return nil
5478 }
5479
5480 func (sc *http2serverConn) processResetStream(f *http2RSTStreamFrame) error {
5481 sc.serveG.check()
5482
5483 state, st := sc.state(f.StreamID)
5484 if state == http2stateIdle {
5485
5486
5487
5488
5489
5490 return sc.countError("reset_idle_stream", http2ConnectionError(http2ErrCodeProtocol))
5491 }
5492 if st != nil {
5493 st.cancelCtx()
5494 sc.closeStream(st, http2streamError(f.StreamID, f.ErrCode))
5495 }
5496 return nil
5497 }
5498
5499 func (sc *http2serverConn) closeStream(st *http2stream, err error) {
5500 sc.serveG.check()
5501 if st.state == http2stateIdle || st.state == http2stateClosed {
5502 panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
5503 }
5504 st.state = http2stateClosed
5505 if st.readDeadline != nil {
5506 st.readDeadline.Stop()
5507 }
5508 if st.writeDeadline != nil {
5509 st.writeDeadline.Stop()
5510 }
5511 if st.isPushed() {
5512 sc.curPushedStreams--
5513 } else {
5514 sc.curClientStreams--
5515 }
5516 delete(sc.streams, st.id)
5517 if len(sc.streams) == 0 {
5518 sc.setConnState(StateIdle)
5519 if sc.srv.IdleTimeout > 0 && sc.idleTimer != nil {
5520 sc.idleTimer.Reset(sc.srv.IdleTimeout)
5521 }
5522 if http2h1ServerKeepAlivesDisabled(sc.hs) {
5523 sc.startGracefulShutdownInternal()
5524 }
5525 }
5526 if p := st.body; p != nil {
5527
5528
5529 sc.sendWindowUpdate(nil, p.Len())
5530
5531 p.CloseWithError(err)
5532 }
5533 if e, ok := err.(http2StreamError); ok {
5534 if e.Cause != nil {
5535 err = e.Cause
5536 } else {
5537 err = http2errStreamClosed
5538 }
5539 }
5540 st.closeErr = err
5541 st.cancelCtx()
5542 st.cw.Close()
5543 sc.writeSched.CloseStream(st.id)
5544 }
5545
5546 func (sc *http2serverConn) processSettings(f *http2SettingsFrame) error {
5547 sc.serveG.check()
5548 if f.IsAck() {
5549 sc.unackedSettings--
5550 if sc.unackedSettings < 0 {
5551
5552
5553
5554 return sc.countError("ack_mystery", http2ConnectionError(http2ErrCodeProtocol))
5555 }
5556 return nil
5557 }
5558 if f.NumSettings() > 100 || f.HasDuplicates() {
5559
5560
5561
5562 return sc.countError("settings_big_or_dups", http2ConnectionError(http2ErrCodeProtocol))
5563 }
5564 if err := f.ForeachSetting(sc.processSetting); err != nil {
5565 return err
5566 }
5567
5568
5569 sc.needToSendSettingsAck = true
5570 sc.scheduleFrameWrite()
5571 return nil
5572 }
5573
5574 func (sc *http2serverConn) processSetting(s http2Setting) error {
5575 sc.serveG.check()
5576 if err := s.Valid(); err != nil {
5577 return err
5578 }
5579 if http2VerboseLogs {
5580 sc.vlogf("http2: server processing setting %v", s)
5581 }
5582 switch s.ID {
5583 case http2SettingHeaderTableSize:
5584 sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
5585 case http2SettingEnablePush:
5586 sc.pushEnabled = s.Val != 0
5587 case http2SettingMaxConcurrentStreams:
5588 sc.clientMaxStreams = s.Val
5589 case http2SettingInitialWindowSize:
5590 return sc.processSettingInitialWindowSize(s.Val)
5591 case http2SettingMaxFrameSize:
5592 sc.maxFrameSize = int32(s.Val)
5593 case http2SettingMaxHeaderListSize:
5594 sc.peerMaxHeaderListSize = s.Val
5595 default:
5596
5597
5598
5599 if http2VerboseLogs {
5600 sc.vlogf("http2: server ignoring unknown setting %v", s)
5601 }
5602 }
5603 return nil
5604 }
5605
5606 func (sc *http2serverConn) processSettingInitialWindowSize(val uint32) error {
5607 sc.serveG.check()
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617 old := sc.initialStreamSendWindowSize
5618 sc.initialStreamSendWindowSize = int32(val)
5619 growth := int32(val) - old
5620 for _, st := range sc.streams {
5621 if !st.flow.add(growth) {
5622
5623
5624
5625
5626
5627
5628 return sc.countError("setting_win_size", http2ConnectionError(http2ErrCodeFlowControl))
5629 }
5630 }
5631 return nil
5632 }
5633
5634 func (sc *http2serverConn) processData(f *http2DataFrame) error {
5635 sc.serveG.check()
5636 id := f.Header().StreamID
5637
5638 data := f.Data()
5639 state, st := sc.state(id)
5640 if id == 0 || state == http2stateIdle {
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651 return sc.countError("data_on_idle", http2ConnectionError(http2ErrCodeProtocol))
5652 }
5653
5654
5655
5656
5657 if st == nil || state != http2stateOpen || st.gotTrailerHeader || st.resetQueued {
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667 if !sc.inflow.take(f.Length) {
5668 return sc.countError("data_flow", http2streamError(id, http2ErrCodeFlowControl))
5669 }
5670 sc.sendWindowUpdate(nil, int(f.Length))
5671
5672 if st != nil && st.resetQueued {
5673
5674 return nil
5675 }
5676 return sc.countError("closed", http2streamError(id, http2ErrCodeStreamClosed))
5677 }
5678 if st.body == nil {
5679 panic("internal error: should have a body in this state")
5680 }
5681
5682
5683 if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
5684 if !sc.inflow.take(f.Length) {
5685 return sc.countError("data_flow", http2streamError(id, http2ErrCodeFlowControl))
5686 }
5687 sc.sendWindowUpdate(nil, int(f.Length))
5688
5689 st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
5690
5691
5692
5693 return sc.countError("send_too_much", http2streamError(id, http2ErrCodeProtocol))
5694 }
5695 if f.Length > 0 {
5696
5697 if !http2takeInflows(&sc.inflow, &st.inflow, f.Length) {
5698 return sc.countError("flow_on_data_length", http2streamError(id, http2ErrCodeFlowControl))
5699 }
5700
5701 if len(data) > 0 {
5702 st.bodyBytes += int64(len(data))
5703 wrote, err := st.body.Write(data)
5704 if err != nil {
5705
5706
5707
5708 sc.sendWindowUpdate(nil, int(f.Length)-wrote)
5709 return nil
5710 }
5711 if wrote != len(data) {
5712 panic("internal error: bad Writer")
5713 }
5714 }
5715
5716
5717
5718
5719
5720
5721 pad := int32(f.Length) - int32(len(data))
5722 sc.sendWindowUpdate32(nil, pad)
5723 sc.sendWindowUpdate32(st, pad)
5724 }
5725 if f.StreamEnded() {
5726 st.endStream()
5727 }
5728 return nil
5729 }
5730
5731 func (sc *http2serverConn) processGoAway(f *http2GoAwayFrame) error {
5732 sc.serveG.check()
5733 if f.ErrCode != http2ErrCodeNo {
5734 sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
5735 } else {
5736 sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
5737 }
5738 sc.startGracefulShutdownInternal()
5739
5740
5741 sc.pushEnabled = false
5742 return nil
5743 }
5744
5745
5746 func (st *http2stream) isPushed() bool {
5747 return st.id%2 == 0
5748 }
5749
5750
5751
5752 func (st *http2stream) endStream() {
5753 sc := st.sc
5754 sc.serveG.check()
5755
5756 if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
5757 st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
5758 st.declBodyBytes, st.bodyBytes))
5759 } else {
5760 st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
5761 st.body.CloseWithError(io.EOF)
5762 }
5763 st.state = http2stateHalfClosedRemote
5764 }
5765
5766
5767
5768 func (st *http2stream) copyTrailersToHandlerRequest() {
5769 for k, vv := range st.trailer {
5770 if _, ok := st.reqTrailer[k]; ok {
5771
5772 st.reqTrailer[k] = vv
5773 }
5774 }
5775 }
5776
5777
5778
5779 func (st *http2stream) onReadTimeout() {
5780 if st.body != nil {
5781
5782
5783 st.body.CloseWithError(fmt.Errorf("%w", os.ErrDeadlineExceeded))
5784 }
5785 }
5786
5787
5788
5789 func (st *http2stream) onWriteTimeout() {
5790 st.sc.writeFrameFromHandler(http2FrameWriteRequest{write: http2StreamError{
5791 StreamID: st.id,
5792 Code: http2ErrCodeInternal,
5793 Cause: os.ErrDeadlineExceeded,
5794 }})
5795 }
5796
5797 func (sc *http2serverConn) processHeaders(f *http2MetaHeadersFrame) error {
5798 sc.serveG.check()
5799 id := f.StreamID
5800
5801
5802
5803
5804
5805 if id%2 != 1 {
5806 return sc.countError("headers_even", http2ConnectionError(http2ErrCodeProtocol))
5807 }
5808
5809
5810
5811
5812 if st := sc.streams[f.StreamID]; st != nil {
5813 if st.resetQueued {
5814
5815
5816 return nil
5817 }
5818
5819
5820
5821
5822 if st.state == http2stateHalfClosedRemote {
5823 return sc.countError("headers_half_closed", http2streamError(id, http2ErrCodeStreamClosed))
5824 }
5825 return st.processTrailerHeaders(f)
5826 }
5827
5828
5829
5830
5831
5832
5833 if id <= sc.maxClientStreamID {
5834 return sc.countError("stream_went_down", http2ConnectionError(http2ErrCodeProtocol))
5835 }
5836 sc.maxClientStreamID = id
5837
5838 if sc.idleTimer != nil {
5839 sc.idleTimer.Stop()
5840 }
5841
5842
5843
5844
5845
5846
5847
5848 if sc.curClientStreams+1 > sc.advMaxStreams {
5849 if sc.unackedSettings == 0 {
5850
5851 return sc.countError("over_max_streams", http2streamError(id, http2ErrCodeProtocol))
5852 }
5853
5854
5855
5856
5857
5858 return sc.countError("over_max_streams_race", http2streamError(id, http2ErrCodeRefusedStream))
5859 }
5860
5861 initialState := http2stateOpen
5862 if f.StreamEnded() {
5863 initialState = http2stateHalfClosedRemote
5864 }
5865 st := sc.newStream(id, 0, initialState)
5866
5867 if f.HasPriority() {
5868 if err := sc.checkPriority(f.StreamID, f.Priority); err != nil {
5869 return err
5870 }
5871 sc.writeSched.AdjustStream(st.id, f.Priority)
5872 }
5873
5874 rw, req, err := sc.newWriterAndRequest(st, f)
5875 if err != nil {
5876 return err
5877 }
5878 st.reqTrailer = req.Trailer
5879 if st.reqTrailer != nil {
5880 st.trailer = make(Header)
5881 }
5882 st.body = req.Body.(*http2requestBody).pipe
5883 st.declBodyBytes = req.ContentLength
5884
5885 handler := sc.handler.ServeHTTP
5886 if f.Truncated {
5887
5888 handler = http2handleHeaderListTooLong
5889 } else if err := http2checkValidHTTP2RequestHeaders(req.Header); err != nil {
5890 handler = http2new400Handler(err)
5891 }
5892
5893
5894
5895
5896
5897
5898
5899
5900 if sc.hs.ReadTimeout > 0 {
5901 sc.conn.SetReadDeadline(time.Time{})
5902 st.readDeadline = sc.srv.afterFunc(sc.hs.ReadTimeout, st.onReadTimeout)
5903 }
5904
5905 return sc.scheduleHandler(id, rw, req, handler)
5906 }
5907
5908 func (sc *http2serverConn) upgradeRequest(req *Request) {
5909 sc.serveG.check()
5910 id := uint32(1)
5911 sc.maxClientStreamID = id
5912 st := sc.newStream(id, 0, http2stateHalfClosedRemote)
5913 st.reqTrailer = req.Trailer
5914 if st.reqTrailer != nil {
5915 st.trailer = make(Header)
5916 }
5917 rw := sc.newResponseWriter(st, req)
5918
5919
5920
5921 if sc.hs.ReadTimeout > 0 {
5922 sc.conn.SetReadDeadline(time.Time{})
5923 }
5924
5925
5926
5927
5928 sc.curHandlers++
5929 go sc.runHandler(rw, req, sc.handler.ServeHTTP)
5930 }
5931
5932 func (st *http2stream) processTrailerHeaders(f *http2MetaHeadersFrame) error {
5933 sc := st.sc
5934 sc.serveG.check()
5935 if st.gotTrailerHeader {
5936 return sc.countError("dup_trailers", http2ConnectionError(http2ErrCodeProtocol))
5937 }
5938 st.gotTrailerHeader = true
5939 if !f.StreamEnded() {
5940 return sc.countError("trailers_not_ended", http2streamError(st.id, http2ErrCodeProtocol))
5941 }
5942
5943 if len(f.PseudoFields()) > 0 {
5944 return sc.countError("trailers_pseudo", http2streamError(st.id, http2ErrCodeProtocol))
5945 }
5946 if st.trailer != nil {
5947 for _, hf := range f.RegularFields() {
5948 key := sc.canonicalHeader(hf.Name)
5949 if !httpguts.ValidTrailerHeader(key) {
5950
5951
5952
5953 return sc.countError("trailers_bogus", http2streamError(st.id, http2ErrCodeProtocol))
5954 }
5955 st.trailer[key] = append(st.trailer[key], hf.Value)
5956 }
5957 }
5958 st.endStream()
5959 return nil
5960 }
5961
5962 func (sc *http2serverConn) checkPriority(streamID uint32, p http2PriorityParam) error {
5963 if streamID == p.StreamDep {
5964
5965
5966
5967
5968 return sc.countError("priority", http2streamError(streamID, http2ErrCodeProtocol))
5969 }
5970 return nil
5971 }
5972
5973 func (sc *http2serverConn) processPriority(f *http2PriorityFrame) error {
5974 if err := sc.checkPriority(f.StreamID, f.http2PriorityParam); err != nil {
5975 return err
5976 }
5977 sc.writeSched.AdjustStream(f.StreamID, f.http2PriorityParam)
5978 return nil
5979 }
5980
5981 func (sc *http2serverConn) newStream(id, pusherID uint32, state http2streamState) *http2stream {
5982 sc.serveG.check()
5983 if id == 0 {
5984 panic("internal error: cannot create stream with id 0")
5985 }
5986
5987 ctx, cancelCtx := context.WithCancel(sc.baseCtx)
5988 st := &http2stream{
5989 sc: sc,
5990 id: id,
5991 state: state,
5992 ctx: ctx,
5993 cancelCtx: cancelCtx,
5994 }
5995 st.cw.Init()
5996 st.flow.conn = &sc.flow
5997 st.flow.add(sc.initialStreamSendWindowSize)
5998 st.inflow.init(sc.srv.initialStreamRecvWindowSize())
5999 if sc.hs.WriteTimeout > 0 {
6000 st.writeDeadline = sc.srv.afterFunc(sc.hs.WriteTimeout, st.onWriteTimeout)
6001 }
6002
6003 sc.streams[id] = st
6004 sc.writeSched.OpenStream(st.id, http2OpenStreamOptions{PusherID: pusherID})
6005 if st.isPushed() {
6006 sc.curPushedStreams++
6007 } else {
6008 sc.curClientStreams++
6009 }
6010 if sc.curOpenStreams() == 1 {
6011 sc.setConnState(StateActive)
6012 }
6013
6014 return st
6015 }
6016
6017 func (sc *http2serverConn) newWriterAndRequest(st *http2stream, f *http2MetaHeadersFrame) (*http2responseWriter, *Request, error) {
6018 sc.serveG.check()
6019
6020 rp := http2requestParam{
6021 method: f.PseudoValue("method"),
6022 scheme: f.PseudoValue("scheme"),
6023 authority: f.PseudoValue("authority"),
6024 path: f.PseudoValue("path"),
6025 }
6026
6027 isConnect := rp.method == "CONNECT"
6028 if isConnect {
6029 if rp.path != "" || rp.scheme != "" || rp.authority == "" {
6030 return nil, nil, sc.countError("bad_connect", http2streamError(f.StreamID, http2ErrCodeProtocol))
6031 }
6032 } else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043 return nil, nil, sc.countError("bad_path_method", http2streamError(f.StreamID, http2ErrCodeProtocol))
6044 }
6045
6046 rp.header = make(Header)
6047 for _, hf := range f.RegularFields() {
6048 rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
6049 }
6050 if rp.authority == "" {
6051 rp.authority = rp.header.Get("Host")
6052 }
6053
6054 rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
6055 if err != nil {
6056 return nil, nil, err
6057 }
6058 bodyOpen := !f.StreamEnded()
6059 if bodyOpen {
6060 if vv, ok := rp.header["Content-Length"]; ok {
6061 if cl, err := strconv.ParseUint(vv[0], 10, 63); err == nil {
6062 req.ContentLength = int64(cl)
6063 } else {
6064 req.ContentLength = 0
6065 }
6066 } else {
6067 req.ContentLength = -1
6068 }
6069 req.Body.(*http2requestBody).pipe = &http2pipe{
6070 b: &http2dataBuffer{expected: req.ContentLength},
6071 }
6072 }
6073 return rw, req, nil
6074 }
6075
6076 type http2requestParam struct {
6077 method string
6078 scheme, authority, path string
6079 header Header
6080 }
6081
6082 func (sc *http2serverConn) newWriterAndRequestNoBody(st *http2stream, rp http2requestParam) (*http2responseWriter, *Request, error) {
6083 sc.serveG.check()
6084
6085 var tlsState *tls.ConnectionState
6086 if rp.scheme == "https" {
6087 tlsState = sc.tlsState
6088 }
6089
6090 needsContinue := httpguts.HeaderValuesContainsToken(rp.header["Expect"], "100-continue")
6091 if needsContinue {
6092 rp.header.Del("Expect")
6093 }
6094
6095 if cookies := rp.header["Cookie"]; len(cookies) > 1 {
6096 rp.header.Set("Cookie", strings.Join(cookies, "; "))
6097 }
6098
6099
6100 var trailer Header
6101 for _, v := range rp.header["Trailer"] {
6102 for _, key := range strings.Split(v, ",") {
6103 key = CanonicalHeaderKey(textproto.TrimString(key))
6104 switch key {
6105 case "Transfer-Encoding", "Trailer", "Content-Length":
6106
6107
6108 default:
6109 if trailer == nil {
6110 trailer = make(Header)
6111 }
6112 trailer[key] = nil
6113 }
6114 }
6115 }
6116 delete(rp.header, "Trailer")
6117
6118 var url_ *url.URL
6119 var requestURI string
6120 if rp.method == "CONNECT" {
6121 url_ = &url.URL{Host: rp.authority}
6122 requestURI = rp.authority
6123 } else {
6124 var err error
6125 url_, err = url.ParseRequestURI(rp.path)
6126 if err != nil {
6127 return nil, nil, sc.countError("bad_path", http2streamError(st.id, http2ErrCodeProtocol))
6128 }
6129 requestURI = rp.path
6130 }
6131
6132 body := &http2requestBody{
6133 conn: sc,
6134 stream: st,
6135 needsContinue: needsContinue,
6136 }
6137 req := &Request{
6138 Method: rp.method,
6139 URL: url_,
6140 RemoteAddr: sc.remoteAddrStr,
6141 Header: rp.header,
6142 RequestURI: requestURI,
6143 Proto: "HTTP/2.0",
6144 ProtoMajor: 2,
6145 ProtoMinor: 0,
6146 TLS: tlsState,
6147 Host: rp.authority,
6148 Body: body,
6149 Trailer: trailer,
6150 }
6151 req = req.WithContext(st.ctx)
6152
6153 rw := sc.newResponseWriter(st, req)
6154 return rw, req, nil
6155 }
6156
6157 func (sc *http2serverConn) newResponseWriter(st *http2stream, req *Request) *http2responseWriter {
6158 rws := http2responseWriterStatePool.Get().(*http2responseWriterState)
6159 bwSave := rws.bw
6160 *rws = http2responseWriterState{}
6161 rws.conn = sc
6162 rws.bw = bwSave
6163 rws.bw.Reset(http2chunkWriter{rws})
6164 rws.stream = st
6165 rws.req = req
6166 return &http2responseWriter{rws: rws}
6167 }
6168
6169 type http2unstartedHandler struct {
6170 streamID uint32
6171 rw *http2responseWriter
6172 req *Request
6173 handler func(ResponseWriter, *Request)
6174 }
6175
6176
6177
6178 func (sc *http2serverConn) scheduleHandler(streamID uint32, rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request)) error {
6179 sc.serveG.check()
6180 maxHandlers := sc.advMaxStreams
6181 if sc.curHandlers < maxHandlers {
6182 sc.curHandlers++
6183 go sc.runHandler(rw, req, handler)
6184 return nil
6185 }
6186 if len(sc.unstartedHandlers) > int(4*sc.advMaxStreams) {
6187 return sc.countError("too_many_early_resets", http2ConnectionError(http2ErrCodeEnhanceYourCalm))
6188 }
6189 sc.unstartedHandlers = append(sc.unstartedHandlers, http2unstartedHandler{
6190 streamID: streamID,
6191 rw: rw,
6192 req: req,
6193 handler: handler,
6194 })
6195 return nil
6196 }
6197
6198 func (sc *http2serverConn) handlerDone() {
6199 sc.serveG.check()
6200 sc.curHandlers--
6201 i := 0
6202 maxHandlers := sc.advMaxStreams
6203 for ; i < len(sc.unstartedHandlers); i++ {
6204 u := sc.unstartedHandlers[i]
6205 if sc.streams[u.streamID] == nil {
6206
6207 continue
6208 }
6209 if sc.curHandlers >= maxHandlers {
6210 break
6211 }
6212 sc.curHandlers++
6213 go sc.runHandler(u.rw, u.req, u.handler)
6214 sc.unstartedHandlers[i] = http2unstartedHandler{}
6215 }
6216 sc.unstartedHandlers = sc.unstartedHandlers[i:]
6217 if len(sc.unstartedHandlers) == 0 {
6218 sc.unstartedHandlers = nil
6219 }
6220 }
6221
6222
6223 func (sc *http2serverConn) runHandler(rw *http2responseWriter, req *Request, handler func(ResponseWriter, *Request)) {
6224 sc.srv.markNewGoroutine()
6225 defer sc.sendServeMsg(http2handlerDoneMsg)
6226 didPanic := true
6227 defer func() {
6228 rw.rws.stream.cancelCtx()
6229 if req.MultipartForm != nil {
6230 req.MultipartForm.RemoveAll()
6231 }
6232 if didPanic {
6233 e := recover()
6234 sc.writeFrameFromHandler(http2FrameWriteRequest{
6235 write: http2handlerPanicRST{rw.rws.stream.id},
6236 stream: rw.rws.stream,
6237 })
6238
6239 if e != nil && e != ErrAbortHandler {
6240 const size = 64 << 10
6241 buf := make([]byte, size)
6242 buf = buf[:runtime.Stack(buf, false)]
6243 sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
6244 }
6245 return
6246 }
6247 rw.handlerDone()
6248 }()
6249 handler(rw, req)
6250 didPanic = false
6251 }
6252
6253 func http2handleHeaderListTooLong(w ResponseWriter, r *Request) {
6254
6255
6256
6257
6258 const statusRequestHeaderFieldsTooLarge = 431
6259 w.WriteHeader(statusRequestHeaderFieldsTooLarge)
6260 io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
6261 }
6262
6263
6264
6265 func (sc *http2serverConn) writeHeaders(st *http2stream, headerData *http2writeResHeaders) error {
6266 sc.serveG.checkNotOn()
6267 var errc chan error
6268 if headerData.h != nil {
6269
6270
6271
6272
6273 errc = http2errChanPool.Get().(chan error)
6274 }
6275 if err := sc.writeFrameFromHandler(http2FrameWriteRequest{
6276 write: headerData,
6277 stream: st,
6278 done: errc,
6279 }); err != nil {
6280 return err
6281 }
6282 if errc != nil {
6283 select {
6284 case err := <-errc:
6285 http2errChanPool.Put(errc)
6286 return err
6287 case <-sc.doneServing:
6288 return http2errClientDisconnected
6289 case <-st.cw:
6290 return http2errStreamClosed
6291 }
6292 }
6293 return nil
6294 }
6295
6296
6297 func (sc *http2serverConn) write100ContinueHeaders(st *http2stream) {
6298 sc.writeFrameFromHandler(http2FrameWriteRequest{
6299 write: http2write100ContinueHeadersFrame{st.id},
6300 stream: st,
6301 })
6302 }
6303
6304
6305
6306 type http2bodyReadMsg struct {
6307 st *http2stream
6308 n int
6309 }
6310
6311
6312
6313
6314 func (sc *http2serverConn) noteBodyReadFromHandler(st *http2stream, n int, err error) {
6315 sc.serveG.checkNotOn()
6316 if n > 0 {
6317 select {
6318 case sc.bodyReadCh <- http2bodyReadMsg{st, n}:
6319 case <-sc.doneServing:
6320 }
6321 }
6322 }
6323
6324 func (sc *http2serverConn) noteBodyRead(st *http2stream, n int) {
6325 sc.serveG.check()
6326 sc.sendWindowUpdate(nil, n)
6327 if st.state != http2stateHalfClosedRemote && st.state != http2stateClosed {
6328
6329
6330 sc.sendWindowUpdate(st, n)
6331 }
6332 }
6333
6334
6335 func (sc *http2serverConn) sendWindowUpdate32(st *http2stream, n int32) {
6336 sc.sendWindowUpdate(st, int(n))
6337 }
6338
6339
6340 func (sc *http2serverConn) sendWindowUpdate(st *http2stream, n int) {
6341 sc.serveG.check()
6342 var streamID uint32
6343 var send int32
6344 if st == nil {
6345 send = sc.inflow.add(n)
6346 } else {
6347 streamID = st.id
6348 send = st.inflow.add(n)
6349 }
6350 if send == 0 {
6351 return
6352 }
6353 sc.writeFrame(http2FrameWriteRequest{
6354 write: http2writeWindowUpdate{streamID: streamID, n: uint32(send)},
6355 stream: st,
6356 })
6357 }
6358
6359
6360
6361 type http2requestBody struct {
6362 _ http2incomparable
6363 stream *http2stream
6364 conn *http2serverConn
6365 closeOnce sync.Once
6366 sawEOF bool
6367 pipe *http2pipe
6368 needsContinue bool
6369 }
6370
6371 func (b *http2requestBody) Close() error {
6372 b.closeOnce.Do(func() {
6373 if b.pipe != nil {
6374 b.pipe.BreakWithError(http2errClosedBody)
6375 }
6376 })
6377 return nil
6378 }
6379
6380 func (b *http2requestBody) Read(p []byte) (n int, err error) {
6381 if b.needsContinue {
6382 b.needsContinue = false
6383 b.conn.write100ContinueHeaders(b.stream)
6384 }
6385 if b.pipe == nil || b.sawEOF {
6386 return 0, io.EOF
6387 }
6388 n, err = b.pipe.Read(p)
6389 if err == io.EOF {
6390 b.sawEOF = true
6391 }
6392 if b.conn == nil && http2inTests {
6393 return
6394 }
6395 b.conn.noteBodyReadFromHandler(b.stream, n, err)
6396 return
6397 }
6398
6399
6400
6401
6402
6403
6404
6405 type http2responseWriter struct {
6406 rws *http2responseWriterState
6407 }
6408
6409
6410 var (
6411 _ CloseNotifier = (*http2responseWriter)(nil)
6412 _ Flusher = (*http2responseWriter)(nil)
6413 _ http2stringWriter = (*http2responseWriter)(nil)
6414 )
6415
6416 type http2responseWriterState struct {
6417
6418 stream *http2stream
6419 req *Request
6420 conn *http2serverConn
6421
6422
6423 bw *bufio.Writer
6424
6425
6426 handlerHeader Header
6427 snapHeader Header
6428 trailers []string
6429 status int
6430 wroteHeader bool
6431 sentHeader bool
6432 handlerDone bool
6433
6434 sentContentLen int64
6435 wroteBytes int64
6436
6437 closeNotifierMu sync.Mutex
6438 closeNotifierCh chan bool
6439 }
6440
6441 type http2chunkWriter struct{ rws *http2responseWriterState }
6442
6443 func (cw http2chunkWriter) Write(p []byte) (n int, err error) {
6444 n, err = cw.rws.writeChunk(p)
6445 if err == http2errStreamClosed {
6446
6447
6448 err = cw.rws.stream.closeErr
6449 }
6450 return n, err
6451 }
6452
6453 func (rws *http2responseWriterState) hasTrailers() bool { return len(rws.trailers) > 0 }
6454
6455 func (rws *http2responseWriterState) hasNonemptyTrailers() bool {
6456 for _, trailer := range rws.trailers {
6457 if _, ok := rws.handlerHeader[trailer]; ok {
6458 return true
6459 }
6460 }
6461 return false
6462 }
6463
6464
6465
6466
6467 func (rws *http2responseWriterState) declareTrailer(k string) {
6468 k = CanonicalHeaderKey(k)
6469 if !httpguts.ValidTrailerHeader(k) {
6470
6471 rws.conn.logf("ignoring invalid trailer %q", k)
6472 return
6473 }
6474 if !http2strSliceContains(rws.trailers, k) {
6475 rws.trailers = append(rws.trailers, k)
6476 }
6477 }
6478
6479
6480
6481
6482
6483
6484
6485 func (rws *http2responseWriterState) writeChunk(p []byte) (n int, err error) {
6486 if !rws.wroteHeader {
6487 rws.writeHeader(200)
6488 }
6489
6490 if rws.handlerDone {
6491 rws.promoteUndeclaredTrailers()
6492 }
6493
6494 isHeadResp := rws.req.Method == "HEAD"
6495 if !rws.sentHeader {
6496 rws.sentHeader = true
6497 var ctype, clen string
6498 if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
6499 rws.snapHeader.Del("Content-Length")
6500 if cl, err := strconv.ParseUint(clen, 10, 63); err == nil {
6501 rws.sentContentLen = int64(cl)
6502 } else {
6503 clen = ""
6504 }
6505 }
6506 _, hasContentLength := rws.snapHeader["Content-Length"]
6507 if !hasContentLength && clen == "" && rws.handlerDone && http2bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
6508 clen = strconv.Itoa(len(p))
6509 }
6510 _, hasContentType := rws.snapHeader["Content-Type"]
6511
6512
6513 ce := rws.snapHeader.Get("Content-Encoding")
6514 hasCE := len(ce) > 0
6515 if !hasCE && !hasContentType && http2bodyAllowedForStatus(rws.status) && len(p) > 0 {
6516 ctype = DetectContentType(p)
6517 }
6518 var date string
6519 if _, ok := rws.snapHeader["Date"]; !ok {
6520
6521 date = rws.conn.srv.now().UTC().Format(TimeFormat)
6522 }
6523
6524 for _, v := range rws.snapHeader["Trailer"] {
6525 http2foreachHeaderElement(v, rws.declareTrailer)
6526 }
6527
6528
6529
6530
6531
6532
6533 if _, ok := rws.snapHeader["Connection"]; ok {
6534 v := rws.snapHeader.Get("Connection")
6535 delete(rws.snapHeader, "Connection")
6536 if v == "close" {
6537 rws.conn.startGracefulShutdown()
6538 }
6539 }
6540
6541 endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
6542 err = rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
6543 streamID: rws.stream.id,
6544 httpResCode: rws.status,
6545 h: rws.snapHeader,
6546 endStream: endStream,
6547 contentType: ctype,
6548 contentLength: clen,
6549 date: date,
6550 })
6551 if err != nil {
6552 return 0, err
6553 }
6554 if endStream {
6555 return 0, nil
6556 }
6557 }
6558 if isHeadResp {
6559 return len(p), nil
6560 }
6561 if len(p) == 0 && !rws.handlerDone {
6562 return 0, nil
6563 }
6564
6565
6566
6567 hasNonemptyTrailers := rws.hasNonemptyTrailers()
6568 endStream := rws.handlerDone && !hasNonemptyTrailers
6569 if len(p) > 0 || endStream {
6570
6571 if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
6572 return 0, err
6573 }
6574 }
6575
6576 if rws.handlerDone && hasNonemptyTrailers {
6577 err = rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
6578 streamID: rws.stream.id,
6579 h: rws.handlerHeader,
6580 trailers: rws.trailers,
6581 endStream: true,
6582 })
6583 return len(p), err
6584 }
6585 return len(p), nil
6586 }
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601 const http2TrailerPrefix = "Trailer:"
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624 func (rws *http2responseWriterState) promoteUndeclaredTrailers() {
6625 for k, vv := range rws.handlerHeader {
6626 if !strings.HasPrefix(k, http2TrailerPrefix) {
6627 continue
6628 }
6629 trailerKey := strings.TrimPrefix(k, http2TrailerPrefix)
6630 rws.declareTrailer(trailerKey)
6631 rws.handlerHeader[CanonicalHeaderKey(trailerKey)] = vv
6632 }
6633
6634 if len(rws.trailers) > 1 {
6635 sorter := http2sorterPool.Get().(*http2sorter)
6636 sorter.SortStrings(rws.trailers)
6637 http2sorterPool.Put(sorter)
6638 }
6639 }
6640
6641 func (w *http2responseWriter) SetReadDeadline(deadline time.Time) error {
6642 st := w.rws.stream
6643 if !deadline.IsZero() && deadline.Before(w.rws.conn.srv.now()) {
6644
6645
6646 st.onReadTimeout()
6647 return nil
6648 }
6649 w.rws.conn.sendServeMsg(func(sc *http2serverConn) {
6650 if st.readDeadline != nil {
6651 if !st.readDeadline.Stop() {
6652
6653 return
6654 }
6655 }
6656 if deadline.IsZero() {
6657 st.readDeadline = nil
6658 } else if st.readDeadline == nil {
6659 st.readDeadline = sc.srv.afterFunc(deadline.Sub(sc.srv.now()), st.onReadTimeout)
6660 } else {
6661 st.readDeadline.Reset(deadline.Sub(sc.srv.now()))
6662 }
6663 })
6664 return nil
6665 }
6666
6667 func (w *http2responseWriter) SetWriteDeadline(deadline time.Time) error {
6668 st := w.rws.stream
6669 if !deadline.IsZero() && deadline.Before(w.rws.conn.srv.now()) {
6670
6671
6672 st.onWriteTimeout()
6673 return nil
6674 }
6675 w.rws.conn.sendServeMsg(func(sc *http2serverConn) {
6676 if st.writeDeadline != nil {
6677 if !st.writeDeadline.Stop() {
6678
6679 return
6680 }
6681 }
6682 if deadline.IsZero() {
6683 st.writeDeadline = nil
6684 } else if st.writeDeadline == nil {
6685 st.writeDeadline = sc.srv.afterFunc(deadline.Sub(sc.srv.now()), st.onWriteTimeout)
6686 } else {
6687 st.writeDeadline.Reset(deadline.Sub(sc.srv.now()))
6688 }
6689 })
6690 return nil
6691 }
6692
6693 func (w *http2responseWriter) Flush() {
6694 w.FlushError()
6695 }
6696
6697 func (w *http2responseWriter) FlushError() error {
6698 rws := w.rws
6699 if rws == nil {
6700 panic("Header called after Handler finished")
6701 }
6702 var err error
6703 if rws.bw.Buffered() > 0 {
6704 err = rws.bw.Flush()
6705 } else {
6706
6707
6708
6709
6710 _, err = http2chunkWriter{rws}.Write(nil)
6711 if err == nil {
6712 select {
6713 case <-rws.stream.cw:
6714 err = rws.stream.closeErr
6715 default:
6716 }
6717 }
6718 }
6719 return err
6720 }
6721
6722 func (w *http2responseWriter) CloseNotify() <-chan bool {
6723 rws := w.rws
6724 if rws == nil {
6725 panic("CloseNotify called after Handler finished")
6726 }
6727 rws.closeNotifierMu.Lock()
6728 ch := rws.closeNotifierCh
6729 if ch == nil {
6730 ch = make(chan bool, 1)
6731 rws.closeNotifierCh = ch
6732 cw := rws.stream.cw
6733 go func() {
6734 cw.Wait()
6735 ch <- true
6736 }()
6737 }
6738 rws.closeNotifierMu.Unlock()
6739 return ch
6740 }
6741
6742 func (w *http2responseWriter) Header() Header {
6743 rws := w.rws
6744 if rws == nil {
6745 panic("Header called after Handler finished")
6746 }
6747 if rws.handlerHeader == nil {
6748 rws.handlerHeader = make(Header)
6749 }
6750 return rws.handlerHeader
6751 }
6752
6753
6754 func http2checkWriteHeaderCode(code int) {
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765 if code < 100 || code > 999 {
6766 panic(fmt.Sprintf("invalid WriteHeader code %v", code))
6767 }
6768 }
6769
6770 func (w *http2responseWriter) WriteHeader(code int) {
6771 rws := w.rws
6772 if rws == nil {
6773 panic("WriteHeader called after Handler finished")
6774 }
6775 rws.writeHeader(code)
6776 }
6777
6778 func (rws *http2responseWriterState) writeHeader(code int) {
6779 if rws.wroteHeader {
6780 return
6781 }
6782
6783 http2checkWriteHeaderCode(code)
6784
6785
6786 if code >= 100 && code <= 199 {
6787
6788 h := rws.handlerHeader
6789
6790 _, cl := h["Content-Length"]
6791 _, te := h["Transfer-Encoding"]
6792 if cl || te {
6793 h = h.Clone()
6794 h.Del("Content-Length")
6795 h.Del("Transfer-Encoding")
6796 }
6797
6798 rws.conn.writeHeaders(rws.stream, &http2writeResHeaders{
6799 streamID: rws.stream.id,
6800 httpResCode: code,
6801 h: h,
6802 endStream: rws.handlerDone && !rws.hasTrailers(),
6803 })
6804
6805 return
6806 }
6807
6808 rws.wroteHeader = true
6809 rws.status = code
6810 if len(rws.handlerHeader) > 0 {
6811 rws.snapHeader = http2cloneHeader(rws.handlerHeader)
6812 }
6813 }
6814
6815 func http2cloneHeader(h Header) Header {
6816 h2 := make(Header, len(h))
6817 for k, vv := range h {
6818 vv2 := make([]string, len(vv))
6819 copy(vv2, vv)
6820 h2[k] = vv2
6821 }
6822 return h2
6823 }
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833 func (w *http2responseWriter) Write(p []byte) (n int, err error) {
6834 return w.write(len(p), p, "")
6835 }
6836
6837 func (w *http2responseWriter) WriteString(s string) (n int, err error) {
6838 return w.write(len(s), nil, s)
6839 }
6840
6841
6842 func (w *http2responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
6843 rws := w.rws
6844 if rws == nil {
6845 panic("Write called after Handler finished")
6846 }
6847 if !rws.wroteHeader {
6848 w.WriteHeader(200)
6849 }
6850 if !http2bodyAllowedForStatus(rws.status) {
6851 return 0, ErrBodyNotAllowed
6852 }
6853 rws.wroteBytes += int64(len(dataB)) + int64(len(dataS))
6854 if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
6855
6856 return 0, errors.New("http2: handler wrote more than declared Content-Length")
6857 }
6858
6859 if dataB != nil {
6860 return rws.bw.Write(dataB)
6861 } else {
6862 return rws.bw.WriteString(dataS)
6863 }
6864 }
6865
6866 func (w *http2responseWriter) handlerDone() {
6867 rws := w.rws
6868 rws.handlerDone = true
6869 w.Flush()
6870 w.rws = nil
6871 http2responseWriterStatePool.Put(rws)
6872 }
6873
6874
6875 var (
6876 http2ErrRecursivePush = errors.New("http2: recursive push not allowed")
6877 http2ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
6878 )
6879
6880 var _ Pusher = (*http2responseWriter)(nil)
6881
6882 func (w *http2responseWriter) Push(target string, opts *PushOptions) error {
6883 st := w.rws.stream
6884 sc := st.sc
6885 sc.serveG.checkNotOn()
6886
6887
6888
6889 if st.isPushed() {
6890 return http2ErrRecursivePush
6891 }
6892
6893 if opts == nil {
6894 opts = new(PushOptions)
6895 }
6896
6897
6898 if opts.Method == "" {
6899 opts.Method = "GET"
6900 }
6901 if opts.Header == nil {
6902 opts.Header = Header{}
6903 }
6904 wantScheme := "http"
6905 if w.rws.req.TLS != nil {
6906 wantScheme = "https"
6907 }
6908
6909
6910 u, err := url.Parse(target)
6911 if err != nil {
6912 return err
6913 }
6914 if u.Scheme == "" {
6915 if !strings.HasPrefix(target, "/") {
6916 return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
6917 }
6918 u.Scheme = wantScheme
6919 u.Host = w.rws.req.Host
6920 } else {
6921 if u.Scheme != wantScheme {
6922 return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
6923 }
6924 if u.Host == "" {
6925 return errors.New("URL must have a host")
6926 }
6927 }
6928 for k := range opts.Header {
6929 if strings.HasPrefix(k, ":") {
6930 return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
6931 }
6932
6933
6934
6935
6936 if http2asciiEqualFold(k, "content-length") ||
6937 http2asciiEqualFold(k, "content-encoding") ||
6938 http2asciiEqualFold(k, "trailer") ||
6939 http2asciiEqualFold(k, "te") ||
6940 http2asciiEqualFold(k, "expect") ||
6941 http2asciiEqualFold(k, "host") {
6942 return fmt.Errorf("promised request headers cannot include %q", k)
6943 }
6944 }
6945 if err := http2checkValidHTTP2RequestHeaders(opts.Header); err != nil {
6946 return err
6947 }
6948
6949
6950
6951
6952 if opts.Method != "GET" && opts.Method != "HEAD" {
6953 return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
6954 }
6955
6956 msg := &http2startPushRequest{
6957 parent: st,
6958 method: opts.Method,
6959 url: u,
6960 header: http2cloneHeader(opts.Header),
6961 done: http2errChanPool.Get().(chan error),
6962 }
6963
6964 select {
6965 case <-sc.doneServing:
6966 return http2errClientDisconnected
6967 case <-st.cw:
6968 return http2errStreamClosed
6969 case sc.serveMsgCh <- msg:
6970 }
6971
6972 select {
6973 case <-sc.doneServing:
6974 return http2errClientDisconnected
6975 case <-st.cw:
6976 return http2errStreamClosed
6977 case err := <-msg.done:
6978 http2errChanPool.Put(msg.done)
6979 return err
6980 }
6981 }
6982
6983 type http2startPushRequest struct {
6984 parent *http2stream
6985 method string
6986 url *url.URL
6987 header Header
6988 done chan error
6989 }
6990
6991 func (sc *http2serverConn) startPush(msg *http2startPushRequest) {
6992 sc.serveG.check()
6993
6994
6995
6996
6997 if msg.parent.state != http2stateOpen && msg.parent.state != http2stateHalfClosedRemote {
6998
6999 msg.done <- http2errStreamClosed
7000 return
7001 }
7002
7003
7004 if !sc.pushEnabled {
7005 msg.done <- ErrNotSupported
7006 return
7007 }
7008
7009
7010
7011
7012 allocatePromisedID := func() (uint32, error) {
7013 sc.serveG.check()
7014
7015
7016
7017 if !sc.pushEnabled {
7018 return 0, ErrNotSupported
7019 }
7020
7021 if sc.curPushedStreams+1 > sc.clientMaxStreams {
7022 return 0, http2ErrPushLimitReached
7023 }
7024
7025
7026
7027
7028
7029 if sc.maxPushPromiseID+2 >= 1<<31 {
7030 sc.startGracefulShutdownInternal()
7031 return 0, http2ErrPushLimitReached
7032 }
7033 sc.maxPushPromiseID += 2
7034 promisedID := sc.maxPushPromiseID
7035
7036
7037
7038
7039
7040
7041 promised := sc.newStream(promisedID, msg.parent.id, http2stateHalfClosedRemote)
7042 rw, req, err := sc.newWriterAndRequestNoBody(promised, http2requestParam{
7043 method: msg.method,
7044 scheme: msg.url.Scheme,
7045 authority: msg.url.Host,
7046 path: msg.url.RequestURI(),
7047 header: http2cloneHeader(msg.header),
7048 })
7049 if err != nil {
7050
7051 panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
7052 }
7053
7054 sc.curHandlers++
7055 go sc.runHandler(rw, req, sc.handler.ServeHTTP)
7056 return promisedID, nil
7057 }
7058
7059 sc.writeFrame(http2FrameWriteRequest{
7060 write: &http2writePushPromise{
7061 streamID: msg.parent.id,
7062 method: msg.method,
7063 url: msg.url,
7064 h: msg.header,
7065 allocatePromisedID: allocatePromisedID,
7066 },
7067 stream: msg.parent,
7068 done: msg.done,
7069 })
7070 }
7071
7072
7073
7074 func http2foreachHeaderElement(v string, fn func(string)) {
7075 v = textproto.TrimString(v)
7076 if v == "" {
7077 return
7078 }
7079 if !strings.Contains(v, ",") {
7080 fn(v)
7081 return
7082 }
7083 for _, f := range strings.Split(v, ",") {
7084 if f = textproto.TrimString(f); f != "" {
7085 fn(f)
7086 }
7087 }
7088 }
7089
7090
7091 var http2connHeaders = []string{
7092 "Connection",
7093 "Keep-Alive",
7094 "Proxy-Connection",
7095 "Transfer-Encoding",
7096 "Upgrade",
7097 }
7098
7099
7100
7101
7102 func http2checkValidHTTP2RequestHeaders(h Header) error {
7103 for _, k := range http2connHeaders {
7104 if _, ok := h[k]; ok {
7105 return fmt.Errorf("request header %q is not valid in HTTP/2", k)
7106 }
7107 }
7108 te := h["Te"]
7109 if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
7110 return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
7111 }
7112 return nil
7113 }
7114
7115 func http2new400Handler(err error) HandlerFunc {
7116 return func(w ResponseWriter, r *Request) {
7117 Error(w, err.Error(), StatusBadRequest)
7118 }
7119 }
7120
7121
7122
7123
7124 func http2h1ServerKeepAlivesDisabled(hs *Server) bool {
7125 var x interface{} = hs
7126 type I interface {
7127 doKeepAlives() bool
7128 }
7129 if hs, ok := x.(I); ok {
7130 return !hs.doKeepAlives()
7131 }
7132 return false
7133 }
7134
7135 func (sc *http2serverConn) countError(name string, err error) error {
7136 if sc == nil || sc.srv == nil {
7137 return err
7138 }
7139 f := sc.srv.CountError
7140 if f == nil {
7141 return err
7142 }
7143 var typ string
7144 var code http2ErrCode
7145 switch e := err.(type) {
7146 case http2ConnectionError:
7147 typ = "conn"
7148 code = http2ErrCode(e)
7149 case http2StreamError:
7150 typ = "stream"
7151 code = http2ErrCode(e.Code)
7152 default:
7153 return err
7154 }
7155 codeStr := http2errCodeName[code]
7156 if codeStr == "" {
7157 codeStr = strconv.Itoa(int(code))
7158 }
7159 f(fmt.Sprintf("%s_%s_%s", typ, codeStr, name))
7160 return err
7161 }
7162
7163
7164 type http2timer = interface {
7165 C() <-chan time.Time
7166 Reset(d time.Duration) bool
7167 Stop() bool
7168 }
7169
7170
7171 type http2timeTimer struct {
7172 *time.Timer
7173 }
7174
7175 func (t http2timeTimer) C() <-chan time.Time { return t.Timer.C }
7176
7177 const (
7178
7179
7180 http2transportDefaultConnFlow = 1 << 30
7181
7182
7183
7184
7185 http2transportDefaultStreamFlow = 4 << 20
7186
7187 http2defaultUserAgent = "Go-http-client/2.0"
7188
7189
7190
7191
7192 http2initialMaxConcurrentStreams = 100
7193
7194
7195
7196 http2defaultMaxConcurrentStreams = 1000
7197 )
7198
7199
7200
7201
7202
7203 type http2Transport struct {
7204
7205
7206
7207
7208
7209
7210
7211 DialTLSContext func(ctx context.Context, network, addr string, cfg *tls.Config) (net.Conn, error)
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221 DialTLS func(network, addr string, cfg *tls.Config) (net.Conn, error)
7222
7223
7224
7225 TLSClientConfig *tls.Config
7226
7227
7228
7229 ConnPool http2ClientConnPool
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239 DisableCompression bool
7240
7241
7242
7243 AllowHTTP bool
7244
7245
7246
7247
7248
7249
7250
7251
7252 MaxHeaderListSize uint32
7253
7254
7255
7256
7257
7258
7259
7260
7261 MaxReadFrameSize uint32
7262
7263
7264
7265
7266
7267
7268 MaxDecoderHeaderTableSize uint32
7269
7270
7271
7272
7273
7274 MaxEncoderHeaderTableSize uint32
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284 StrictMaxConcurrentStreams bool
7285
7286
7287
7288
7289
7290 IdleConnTimeout time.Duration
7291
7292
7293
7294
7295
7296
7297
7298 ReadIdleTimeout time.Duration
7299
7300
7301
7302
7303 PingTimeout time.Duration
7304
7305
7306
7307
7308 WriteByteTimeout time.Duration
7309
7310
7311
7312
7313
7314 CountError func(errType string)
7315
7316
7317
7318
7319 t1 *Transport
7320
7321 connPoolOnce sync.Once
7322 connPoolOrDef http2ClientConnPool
7323
7324 *http2transportTestHooks
7325 }
7326
7327
7328
7329
7330
7331 type http2transportTestHooks struct {
7332 newclientconn func(*http2ClientConn)
7333 group http2synctestGroupInterface
7334 }
7335
7336 func (t *http2Transport) markNewGoroutine() {
7337 if t != nil && t.http2transportTestHooks != nil {
7338 t.http2transportTestHooks.group.Join()
7339 }
7340 }
7341
7342
7343 func (t *http2Transport) newTimer(d time.Duration) http2timer {
7344 if t.http2transportTestHooks != nil {
7345 return t.http2transportTestHooks.group.NewTimer(d)
7346 }
7347 return http2timeTimer{time.NewTimer(d)}
7348 }
7349
7350
7351 func (t *http2Transport) afterFunc(d time.Duration, f func()) http2timer {
7352 if t.http2transportTestHooks != nil {
7353 return t.http2transportTestHooks.group.AfterFunc(d, f)
7354 }
7355 return http2timeTimer{time.AfterFunc(d, f)}
7356 }
7357
7358 func (t *http2Transport) contextWithTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
7359 if t.http2transportTestHooks != nil {
7360 return t.http2transportTestHooks.group.ContextWithTimeout(ctx, d)
7361 }
7362 return context.WithTimeout(ctx, d)
7363 }
7364
7365 func (t *http2Transport) maxHeaderListSize() uint32 {
7366 if t.MaxHeaderListSize == 0 {
7367 return 10 << 20
7368 }
7369 if t.MaxHeaderListSize == 0xffffffff {
7370 return 0
7371 }
7372 return t.MaxHeaderListSize
7373 }
7374
7375 func (t *http2Transport) maxFrameReadSize() uint32 {
7376 if t.MaxReadFrameSize == 0 {
7377 return 0
7378 }
7379 if t.MaxReadFrameSize < http2minMaxFrameSize {
7380 return http2minMaxFrameSize
7381 }
7382 if t.MaxReadFrameSize > http2maxFrameSize {
7383 return http2maxFrameSize
7384 }
7385 return t.MaxReadFrameSize
7386 }
7387
7388 func (t *http2Transport) disableCompression() bool {
7389 return t.DisableCompression || (t.t1 != nil && t.t1.DisableCompression)
7390 }
7391
7392 func (t *http2Transport) pingTimeout() time.Duration {
7393 if t.PingTimeout == 0 {
7394 return 15 * time.Second
7395 }
7396 return t.PingTimeout
7397
7398 }
7399
7400
7401
7402
7403
7404 func http2ConfigureTransport(t1 *Transport) error {
7405 _, err := http2ConfigureTransports(t1)
7406 return err
7407 }
7408
7409
7410
7411
7412 func http2ConfigureTransports(t1 *Transport) (*http2Transport, error) {
7413 return http2configureTransports(t1)
7414 }
7415
7416 func http2configureTransports(t1 *Transport) (*http2Transport, error) {
7417 connPool := new(http2clientConnPool)
7418 t2 := &http2Transport{
7419 ConnPool: http2noDialClientConnPool{connPool},
7420 t1: t1,
7421 }
7422 connPool.t = t2
7423 if err := http2registerHTTPSProtocol(t1, http2noDialH2RoundTripper{t2}); err != nil {
7424 return nil, err
7425 }
7426 if t1.TLSClientConfig == nil {
7427 t1.TLSClientConfig = new(tls.Config)
7428 }
7429 if !http2strSliceContains(t1.TLSClientConfig.NextProtos, "h2") {
7430 t1.TLSClientConfig.NextProtos = append([]string{"h2"}, t1.TLSClientConfig.NextProtos...)
7431 }
7432 if !http2strSliceContains(t1.TLSClientConfig.NextProtos, "http/1.1") {
7433 t1.TLSClientConfig.NextProtos = append(t1.TLSClientConfig.NextProtos, "http/1.1")
7434 }
7435 upgradeFn := func(authority string, c *tls.Conn) RoundTripper {
7436 addr := http2authorityAddr("https", authority)
7437 if used, err := connPool.addConnIfNeeded(addr, t2, c); err != nil {
7438 go c.Close()
7439 return http2erringRoundTripper{err}
7440 } else if !used {
7441
7442
7443
7444
7445 go c.Close()
7446 }
7447 return t2
7448 }
7449 if m := t1.TLSNextProto; len(m) == 0 {
7450 t1.TLSNextProto = map[string]func(string, *tls.Conn) RoundTripper{
7451 "h2": upgradeFn,
7452 }
7453 } else {
7454 m["h2"] = upgradeFn
7455 }
7456 return t2, nil
7457 }
7458
7459 func (t *http2Transport) connPool() http2ClientConnPool {
7460 t.connPoolOnce.Do(t.initConnPool)
7461 return t.connPoolOrDef
7462 }
7463
7464 func (t *http2Transport) initConnPool() {
7465 if t.ConnPool != nil {
7466 t.connPoolOrDef = t.ConnPool
7467 } else {
7468 t.connPoolOrDef = &http2clientConnPool{t: t}
7469 }
7470 }
7471
7472
7473
7474 type http2ClientConn struct {
7475 t *http2Transport
7476 tconn net.Conn
7477 tlsState *tls.ConnectionState
7478 reused uint32
7479 singleUse bool
7480 getConnCalled bool
7481
7482
7483 readerDone chan struct{}
7484 readerErr error
7485
7486 idleTimeout time.Duration
7487 idleTimer http2timer
7488
7489 mu sync.Mutex
7490 cond *sync.Cond
7491 flow http2outflow
7492 inflow http2inflow
7493 doNotReuse bool
7494 closing bool
7495 closed bool
7496 seenSettings bool
7497 wantSettingsAck bool
7498 goAway *http2GoAwayFrame
7499 goAwayDebug string
7500 streams map[uint32]*http2clientStream
7501 streamsReserved int
7502 nextStreamID uint32
7503 pendingRequests int
7504 pings map[[8]byte]chan struct{}
7505 br *bufio.Reader
7506 lastActive time.Time
7507 lastIdle time.Time
7508
7509 maxFrameSize uint32
7510 maxConcurrentStreams uint32
7511 peerMaxHeaderListSize uint64
7512 peerMaxHeaderTableSize uint32
7513 initialWindowSize uint32
7514
7515
7516
7517
7518 reqHeaderMu chan struct{}
7519
7520
7521
7522
7523 wmu sync.Mutex
7524 bw *bufio.Writer
7525 fr *http2Framer
7526 werr error
7527 hbuf bytes.Buffer
7528 henc *hpack.Encoder
7529 }
7530
7531
7532
7533 type http2clientStream struct {
7534 cc *http2ClientConn
7535
7536
7537 ctx context.Context
7538 reqCancel <-chan struct{}
7539
7540 trace *httptrace.ClientTrace
7541 ID uint32
7542 bufPipe http2pipe
7543 requestedGzip bool
7544 isHead bool
7545
7546 abortOnce sync.Once
7547 abort chan struct{}
7548 abortErr error
7549
7550 peerClosed chan struct{}
7551 donec chan struct{}
7552 on100 chan struct{}
7553
7554 respHeaderRecv chan struct{}
7555 res *Response
7556
7557 flow http2outflow
7558 inflow http2inflow
7559 bytesRemain int64
7560 readErr error
7561
7562 reqBody io.ReadCloser
7563 reqBodyContentLength int64
7564 reqBodyClosed chan struct{}
7565
7566
7567 sentEndStream bool
7568 sentHeaders bool
7569
7570
7571 firstByte bool
7572 pastHeaders bool
7573 pastTrailers bool
7574 num1xx uint8
7575 readClosed bool
7576 readAborted bool
7577
7578 trailer Header
7579 resTrailer *Header
7580 }
7581
7582 var http2got1xxFuncForTests func(int, textproto.MIMEHeader) error
7583
7584
7585
7586 func (cs *http2clientStream) get1xxTraceFunc() func(int, textproto.MIMEHeader) error {
7587 if fn := http2got1xxFuncForTests; fn != nil {
7588 return fn
7589 }
7590 return http2traceGot1xxResponseFunc(cs.trace)
7591 }
7592
7593 func (cs *http2clientStream) abortStream(err error) {
7594 cs.cc.mu.Lock()
7595 defer cs.cc.mu.Unlock()
7596 cs.abortStreamLocked(err)
7597 }
7598
7599 func (cs *http2clientStream) abortStreamLocked(err error) {
7600 cs.abortOnce.Do(func() {
7601 cs.abortErr = err
7602 close(cs.abort)
7603 })
7604 if cs.reqBody != nil {
7605 cs.closeReqBodyLocked()
7606 }
7607
7608 if cs.cc.cond != nil {
7609
7610 cs.cc.cond.Broadcast()
7611 }
7612 }
7613
7614 func (cs *http2clientStream) abortRequestBodyWrite() {
7615 cc := cs.cc
7616 cc.mu.Lock()
7617 defer cc.mu.Unlock()
7618 if cs.reqBody != nil && cs.reqBodyClosed == nil {
7619 cs.closeReqBodyLocked()
7620 cc.cond.Broadcast()
7621 }
7622 }
7623
7624 func (cs *http2clientStream) closeReqBodyLocked() {
7625 if cs.reqBodyClosed != nil {
7626 return
7627 }
7628 cs.reqBodyClosed = make(chan struct{})
7629 reqBodyClosed := cs.reqBodyClosed
7630 go func() {
7631 cs.cc.t.markNewGoroutine()
7632 cs.reqBody.Close()
7633 close(reqBodyClosed)
7634 }()
7635 }
7636
7637 type http2stickyErrWriter struct {
7638 conn net.Conn
7639 timeout time.Duration
7640 err *error
7641 }
7642
7643 func (sew http2stickyErrWriter) Write(p []byte) (n int, err error) {
7644 if *sew.err != nil {
7645 return 0, *sew.err
7646 }
7647 for {
7648 if sew.timeout != 0 {
7649 sew.conn.SetWriteDeadline(time.Now().Add(sew.timeout))
7650 }
7651 nn, err := sew.conn.Write(p[n:])
7652 n += nn
7653 if n < len(p) && nn > 0 && errors.Is(err, os.ErrDeadlineExceeded) {
7654
7655 continue
7656 }
7657 if sew.timeout != 0 {
7658 sew.conn.SetWriteDeadline(time.Time{})
7659 }
7660 *sew.err = err
7661 return n, err
7662 }
7663 }
7664
7665
7666
7667
7668
7669
7670
7671 type http2noCachedConnError struct{}
7672
7673 func (http2noCachedConnError) IsHTTP2NoCachedConnError() {}
7674
7675 func (http2noCachedConnError) Error() string { return "http2: no cached connection was available" }
7676
7677
7678
7679
7680 func http2isNoCachedConnError(err error) bool {
7681 _, ok := err.(interface{ IsHTTP2NoCachedConnError() })
7682 return ok
7683 }
7684
7685 var http2ErrNoCachedConn error = http2noCachedConnError{}
7686
7687
7688 type http2RoundTripOpt struct {
7689
7690
7691
7692
7693 OnlyCachedConn bool
7694 }
7695
7696 func (t *http2Transport) RoundTrip(req *Request) (*Response, error) {
7697 return t.RoundTripOpt(req, http2RoundTripOpt{})
7698 }
7699
7700
7701
7702 func http2authorityAddr(scheme string, authority string) (addr string) {
7703 host, port, err := net.SplitHostPort(authority)
7704 if err != nil {
7705 host = authority
7706 port = ""
7707 }
7708 if port == "" {
7709 port = "443"
7710 if scheme == "http" {
7711 port = "80"
7712 }
7713 }
7714 if a, err := idna.ToASCII(host); err == nil {
7715 host = a
7716 }
7717
7718 if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
7719 return host + ":" + port
7720 }
7721 return net.JoinHostPort(host, port)
7722 }
7723
7724
7725 func (t *http2Transport) RoundTripOpt(req *Request, opt http2RoundTripOpt) (*Response, error) {
7726 if !(req.URL.Scheme == "https" || (req.URL.Scheme == "http" && t.AllowHTTP)) {
7727 return nil, errors.New("http2: unsupported scheme")
7728 }
7729
7730 addr := http2authorityAddr(req.URL.Scheme, req.URL.Host)
7731 for retry := 0; ; retry++ {
7732 cc, err := t.connPool().GetClientConn(req, addr)
7733 if err != nil {
7734 t.vlogf("http2: Transport failed to get client conn for %s: %v", addr, err)
7735 return nil, err
7736 }
7737 reused := !atomic.CompareAndSwapUint32(&cc.reused, 0, 1)
7738 http2traceGotConn(req, cc, reused)
7739 res, err := cc.RoundTrip(req)
7740 if err != nil && retry <= 6 {
7741 roundTripErr := err
7742 if req, err = http2shouldRetryRequest(req, err); err == nil {
7743
7744 if retry == 0 {
7745 t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
7746 continue
7747 }
7748 backoff := float64(uint(1) << (uint(retry) - 1))
7749 backoff += backoff * (0.1 * mathrand.Float64())
7750 d := time.Second * time.Duration(backoff)
7751 tm := t.newTimer(d)
7752 select {
7753 case <-tm.C():
7754 t.vlogf("RoundTrip retrying after failure: %v", roundTripErr)
7755 continue
7756 case <-req.Context().Done():
7757 tm.Stop()
7758 err = req.Context().Err()
7759 }
7760 }
7761 }
7762 if err != nil {
7763 t.vlogf("RoundTrip failure: %v", err)
7764 return nil, err
7765 }
7766 return res, nil
7767 }
7768 }
7769
7770
7771
7772
7773 func (t *http2Transport) CloseIdleConnections() {
7774 if cp, ok := t.connPool().(http2clientConnPoolIdleCloser); ok {
7775 cp.closeIdleConnections()
7776 }
7777 }
7778
7779 var (
7780 http2errClientConnClosed = errors.New("http2: client conn is closed")
7781 http2errClientConnUnusable = errors.New("http2: client conn not usable")
7782 http2errClientConnGotGoAway = errors.New("http2: Transport received Server's graceful shutdown GOAWAY")
7783 )
7784
7785
7786
7787
7788
7789 func http2shouldRetryRequest(req *Request, err error) (*Request, error) {
7790 if !http2canRetryError(err) {
7791 return nil, err
7792 }
7793
7794
7795 if req.Body == nil || req.Body == NoBody {
7796 return req, nil
7797 }
7798
7799
7800
7801 if req.GetBody != nil {
7802 body, err := req.GetBody()
7803 if err != nil {
7804 return nil, err
7805 }
7806 newReq := *req
7807 newReq.Body = body
7808 return &newReq, nil
7809 }
7810
7811
7812
7813
7814 if err == http2errClientConnUnusable {
7815 return req, nil
7816 }
7817
7818 return nil, fmt.Errorf("http2: Transport: cannot retry err [%v] after Request.Body was written; define Request.GetBody to avoid this error", err)
7819 }
7820
7821 func http2canRetryError(err error) bool {
7822 if err == http2errClientConnUnusable || err == http2errClientConnGotGoAway {
7823 return true
7824 }
7825 if se, ok := err.(http2StreamError); ok {
7826 if se.Code == http2ErrCodeProtocol && se.Cause == http2errFromPeer {
7827
7828 return true
7829 }
7830 return se.Code == http2ErrCodeRefusedStream
7831 }
7832 return false
7833 }
7834
7835 func (t *http2Transport) dialClientConn(ctx context.Context, addr string, singleUse bool) (*http2ClientConn, error) {
7836 if t.http2transportTestHooks != nil {
7837 return t.newClientConn(nil, singleUse)
7838 }
7839 host, _, err := net.SplitHostPort(addr)
7840 if err != nil {
7841 return nil, err
7842 }
7843 tconn, err := t.dialTLS(ctx, "tcp", addr, t.newTLSConfig(host))
7844 if err != nil {
7845 return nil, err
7846 }
7847 return t.newClientConn(tconn, singleUse)
7848 }
7849
7850 func (t *http2Transport) newTLSConfig(host string) *tls.Config {
7851 cfg := new(tls.Config)
7852 if t.TLSClientConfig != nil {
7853 *cfg = *t.TLSClientConfig.Clone()
7854 }
7855 if !http2strSliceContains(cfg.NextProtos, http2NextProtoTLS) {
7856 cfg.NextProtos = append([]string{http2NextProtoTLS}, cfg.NextProtos...)
7857 }
7858 if cfg.ServerName == "" {
7859 cfg.ServerName = host
7860 }
7861 return cfg
7862 }
7863
7864 func (t *http2Transport) dialTLS(ctx context.Context, network, addr string, tlsCfg *tls.Config) (net.Conn, error) {
7865 if t.DialTLSContext != nil {
7866 return t.DialTLSContext(ctx, network, addr, tlsCfg)
7867 } else if t.DialTLS != nil {
7868 return t.DialTLS(network, addr, tlsCfg)
7869 }
7870
7871 tlsCn, err := t.dialTLSWithContext(ctx, network, addr, tlsCfg)
7872 if err != nil {
7873 return nil, err
7874 }
7875 state := tlsCn.ConnectionState()
7876 if p := state.NegotiatedProtocol; p != http2NextProtoTLS {
7877 return nil, fmt.Errorf("http2: unexpected ALPN protocol %q; want %q", p, http2NextProtoTLS)
7878 }
7879 if !state.NegotiatedProtocolIsMutual {
7880 return nil, errors.New("http2: could not negotiate protocol mutually")
7881 }
7882 return tlsCn, nil
7883 }
7884
7885
7886
7887 func (t *http2Transport) disableKeepAlives() bool {
7888 return t.t1 != nil && t.t1.DisableKeepAlives
7889 }
7890
7891 func (t *http2Transport) expectContinueTimeout() time.Duration {
7892 if t.t1 == nil {
7893 return 0
7894 }
7895 return t.t1.ExpectContinueTimeout
7896 }
7897
7898 func (t *http2Transport) maxDecoderHeaderTableSize() uint32 {
7899 if v := t.MaxDecoderHeaderTableSize; v > 0 {
7900 return v
7901 }
7902 return http2initialHeaderTableSize
7903 }
7904
7905 func (t *http2Transport) maxEncoderHeaderTableSize() uint32 {
7906 if v := t.MaxEncoderHeaderTableSize; v > 0 {
7907 return v
7908 }
7909 return http2initialHeaderTableSize
7910 }
7911
7912 func (t *http2Transport) NewClientConn(c net.Conn) (*http2ClientConn, error) {
7913 return t.newClientConn(c, t.disableKeepAlives())
7914 }
7915
7916 func (t *http2Transport) newClientConn(c net.Conn, singleUse bool) (*http2ClientConn, error) {
7917 cc := &http2ClientConn{
7918 t: t,
7919 tconn: c,
7920 readerDone: make(chan struct{}),
7921 nextStreamID: 1,
7922 maxFrameSize: 16 << 10,
7923 initialWindowSize: 65535,
7924 maxConcurrentStreams: http2initialMaxConcurrentStreams,
7925 peerMaxHeaderListSize: 0xffffffffffffffff,
7926 streams: make(map[uint32]*http2clientStream),
7927 singleUse: singleUse,
7928 wantSettingsAck: true,
7929 pings: make(map[[8]byte]chan struct{}),
7930 reqHeaderMu: make(chan struct{}, 1),
7931 }
7932 if t.http2transportTestHooks != nil {
7933 t.markNewGoroutine()
7934 t.http2transportTestHooks.newclientconn(cc)
7935 c = cc.tconn
7936 }
7937 if http2VerboseLogs {
7938 t.vlogf("http2: Transport creating client conn %p to %v", cc, c.RemoteAddr())
7939 }
7940
7941 cc.cond = sync.NewCond(&cc.mu)
7942 cc.flow.add(int32(http2initialWindowSize))
7943
7944
7945
7946 cc.bw = bufio.NewWriter(http2stickyErrWriter{
7947 conn: c,
7948 timeout: t.WriteByteTimeout,
7949 err: &cc.werr,
7950 })
7951 cc.br = bufio.NewReader(c)
7952 cc.fr = http2NewFramer(cc.bw, cc.br)
7953 if t.maxFrameReadSize() != 0 {
7954 cc.fr.SetMaxReadFrameSize(t.maxFrameReadSize())
7955 }
7956 if t.CountError != nil {
7957 cc.fr.countError = t.CountError
7958 }
7959 maxHeaderTableSize := t.maxDecoderHeaderTableSize()
7960 cc.fr.ReadMetaHeaders = hpack.NewDecoder(maxHeaderTableSize, nil)
7961 cc.fr.MaxHeaderListSize = t.maxHeaderListSize()
7962
7963 cc.henc = hpack.NewEncoder(&cc.hbuf)
7964 cc.henc.SetMaxDynamicTableSizeLimit(t.maxEncoderHeaderTableSize())
7965 cc.peerMaxHeaderTableSize = http2initialHeaderTableSize
7966
7967 if cs, ok := c.(http2connectionStater); ok {
7968 state := cs.ConnectionState()
7969 cc.tlsState = &state
7970 }
7971
7972 initialSettings := []http2Setting{
7973 {ID: http2SettingEnablePush, Val: 0},
7974 {ID: http2SettingInitialWindowSize, Val: http2transportDefaultStreamFlow},
7975 }
7976 if max := t.maxFrameReadSize(); max != 0 {
7977 initialSettings = append(initialSettings, http2Setting{ID: http2SettingMaxFrameSize, Val: max})
7978 }
7979 if max := t.maxHeaderListSize(); max != 0 {
7980 initialSettings = append(initialSettings, http2Setting{ID: http2SettingMaxHeaderListSize, Val: max})
7981 }
7982 if maxHeaderTableSize != http2initialHeaderTableSize {
7983 initialSettings = append(initialSettings, http2Setting{ID: http2SettingHeaderTableSize, Val: maxHeaderTableSize})
7984 }
7985
7986 cc.bw.Write(http2clientPreface)
7987 cc.fr.WriteSettings(initialSettings...)
7988 cc.fr.WriteWindowUpdate(0, http2transportDefaultConnFlow)
7989 cc.inflow.init(http2transportDefaultConnFlow + http2initialWindowSize)
7990 cc.bw.Flush()
7991 if cc.werr != nil {
7992 cc.Close()
7993 return nil, cc.werr
7994 }
7995
7996
7997 if d := t.idleConnTimeout(); d != 0 {
7998 cc.idleTimeout = d
7999 cc.idleTimer = t.afterFunc(d, cc.onIdleTimeout)
8000 }
8001
8002 go cc.readLoop()
8003 return cc, nil
8004 }
8005
8006 func (cc *http2ClientConn) healthCheck() {
8007 pingTimeout := cc.t.pingTimeout()
8008
8009
8010 ctx, cancel := cc.t.contextWithTimeout(context.Background(), pingTimeout)
8011 defer cancel()
8012 cc.vlogf("http2: Transport sending health check")
8013 err := cc.Ping(ctx)
8014 if err != nil {
8015 cc.vlogf("http2: Transport health check failure: %v", err)
8016 cc.closeForLostPing()
8017 } else {
8018 cc.vlogf("http2: Transport health check success")
8019 }
8020 }
8021
8022
8023 func (cc *http2ClientConn) SetDoNotReuse() {
8024 cc.mu.Lock()
8025 defer cc.mu.Unlock()
8026 cc.doNotReuse = true
8027 }
8028
8029 func (cc *http2ClientConn) setGoAway(f *http2GoAwayFrame) {
8030 cc.mu.Lock()
8031 defer cc.mu.Unlock()
8032
8033 old := cc.goAway
8034 cc.goAway = f
8035
8036
8037 if cc.goAwayDebug == "" {
8038 cc.goAwayDebug = string(f.DebugData())
8039 }
8040 if old != nil && old.ErrCode != http2ErrCodeNo {
8041 cc.goAway.ErrCode = old.ErrCode
8042 }
8043 last := f.LastStreamID
8044 for streamID, cs := range cc.streams {
8045 if streamID <= last {
8046
8047
8048
8049 continue
8050 }
8051 if streamID == 1 && cc.goAway.ErrCode != http2ErrCodeNo {
8052
8053
8054
8055 cs.abortStreamLocked(fmt.Errorf("http2: Transport received GOAWAY from server ErrCode:%v", cc.goAway.ErrCode))
8056 } else {
8057
8058
8059 cs.abortStreamLocked(http2errClientConnGotGoAway)
8060 }
8061 }
8062 }
8063
8064
8065
8066
8067
8068
8069 func (cc *http2ClientConn) CanTakeNewRequest() bool {
8070 cc.mu.Lock()
8071 defer cc.mu.Unlock()
8072 return cc.canTakeNewRequestLocked()
8073 }
8074
8075
8076
8077
8078 func (cc *http2ClientConn) ReserveNewRequest() bool {
8079 cc.mu.Lock()
8080 defer cc.mu.Unlock()
8081 if st := cc.idleStateLocked(); !st.canTakeNewRequest {
8082 return false
8083 }
8084 cc.streamsReserved++
8085 return true
8086 }
8087
8088
8089 type http2ClientConnState struct {
8090
8091 Closed bool
8092
8093
8094
8095
8096
8097 Closing bool
8098
8099
8100 StreamsActive int
8101
8102
8103
8104 StreamsReserved int
8105
8106
8107
8108
8109 StreamsPending int
8110
8111
8112
8113
8114 MaxConcurrentStreams uint32
8115
8116
8117
8118 LastIdle time.Time
8119 }
8120
8121
8122 func (cc *http2ClientConn) State() http2ClientConnState {
8123 cc.wmu.Lock()
8124 maxConcurrent := cc.maxConcurrentStreams
8125 if !cc.seenSettings {
8126 maxConcurrent = 0
8127 }
8128 cc.wmu.Unlock()
8129
8130 cc.mu.Lock()
8131 defer cc.mu.Unlock()
8132 return http2ClientConnState{
8133 Closed: cc.closed,
8134 Closing: cc.closing || cc.singleUse || cc.doNotReuse || cc.goAway != nil,
8135 StreamsActive: len(cc.streams),
8136 StreamsReserved: cc.streamsReserved,
8137 StreamsPending: cc.pendingRequests,
8138 LastIdle: cc.lastIdle,
8139 MaxConcurrentStreams: maxConcurrent,
8140 }
8141 }
8142
8143
8144
8145 type http2clientConnIdleState struct {
8146 canTakeNewRequest bool
8147 }
8148
8149 func (cc *http2ClientConn) idleState() http2clientConnIdleState {
8150 cc.mu.Lock()
8151 defer cc.mu.Unlock()
8152 return cc.idleStateLocked()
8153 }
8154
8155 func (cc *http2ClientConn) idleStateLocked() (st http2clientConnIdleState) {
8156 if cc.singleUse && cc.nextStreamID > 1 {
8157 return
8158 }
8159 var maxConcurrentOkay bool
8160 if cc.t.StrictMaxConcurrentStreams {
8161
8162
8163
8164
8165 maxConcurrentOkay = true
8166 } else {
8167 maxConcurrentOkay = int64(len(cc.streams)+cc.streamsReserved+1) <= int64(cc.maxConcurrentStreams)
8168 }
8169
8170 st.canTakeNewRequest = cc.goAway == nil && !cc.closed && !cc.closing && maxConcurrentOkay &&
8171 !cc.doNotReuse &&
8172 int64(cc.nextStreamID)+2*int64(cc.pendingRequests) < math.MaxInt32 &&
8173 !cc.tooIdleLocked()
8174 return
8175 }
8176
8177 func (cc *http2ClientConn) canTakeNewRequestLocked() bool {
8178 st := cc.idleStateLocked()
8179 return st.canTakeNewRequest
8180 }
8181
8182
8183
8184 func (cc *http2ClientConn) tooIdleLocked() bool {
8185
8186
8187
8188
8189 return cc.idleTimeout != 0 && !cc.lastIdle.IsZero() && time.Since(cc.lastIdle.Round(0)) > cc.idleTimeout
8190 }
8191
8192
8193
8194
8195
8196
8197
8198 func (cc *http2ClientConn) onIdleTimeout() {
8199 cc.closeIfIdle()
8200 }
8201
8202 func (cc *http2ClientConn) closeConn() {
8203 t := time.AfterFunc(250*time.Millisecond, cc.forceCloseConn)
8204 defer t.Stop()
8205 cc.tconn.Close()
8206 }
8207
8208
8209
8210 func (cc *http2ClientConn) forceCloseConn() {
8211 tc, ok := cc.tconn.(*tls.Conn)
8212 if !ok {
8213 return
8214 }
8215 if nc := tc.NetConn(); nc != nil {
8216 nc.Close()
8217 }
8218 }
8219
8220 func (cc *http2ClientConn) closeIfIdle() {
8221 cc.mu.Lock()
8222 if len(cc.streams) > 0 || cc.streamsReserved > 0 {
8223 cc.mu.Unlock()
8224 return
8225 }
8226 cc.closed = true
8227 nextID := cc.nextStreamID
8228
8229 cc.mu.Unlock()
8230
8231 if http2VerboseLogs {
8232 cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, nextID-2)
8233 }
8234 cc.closeConn()
8235 }
8236
8237 func (cc *http2ClientConn) isDoNotReuseAndIdle() bool {
8238 cc.mu.Lock()
8239 defer cc.mu.Unlock()
8240 return cc.doNotReuse && len(cc.streams) == 0
8241 }
8242
8243 var http2shutdownEnterWaitStateHook = func() {}
8244
8245
8246 func (cc *http2ClientConn) Shutdown(ctx context.Context) error {
8247 if err := cc.sendGoAway(); err != nil {
8248 return err
8249 }
8250
8251 done := make(chan struct{})
8252 cancelled := false
8253 go func() {
8254 cc.t.markNewGoroutine()
8255 cc.mu.Lock()
8256 defer cc.mu.Unlock()
8257 for {
8258 if len(cc.streams) == 0 || cc.closed {
8259 cc.closed = true
8260 close(done)
8261 break
8262 }
8263 if cancelled {
8264 break
8265 }
8266 cc.cond.Wait()
8267 }
8268 }()
8269 http2shutdownEnterWaitStateHook()
8270 select {
8271 case <-done:
8272 cc.closeConn()
8273 return nil
8274 case <-ctx.Done():
8275 cc.mu.Lock()
8276
8277 cancelled = true
8278 cc.cond.Broadcast()
8279 cc.mu.Unlock()
8280 return ctx.Err()
8281 }
8282 }
8283
8284 func (cc *http2ClientConn) sendGoAway() error {
8285 cc.mu.Lock()
8286 closing := cc.closing
8287 cc.closing = true
8288 maxStreamID := cc.nextStreamID
8289 cc.mu.Unlock()
8290 if closing {
8291
8292 return nil
8293 }
8294
8295 cc.wmu.Lock()
8296 defer cc.wmu.Unlock()
8297
8298 if err := cc.fr.WriteGoAway(maxStreamID, http2ErrCodeNo, nil); err != nil {
8299 return err
8300 }
8301 if err := cc.bw.Flush(); err != nil {
8302 return err
8303 }
8304
8305 return nil
8306 }
8307
8308
8309
8310 func (cc *http2ClientConn) closeForError(err error) {
8311 cc.mu.Lock()
8312 cc.closed = true
8313 for _, cs := range cc.streams {
8314 cs.abortStreamLocked(err)
8315 }
8316 cc.cond.Broadcast()
8317 cc.mu.Unlock()
8318 cc.closeConn()
8319 }
8320
8321
8322
8323
8324 func (cc *http2ClientConn) Close() error {
8325 err := errors.New("http2: client connection force closed via ClientConn.Close")
8326 cc.closeForError(err)
8327 return nil
8328 }
8329
8330
8331 func (cc *http2ClientConn) closeForLostPing() {
8332 err := errors.New("http2: client connection lost")
8333 if f := cc.t.CountError; f != nil {
8334 f("conn_close_lost_ping")
8335 }
8336 cc.closeForError(err)
8337 }
8338
8339
8340
8341 var http2errRequestCanceled = errors.New("net/http: request canceled")
8342
8343 func http2commaSeparatedTrailers(req *Request) (string, error) {
8344 keys := make([]string, 0, len(req.Trailer))
8345 for k := range req.Trailer {
8346 k = http2canonicalHeader(k)
8347 switch k {
8348 case "Transfer-Encoding", "Trailer", "Content-Length":
8349 return "", fmt.Errorf("invalid Trailer key %q", k)
8350 }
8351 keys = append(keys, k)
8352 }
8353 if len(keys) > 0 {
8354 sort.Strings(keys)
8355 return strings.Join(keys, ","), nil
8356 }
8357 return "", nil
8358 }
8359
8360 func (cc *http2ClientConn) responseHeaderTimeout() time.Duration {
8361 if cc.t.t1 != nil {
8362 return cc.t.t1.ResponseHeaderTimeout
8363 }
8364
8365
8366
8367
8368 return 0
8369 }
8370
8371
8372
8373
8374 func http2checkConnHeaders(req *Request) error {
8375 if v := req.Header.Get("Upgrade"); v != "" {
8376 return fmt.Errorf("http2: invalid Upgrade request header: %q", req.Header["Upgrade"])
8377 }
8378 if vv := req.Header["Transfer-Encoding"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && vv[0] != "chunked") {
8379 return fmt.Errorf("http2: invalid Transfer-Encoding request header: %q", vv)
8380 }
8381 if vv := req.Header["Connection"]; len(vv) > 0 && (len(vv) > 1 || vv[0] != "" && !http2asciiEqualFold(vv[0], "close") && !http2asciiEqualFold(vv[0], "keep-alive")) {
8382 return fmt.Errorf("http2: invalid Connection request header: %q", vv)
8383 }
8384 return nil
8385 }
8386
8387
8388
8389
8390 func http2actualContentLength(req *Request) int64 {
8391 if req.Body == nil || req.Body == NoBody {
8392 return 0
8393 }
8394 if req.ContentLength != 0 {
8395 return req.ContentLength
8396 }
8397 return -1
8398 }
8399
8400 func (cc *http2ClientConn) decrStreamReservations() {
8401 cc.mu.Lock()
8402 defer cc.mu.Unlock()
8403 cc.decrStreamReservationsLocked()
8404 }
8405
8406 func (cc *http2ClientConn) decrStreamReservationsLocked() {
8407 if cc.streamsReserved > 0 {
8408 cc.streamsReserved--
8409 }
8410 }
8411
8412 func (cc *http2ClientConn) RoundTrip(req *Request) (*Response, error) {
8413 return cc.roundTrip(req, nil)
8414 }
8415
8416 func (cc *http2ClientConn) roundTrip(req *Request, streamf func(*http2clientStream)) (*Response, error) {
8417 ctx := req.Context()
8418 cs := &http2clientStream{
8419 cc: cc,
8420 ctx: ctx,
8421 reqCancel: req.Cancel,
8422 isHead: req.Method == "HEAD",
8423 reqBody: req.Body,
8424 reqBodyContentLength: http2actualContentLength(req),
8425 trace: httptrace.ContextClientTrace(ctx),
8426 peerClosed: make(chan struct{}),
8427 abort: make(chan struct{}),
8428 respHeaderRecv: make(chan struct{}),
8429 donec: make(chan struct{}),
8430 }
8431
8432
8433 if !cc.t.disableCompression() &&
8434 req.Header.Get("Accept-Encoding") == "" &&
8435 req.Header.Get("Range") == "" &&
8436 !cs.isHead {
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449 cs.requestedGzip = true
8450 }
8451
8452 go cs.doRequest(req, streamf)
8453
8454 waitDone := func() error {
8455 select {
8456 case <-cs.donec:
8457 return nil
8458 case <-ctx.Done():
8459 return ctx.Err()
8460 case <-cs.reqCancel:
8461 return http2errRequestCanceled
8462 }
8463 }
8464
8465 handleResponseHeaders := func() (*Response, error) {
8466 res := cs.res
8467 if res.StatusCode > 299 {
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477 cs.abortRequestBodyWrite()
8478 }
8479 res.Request = req
8480 res.TLS = cc.tlsState
8481 if res.Body == http2noBody && http2actualContentLength(req) == 0 {
8482
8483
8484
8485 if err := waitDone(); err != nil {
8486 return nil, err
8487 }
8488 }
8489 return res, nil
8490 }
8491
8492 cancelRequest := func(cs *http2clientStream, err error) error {
8493 cs.cc.mu.Lock()
8494 bodyClosed := cs.reqBodyClosed
8495 cs.cc.mu.Unlock()
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509 if bodyClosed != nil {
8510 <-bodyClosed
8511 }
8512 return err
8513 }
8514
8515 for {
8516 select {
8517 case <-cs.respHeaderRecv:
8518 return handleResponseHeaders()
8519 case <-cs.abort:
8520 select {
8521 case <-cs.respHeaderRecv:
8522
8523
8524
8525
8526 return handleResponseHeaders()
8527 default:
8528 waitDone()
8529 return nil, cs.abortErr
8530 }
8531 case <-ctx.Done():
8532 err := ctx.Err()
8533 cs.abortStream(err)
8534 return nil, cancelRequest(cs, err)
8535 case <-cs.reqCancel:
8536 cs.abortStream(http2errRequestCanceled)
8537 return nil, cancelRequest(cs, http2errRequestCanceled)
8538 }
8539 }
8540 }
8541
8542
8543
8544
8545 func (cs *http2clientStream) doRequest(req *Request, streamf func(*http2clientStream)) {
8546 cs.cc.t.markNewGoroutine()
8547 err := cs.writeRequest(req, streamf)
8548 cs.cleanupWriteRequest(err)
8549 }
8550
8551
8552
8553
8554
8555
8556
8557
8558 func (cs *http2clientStream) writeRequest(req *Request, streamf func(*http2clientStream)) (err error) {
8559 cc := cs.cc
8560 ctx := cs.ctx
8561
8562 if err := http2checkConnHeaders(req); err != nil {
8563 return err
8564 }
8565
8566
8567
8568
8569 if cc.reqHeaderMu == nil {
8570 panic("RoundTrip on uninitialized ClientConn")
8571 }
8572 select {
8573 case cc.reqHeaderMu <- struct{}{}:
8574 case <-cs.reqCancel:
8575 return http2errRequestCanceled
8576 case <-ctx.Done():
8577 return ctx.Err()
8578 }
8579
8580 cc.mu.Lock()
8581 if cc.idleTimer != nil {
8582 cc.idleTimer.Stop()
8583 }
8584 cc.decrStreamReservationsLocked()
8585 if err := cc.awaitOpenSlotForStreamLocked(cs); err != nil {
8586 cc.mu.Unlock()
8587 <-cc.reqHeaderMu
8588 return err
8589 }
8590 cc.addStreamLocked(cs)
8591 if http2isConnectionCloseRequest(req) {
8592 cc.doNotReuse = true
8593 }
8594 cc.mu.Unlock()
8595
8596 if streamf != nil {
8597 streamf(cs)
8598 }
8599
8600 continueTimeout := cc.t.expectContinueTimeout()
8601 if continueTimeout != 0 {
8602 if !httpguts.HeaderValuesContainsToken(req.Header["Expect"], "100-continue") {
8603 continueTimeout = 0
8604 } else {
8605 cs.on100 = make(chan struct{}, 1)
8606 }
8607 }
8608
8609
8610
8611
8612
8613 err = cs.encodeAndWriteHeaders(req)
8614 <-cc.reqHeaderMu
8615 if err != nil {
8616 return err
8617 }
8618
8619 hasBody := cs.reqBodyContentLength != 0
8620 if !hasBody {
8621 cs.sentEndStream = true
8622 } else {
8623 if continueTimeout != 0 {
8624 http2traceWait100Continue(cs.trace)
8625 timer := time.NewTimer(continueTimeout)
8626 select {
8627 case <-timer.C:
8628 err = nil
8629 case <-cs.on100:
8630 err = nil
8631 case <-cs.abort:
8632 err = cs.abortErr
8633 case <-ctx.Done():
8634 err = ctx.Err()
8635 case <-cs.reqCancel:
8636 err = http2errRequestCanceled
8637 }
8638 timer.Stop()
8639 if err != nil {
8640 http2traceWroteRequest(cs.trace, err)
8641 return err
8642 }
8643 }
8644
8645 if err = cs.writeRequestBody(req); err != nil {
8646 if err != http2errStopReqBodyWrite {
8647 http2traceWroteRequest(cs.trace, err)
8648 return err
8649 }
8650 } else {
8651 cs.sentEndStream = true
8652 }
8653 }
8654
8655 http2traceWroteRequest(cs.trace, err)
8656
8657 var respHeaderTimer <-chan time.Time
8658 var respHeaderRecv chan struct{}
8659 if d := cc.responseHeaderTimeout(); d != 0 {
8660 timer := cc.t.newTimer(d)
8661 defer timer.Stop()
8662 respHeaderTimer = timer.C()
8663 respHeaderRecv = cs.respHeaderRecv
8664 }
8665
8666
8667
8668 for {
8669 select {
8670 case <-cs.peerClosed:
8671 return nil
8672 case <-respHeaderTimer:
8673 return http2errTimeout
8674 case <-respHeaderRecv:
8675 respHeaderRecv = nil
8676 respHeaderTimer = nil
8677 case <-cs.abort:
8678 return cs.abortErr
8679 case <-ctx.Done():
8680 return ctx.Err()
8681 case <-cs.reqCancel:
8682 return http2errRequestCanceled
8683 }
8684 }
8685 }
8686
8687 func (cs *http2clientStream) encodeAndWriteHeaders(req *Request) error {
8688 cc := cs.cc
8689 ctx := cs.ctx
8690
8691 cc.wmu.Lock()
8692 defer cc.wmu.Unlock()
8693
8694
8695 select {
8696 case <-cs.abort:
8697 return cs.abortErr
8698 case <-ctx.Done():
8699 return ctx.Err()
8700 case <-cs.reqCancel:
8701 return http2errRequestCanceled
8702 default:
8703 }
8704
8705
8706
8707
8708
8709
8710 trailers, err := http2commaSeparatedTrailers(req)
8711 if err != nil {
8712 return err
8713 }
8714 hasTrailers := trailers != ""
8715 contentLen := http2actualContentLength(req)
8716 hasBody := contentLen != 0
8717 hdrs, err := cc.encodeHeaders(req, cs.requestedGzip, trailers, contentLen)
8718 if err != nil {
8719 return err
8720 }
8721
8722
8723 endStream := !hasBody && !hasTrailers
8724 cs.sentHeaders = true
8725 err = cc.writeHeaders(cs.ID, endStream, int(cc.maxFrameSize), hdrs)
8726 http2traceWroteHeaders(cs.trace)
8727 return err
8728 }
8729
8730
8731
8732
8733
8734 func (cs *http2clientStream) cleanupWriteRequest(err error) {
8735 cc := cs.cc
8736
8737 if cs.ID == 0 {
8738
8739 cc.decrStreamReservations()
8740 }
8741
8742
8743
8744
8745
8746 cc.mu.Lock()
8747 mustCloseBody := false
8748 if cs.reqBody != nil && cs.reqBodyClosed == nil {
8749 mustCloseBody = true
8750 cs.reqBodyClosed = make(chan struct{})
8751 }
8752 bodyClosed := cs.reqBodyClosed
8753 cc.mu.Unlock()
8754 if mustCloseBody {
8755 cs.reqBody.Close()
8756 close(bodyClosed)
8757 }
8758 if bodyClosed != nil {
8759 <-bodyClosed
8760 }
8761
8762 if err != nil && cs.sentEndStream {
8763
8764
8765
8766 select {
8767 case <-cs.peerClosed:
8768 err = nil
8769 default:
8770 }
8771 }
8772 if err != nil {
8773 cs.abortStream(err)
8774 if cs.sentHeaders {
8775 if se, ok := err.(http2StreamError); ok {
8776 if se.Cause != http2errFromPeer {
8777 cc.writeStreamReset(cs.ID, se.Code, err)
8778 }
8779 } else {
8780 cc.writeStreamReset(cs.ID, http2ErrCodeCancel, err)
8781 }
8782 }
8783 cs.bufPipe.CloseWithError(err)
8784 } else {
8785 if cs.sentHeaders && !cs.sentEndStream {
8786 cc.writeStreamReset(cs.ID, http2ErrCodeNo, nil)
8787 }
8788 cs.bufPipe.CloseWithError(http2errRequestCanceled)
8789 }
8790 if cs.ID != 0 {
8791 cc.forgetStreamID(cs.ID)
8792 }
8793
8794 cc.wmu.Lock()
8795 werr := cc.werr
8796 cc.wmu.Unlock()
8797 if werr != nil {
8798 cc.Close()
8799 }
8800
8801 close(cs.donec)
8802 }
8803
8804
8805
8806 func (cc *http2ClientConn) awaitOpenSlotForStreamLocked(cs *http2clientStream) error {
8807 for {
8808 cc.lastActive = time.Now()
8809 if cc.closed || !cc.canTakeNewRequestLocked() {
8810 return http2errClientConnUnusable
8811 }
8812 cc.lastIdle = time.Time{}
8813 if int64(len(cc.streams)) < int64(cc.maxConcurrentStreams) {
8814 return nil
8815 }
8816 cc.pendingRequests++
8817 cc.cond.Wait()
8818 cc.pendingRequests--
8819 select {
8820 case <-cs.abort:
8821 return cs.abortErr
8822 default:
8823 }
8824 }
8825 }
8826
8827
8828 func (cc *http2ClientConn) writeHeaders(streamID uint32, endStream bool, maxFrameSize int, hdrs []byte) error {
8829 first := true
8830 for len(hdrs) > 0 && cc.werr == nil {
8831 chunk := hdrs
8832 if len(chunk) > maxFrameSize {
8833 chunk = chunk[:maxFrameSize]
8834 }
8835 hdrs = hdrs[len(chunk):]
8836 endHeaders := len(hdrs) == 0
8837 if first {
8838 cc.fr.WriteHeaders(http2HeadersFrameParam{
8839 StreamID: streamID,
8840 BlockFragment: chunk,
8841 EndStream: endStream,
8842 EndHeaders: endHeaders,
8843 })
8844 first = false
8845 } else {
8846 cc.fr.WriteContinuation(streamID, endHeaders, chunk)
8847 }
8848 }
8849 cc.bw.Flush()
8850 return cc.werr
8851 }
8852
8853
8854 var (
8855
8856 http2errStopReqBodyWrite = errors.New("http2: aborting request body write")
8857
8858
8859 http2errStopReqBodyWriteAndCancel = errors.New("http2: canceling request")
8860
8861 http2errReqBodyTooLong = errors.New("http2: request body larger than specified content length")
8862 )
8863
8864
8865
8866
8867
8868
8869 func (cs *http2clientStream) frameScratchBufferLen(maxFrameSize int) int {
8870 const max = 512 << 10
8871 n := int64(maxFrameSize)
8872 if n > max {
8873 n = max
8874 }
8875 if cl := cs.reqBodyContentLength; cl != -1 && cl+1 < n {
8876
8877
8878
8879
8880 n = cl + 1
8881 }
8882 if n < 1 {
8883 return 1
8884 }
8885 return int(n)
8886 }
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896 var http2bufPools [7]sync.Pool
8897
8898 func http2bufPoolIndex(size int) int {
8899 if size <= 16384 {
8900 return 0
8901 }
8902 size -= 1
8903 bits := bits.Len(uint(size))
8904 index := bits - 14
8905 if index >= len(http2bufPools) {
8906 return len(http2bufPools) - 1
8907 }
8908 return index
8909 }
8910
8911 func (cs *http2clientStream) writeRequestBody(req *Request) (err error) {
8912 cc := cs.cc
8913 body := cs.reqBody
8914 sentEnd := false
8915
8916 hasTrailers := req.Trailer != nil
8917 remainLen := cs.reqBodyContentLength
8918 hasContentLen := remainLen != -1
8919
8920 cc.mu.Lock()
8921 maxFrameSize := int(cc.maxFrameSize)
8922 cc.mu.Unlock()
8923
8924
8925 scratchLen := cs.frameScratchBufferLen(maxFrameSize)
8926 var buf []byte
8927 index := http2bufPoolIndex(scratchLen)
8928 if bp, ok := http2bufPools[index].Get().(*[]byte); ok && len(*bp) >= scratchLen {
8929 defer http2bufPools[index].Put(bp)
8930 buf = *bp
8931 } else {
8932 buf = make([]byte, scratchLen)
8933 defer http2bufPools[index].Put(&buf)
8934 }
8935
8936 var sawEOF bool
8937 for !sawEOF {
8938 n, err := body.Read(buf)
8939 if hasContentLen {
8940 remainLen -= int64(n)
8941 if remainLen == 0 && err == nil {
8942
8943
8944
8945
8946
8947
8948
8949 var scratch [1]byte
8950 var n1 int
8951 n1, err = body.Read(scratch[:])
8952 remainLen -= int64(n1)
8953 }
8954 if remainLen < 0 {
8955 err = http2errReqBodyTooLong
8956 return err
8957 }
8958 }
8959 if err != nil {
8960 cc.mu.Lock()
8961 bodyClosed := cs.reqBodyClosed != nil
8962 cc.mu.Unlock()
8963 switch {
8964 case bodyClosed:
8965 return http2errStopReqBodyWrite
8966 case err == io.EOF:
8967 sawEOF = true
8968 err = nil
8969 default:
8970 return err
8971 }
8972 }
8973
8974 remain := buf[:n]
8975 for len(remain) > 0 && err == nil {
8976 var allowed int32
8977 allowed, err = cs.awaitFlowControl(len(remain))
8978 if err != nil {
8979 return err
8980 }
8981 cc.wmu.Lock()
8982 data := remain[:allowed]
8983 remain = remain[allowed:]
8984 sentEnd = sawEOF && len(remain) == 0 && !hasTrailers
8985 err = cc.fr.WriteData(cs.ID, sentEnd, data)
8986 if err == nil {
8987
8988
8989
8990
8991
8992
8993 err = cc.bw.Flush()
8994 }
8995 cc.wmu.Unlock()
8996 }
8997 if err != nil {
8998 return err
8999 }
9000 }
9001
9002 if sentEnd {
9003
9004
9005
9006 return nil
9007 }
9008
9009
9010
9011
9012 cc.mu.Lock()
9013 trailer := req.Trailer
9014 err = cs.abortErr
9015 cc.mu.Unlock()
9016 if err != nil {
9017 return err
9018 }
9019
9020 cc.wmu.Lock()
9021 defer cc.wmu.Unlock()
9022 var trls []byte
9023 if len(trailer) > 0 {
9024 trls, err = cc.encodeTrailers(trailer)
9025 if err != nil {
9026 return err
9027 }
9028 }
9029
9030
9031
9032 if len(trls) > 0 {
9033 err = cc.writeHeaders(cs.ID, true, maxFrameSize, trls)
9034 } else {
9035 err = cc.fr.WriteData(cs.ID, true, nil)
9036 }
9037 if ferr := cc.bw.Flush(); ferr != nil && err == nil {
9038 err = ferr
9039 }
9040 return err
9041 }
9042
9043
9044
9045
9046
9047 func (cs *http2clientStream) awaitFlowControl(maxBytes int) (taken int32, err error) {
9048 cc := cs.cc
9049 ctx := cs.ctx
9050 cc.mu.Lock()
9051 defer cc.mu.Unlock()
9052 for {
9053 if cc.closed {
9054 return 0, http2errClientConnClosed
9055 }
9056 if cs.reqBodyClosed != nil {
9057 return 0, http2errStopReqBodyWrite
9058 }
9059 select {
9060 case <-cs.abort:
9061 return 0, cs.abortErr
9062 case <-ctx.Done():
9063 return 0, ctx.Err()
9064 case <-cs.reqCancel:
9065 return 0, http2errRequestCanceled
9066 default:
9067 }
9068 if a := cs.flow.available(); a > 0 {
9069 take := a
9070 if int(take) > maxBytes {
9071
9072 take = int32(maxBytes)
9073 }
9074 if take > int32(cc.maxFrameSize) {
9075 take = int32(cc.maxFrameSize)
9076 }
9077 cs.flow.take(take)
9078 return take, nil
9079 }
9080 cc.cond.Wait()
9081 }
9082 }
9083
9084 func http2validateHeaders(hdrs Header) string {
9085 for k, vv := range hdrs {
9086 if !httpguts.ValidHeaderFieldName(k) {
9087 return fmt.Sprintf("name %q", k)
9088 }
9089 for _, v := range vv {
9090 if !httpguts.ValidHeaderFieldValue(v) {
9091
9092
9093 return fmt.Sprintf("value for header %q", k)
9094 }
9095 }
9096 }
9097 return ""
9098 }
9099
9100 var http2errNilRequestURL = errors.New("http2: Request.URI is nil")
9101
9102
9103 func (cc *http2ClientConn) encodeHeaders(req *Request, addGzipHeader bool, trailers string, contentLength int64) ([]byte, error) {
9104 cc.hbuf.Reset()
9105 if req.URL == nil {
9106 return nil, http2errNilRequestURL
9107 }
9108
9109 host := req.Host
9110 if host == "" {
9111 host = req.URL.Host
9112 }
9113 host, err := httpguts.PunycodeHostPort(host)
9114 if err != nil {
9115 return nil, err
9116 }
9117 if !httpguts.ValidHostHeader(host) {
9118 return nil, errors.New("http2: invalid Host header")
9119 }
9120
9121 var path string
9122 if req.Method != "CONNECT" {
9123 path = req.URL.RequestURI()
9124 if !http2validPseudoPath(path) {
9125 orig := path
9126 path = strings.TrimPrefix(path, req.URL.Scheme+"://"+host)
9127 if !http2validPseudoPath(path) {
9128 if req.URL.Opaque != "" {
9129 return nil, fmt.Errorf("invalid request :path %q from URL.Opaque = %q", orig, req.URL.Opaque)
9130 } else {
9131 return nil, fmt.Errorf("invalid request :path %q", orig)
9132 }
9133 }
9134 }
9135 }
9136
9137
9138
9139
9140 if err := http2validateHeaders(req.Header); err != "" {
9141 return nil, fmt.Errorf("invalid HTTP header %s", err)
9142 }
9143 if err := http2validateHeaders(req.Trailer); err != "" {
9144 return nil, fmt.Errorf("invalid HTTP trailer %s", err)
9145 }
9146
9147 enumerateHeaders := func(f func(name, value string)) {
9148
9149
9150
9151
9152
9153 f(":authority", host)
9154 m := req.Method
9155 if m == "" {
9156 m = MethodGet
9157 }
9158 f(":method", m)
9159 if req.Method != "CONNECT" {
9160 f(":path", path)
9161 f(":scheme", req.URL.Scheme)
9162 }
9163 if trailers != "" {
9164 f("trailer", trailers)
9165 }
9166
9167 var didUA bool
9168 for k, vv := range req.Header {
9169 if http2asciiEqualFold(k, "host") || http2asciiEqualFold(k, "content-length") {
9170
9171
9172 continue
9173 } else if http2asciiEqualFold(k, "connection") ||
9174 http2asciiEqualFold(k, "proxy-connection") ||
9175 http2asciiEqualFold(k, "transfer-encoding") ||
9176 http2asciiEqualFold(k, "upgrade") ||
9177 http2asciiEqualFold(k, "keep-alive") {
9178
9179
9180
9181
9182 continue
9183 } else if http2asciiEqualFold(k, "user-agent") {
9184
9185
9186
9187
9188 didUA = true
9189 if len(vv) < 1 {
9190 continue
9191 }
9192 vv = vv[:1]
9193 if vv[0] == "" {
9194 continue
9195 }
9196 } else if http2asciiEqualFold(k, "cookie") {
9197
9198
9199
9200 for _, v := range vv {
9201 for {
9202 p := strings.IndexByte(v, ';')
9203 if p < 0 {
9204 break
9205 }
9206 f("cookie", v[:p])
9207 p++
9208
9209 for p+1 <= len(v) && v[p] == ' ' {
9210 p++
9211 }
9212 v = v[p:]
9213 }
9214 if len(v) > 0 {
9215 f("cookie", v)
9216 }
9217 }
9218 continue
9219 }
9220
9221 for _, v := range vv {
9222 f(k, v)
9223 }
9224 }
9225 if http2shouldSendReqContentLength(req.Method, contentLength) {
9226 f("content-length", strconv.FormatInt(contentLength, 10))
9227 }
9228 if addGzipHeader {
9229 f("accept-encoding", "gzip")
9230 }
9231 if !didUA {
9232 f("user-agent", http2defaultUserAgent)
9233 }
9234 }
9235
9236
9237
9238
9239
9240 hlSize := uint64(0)
9241 enumerateHeaders(func(name, value string) {
9242 hf := hpack.HeaderField{Name: name, Value: value}
9243 hlSize += uint64(hf.Size())
9244 })
9245
9246 if hlSize > cc.peerMaxHeaderListSize {
9247 return nil, http2errRequestHeaderListSize
9248 }
9249
9250 trace := httptrace.ContextClientTrace(req.Context())
9251 traceHeaders := http2traceHasWroteHeaderField(trace)
9252
9253
9254 enumerateHeaders(func(name, value string) {
9255 name, ascii := http2lowerHeader(name)
9256 if !ascii {
9257
9258
9259 return
9260 }
9261 cc.writeHeader(name, value)
9262 if traceHeaders {
9263 http2traceWroteHeaderField(trace, name, value)
9264 }
9265 })
9266
9267 return cc.hbuf.Bytes(), nil
9268 }
9269
9270
9271
9272
9273
9274
9275 func http2shouldSendReqContentLength(method string, contentLength int64) bool {
9276 if contentLength > 0 {
9277 return true
9278 }
9279 if contentLength < 0 {
9280 return false
9281 }
9282
9283
9284 switch method {
9285 case "POST", "PUT", "PATCH":
9286 return true
9287 default:
9288 return false
9289 }
9290 }
9291
9292
9293 func (cc *http2ClientConn) encodeTrailers(trailer Header) ([]byte, error) {
9294 cc.hbuf.Reset()
9295
9296 hlSize := uint64(0)
9297 for k, vv := range trailer {
9298 for _, v := range vv {
9299 hf := hpack.HeaderField{Name: k, Value: v}
9300 hlSize += uint64(hf.Size())
9301 }
9302 }
9303 if hlSize > cc.peerMaxHeaderListSize {
9304 return nil, http2errRequestHeaderListSize
9305 }
9306
9307 for k, vv := range trailer {
9308 lowKey, ascii := http2lowerHeader(k)
9309 if !ascii {
9310
9311
9312 continue
9313 }
9314
9315
9316 for _, v := range vv {
9317 cc.writeHeader(lowKey, v)
9318 }
9319 }
9320 return cc.hbuf.Bytes(), nil
9321 }
9322
9323 func (cc *http2ClientConn) writeHeader(name, value string) {
9324 if http2VerboseLogs {
9325 log.Printf("http2: Transport encoding header %q = %q", name, value)
9326 }
9327 cc.henc.WriteField(hpack.HeaderField{Name: name, Value: value})
9328 }
9329
9330 type http2resAndError struct {
9331 _ http2incomparable
9332 res *Response
9333 err error
9334 }
9335
9336
9337 func (cc *http2ClientConn) addStreamLocked(cs *http2clientStream) {
9338 cs.flow.add(int32(cc.initialWindowSize))
9339 cs.flow.setConnFlow(&cc.flow)
9340 cs.inflow.init(http2transportDefaultStreamFlow)
9341 cs.ID = cc.nextStreamID
9342 cc.nextStreamID += 2
9343 cc.streams[cs.ID] = cs
9344 if cs.ID == 0 {
9345 panic("assigned stream ID 0")
9346 }
9347 }
9348
9349 func (cc *http2ClientConn) forgetStreamID(id uint32) {
9350 cc.mu.Lock()
9351 slen := len(cc.streams)
9352 delete(cc.streams, id)
9353 if len(cc.streams) != slen-1 {
9354 panic("forgetting unknown stream id")
9355 }
9356 cc.lastActive = time.Now()
9357 if len(cc.streams) == 0 && cc.idleTimer != nil {
9358 cc.idleTimer.Reset(cc.idleTimeout)
9359 cc.lastIdle = time.Now()
9360 }
9361
9362
9363 cc.cond.Broadcast()
9364
9365 closeOnIdle := cc.singleUse || cc.doNotReuse || cc.t.disableKeepAlives() || cc.goAway != nil
9366 if closeOnIdle && cc.streamsReserved == 0 && len(cc.streams) == 0 {
9367 if http2VerboseLogs {
9368 cc.vlogf("http2: Transport closing idle conn %p (forSingleUse=%v, maxStream=%v)", cc, cc.singleUse, cc.nextStreamID-2)
9369 }
9370 cc.closed = true
9371 defer cc.closeConn()
9372 }
9373
9374 cc.mu.Unlock()
9375 }
9376
9377
9378 type http2clientConnReadLoop struct {
9379 _ http2incomparable
9380 cc *http2ClientConn
9381 }
9382
9383
9384 func (cc *http2ClientConn) readLoop() {
9385 cc.t.markNewGoroutine()
9386 rl := &http2clientConnReadLoop{cc: cc}
9387 defer rl.cleanup()
9388 cc.readerErr = rl.run()
9389 if ce, ok := cc.readerErr.(http2ConnectionError); ok {
9390 cc.wmu.Lock()
9391 cc.fr.WriteGoAway(0, http2ErrCode(ce), nil)
9392 cc.wmu.Unlock()
9393 }
9394 }
9395
9396
9397
9398 type http2GoAwayError struct {
9399 LastStreamID uint32
9400 ErrCode http2ErrCode
9401 DebugData string
9402 }
9403
9404 func (e http2GoAwayError) Error() string {
9405 return fmt.Sprintf("http2: server sent GOAWAY and closed the connection; LastStreamID=%v, ErrCode=%v, debug=%q",
9406 e.LastStreamID, e.ErrCode, e.DebugData)
9407 }
9408
9409 func http2isEOFOrNetReadError(err error) bool {
9410 if err == io.EOF {
9411 return true
9412 }
9413 ne, ok := err.(*net.OpError)
9414 return ok && ne.Op == "read"
9415 }
9416
9417 func (rl *http2clientConnReadLoop) cleanup() {
9418 cc := rl.cc
9419 cc.t.connPool().MarkDead(cc)
9420 defer cc.closeConn()
9421 defer close(cc.readerDone)
9422
9423 if cc.idleTimer != nil {
9424 cc.idleTimer.Stop()
9425 }
9426
9427
9428
9429
9430 err := cc.readerErr
9431 cc.mu.Lock()
9432 if cc.goAway != nil && http2isEOFOrNetReadError(err) {
9433 err = http2GoAwayError{
9434 LastStreamID: cc.goAway.LastStreamID,
9435 ErrCode: cc.goAway.ErrCode,
9436 DebugData: cc.goAwayDebug,
9437 }
9438 } else if err == io.EOF {
9439 err = io.ErrUnexpectedEOF
9440 }
9441 cc.closed = true
9442
9443 for _, cs := range cc.streams {
9444 select {
9445 case <-cs.peerClosed:
9446
9447
9448 default:
9449 cs.abortStreamLocked(err)
9450 }
9451 }
9452 cc.cond.Broadcast()
9453 cc.mu.Unlock()
9454 }
9455
9456
9457
9458 func (cc *http2ClientConn) countReadFrameError(err error) {
9459 f := cc.t.CountError
9460 if f == nil || err == nil {
9461 return
9462 }
9463 if ce, ok := err.(http2ConnectionError); ok {
9464 errCode := http2ErrCode(ce)
9465 f(fmt.Sprintf("read_frame_conn_error_%s", errCode.stringToken()))
9466 return
9467 }
9468 if errors.Is(err, io.EOF) {
9469 f("read_frame_eof")
9470 return
9471 }
9472 if errors.Is(err, io.ErrUnexpectedEOF) {
9473 f("read_frame_unexpected_eof")
9474 return
9475 }
9476 if errors.Is(err, http2ErrFrameTooLarge) {
9477 f("read_frame_too_large")
9478 return
9479 }
9480 f("read_frame_other")
9481 }
9482
9483 func (rl *http2clientConnReadLoop) run() error {
9484 cc := rl.cc
9485 gotSettings := false
9486 readIdleTimeout := cc.t.ReadIdleTimeout
9487 var t http2timer
9488 if readIdleTimeout != 0 {
9489 t = cc.t.afterFunc(readIdleTimeout, cc.healthCheck)
9490 }
9491 for {
9492 f, err := cc.fr.ReadFrame()
9493 if t != nil {
9494 t.Reset(readIdleTimeout)
9495 }
9496 if err != nil {
9497 cc.vlogf("http2: Transport readFrame error on conn %p: (%T) %v", cc, err, err)
9498 }
9499 if se, ok := err.(http2StreamError); ok {
9500 if cs := rl.streamByID(se.StreamID); cs != nil {
9501 if se.Cause == nil {
9502 se.Cause = cc.fr.errDetail
9503 }
9504 rl.endStreamError(cs, se)
9505 }
9506 continue
9507 } else if err != nil {
9508 cc.countReadFrameError(err)
9509 return err
9510 }
9511 if http2VerboseLogs {
9512 cc.vlogf("http2: Transport received %s", http2summarizeFrame(f))
9513 }
9514 if !gotSettings {
9515 if _, ok := f.(*http2SettingsFrame); !ok {
9516 cc.logf("protocol error: received %T before a SETTINGS frame", f)
9517 return http2ConnectionError(http2ErrCodeProtocol)
9518 }
9519 gotSettings = true
9520 }
9521
9522 switch f := f.(type) {
9523 case *http2MetaHeadersFrame:
9524 err = rl.processHeaders(f)
9525 case *http2DataFrame:
9526 err = rl.processData(f)
9527 case *http2GoAwayFrame:
9528 err = rl.processGoAway(f)
9529 case *http2RSTStreamFrame:
9530 err = rl.processResetStream(f)
9531 case *http2SettingsFrame:
9532 err = rl.processSettings(f)
9533 case *http2PushPromiseFrame:
9534 err = rl.processPushPromise(f)
9535 case *http2WindowUpdateFrame:
9536 err = rl.processWindowUpdate(f)
9537 case *http2PingFrame:
9538 err = rl.processPing(f)
9539 default:
9540 cc.logf("Transport: unhandled response frame type %T", f)
9541 }
9542 if err != nil {
9543 if http2VerboseLogs {
9544 cc.vlogf("http2: Transport conn %p received error from processing frame %v: %v", cc, http2summarizeFrame(f), err)
9545 }
9546 return err
9547 }
9548 }
9549 }
9550
9551 func (rl *http2clientConnReadLoop) processHeaders(f *http2MetaHeadersFrame) error {
9552 cs := rl.streamByID(f.StreamID)
9553 if cs == nil {
9554
9555
9556
9557 return nil
9558 }
9559 if cs.readClosed {
9560 rl.endStreamError(cs, http2StreamError{
9561 StreamID: f.StreamID,
9562 Code: http2ErrCodeProtocol,
9563 Cause: errors.New("protocol error: headers after END_STREAM"),
9564 })
9565 return nil
9566 }
9567 if !cs.firstByte {
9568 if cs.trace != nil {
9569
9570
9571
9572
9573 http2traceFirstResponseByte(cs.trace)
9574 }
9575 cs.firstByte = true
9576 }
9577 if !cs.pastHeaders {
9578 cs.pastHeaders = true
9579 } else {
9580 return rl.processTrailers(cs, f)
9581 }
9582
9583 res, err := rl.handleResponse(cs, f)
9584 if err != nil {
9585 if _, ok := err.(http2ConnectionError); ok {
9586 return err
9587 }
9588
9589 rl.endStreamError(cs, http2StreamError{
9590 StreamID: f.StreamID,
9591 Code: http2ErrCodeProtocol,
9592 Cause: err,
9593 })
9594 return nil
9595 }
9596 if res == nil {
9597
9598 return nil
9599 }
9600 cs.resTrailer = &res.Trailer
9601 cs.res = res
9602 close(cs.respHeaderRecv)
9603 if f.StreamEnded() {
9604 rl.endStream(cs)
9605 }
9606 return nil
9607 }
9608
9609
9610
9611
9612
9613
9614
9615 func (rl *http2clientConnReadLoop) handleResponse(cs *http2clientStream, f *http2MetaHeadersFrame) (*Response, error) {
9616 if f.Truncated {
9617 return nil, http2errResponseHeaderListSize
9618 }
9619
9620 status := f.PseudoValue("status")
9621 if status == "" {
9622 return nil, errors.New("malformed response from server: missing status pseudo header")
9623 }
9624 statusCode, err := strconv.Atoi(status)
9625 if err != nil {
9626 return nil, errors.New("malformed response from server: malformed non-numeric status pseudo header")
9627 }
9628
9629 regularFields := f.RegularFields()
9630 strs := make([]string, len(regularFields))
9631 header := make(Header, len(regularFields))
9632 res := &Response{
9633 Proto: "HTTP/2.0",
9634 ProtoMajor: 2,
9635 Header: header,
9636 StatusCode: statusCode,
9637 Status: status + " " + StatusText(statusCode),
9638 }
9639 for _, hf := range regularFields {
9640 key := http2canonicalHeader(hf.Name)
9641 if key == "Trailer" {
9642 t := res.Trailer
9643 if t == nil {
9644 t = make(Header)
9645 res.Trailer = t
9646 }
9647 http2foreachHeaderElement(hf.Value, func(v string) {
9648 t[http2canonicalHeader(v)] = nil
9649 })
9650 } else {
9651 vv := header[key]
9652 if vv == nil && len(strs) > 0 {
9653
9654
9655
9656
9657 vv, strs = strs[:1:1], strs[1:]
9658 vv[0] = hf.Value
9659 header[key] = vv
9660 } else {
9661 header[key] = append(vv, hf.Value)
9662 }
9663 }
9664 }
9665
9666 if statusCode >= 100 && statusCode <= 199 {
9667 if f.StreamEnded() {
9668 return nil, errors.New("1xx informational response with END_STREAM flag")
9669 }
9670 cs.num1xx++
9671 const max1xxResponses = 5
9672 if cs.num1xx > max1xxResponses {
9673 return nil, errors.New("http2: too many 1xx informational responses")
9674 }
9675 if fn := cs.get1xxTraceFunc(); fn != nil {
9676 if err := fn(statusCode, textproto.MIMEHeader(header)); err != nil {
9677 return nil, err
9678 }
9679 }
9680 if statusCode == 100 {
9681 http2traceGot100Continue(cs.trace)
9682 select {
9683 case cs.on100 <- struct{}{}:
9684 default:
9685 }
9686 }
9687 cs.pastHeaders = false
9688 return nil, nil
9689 }
9690
9691 res.ContentLength = -1
9692 if clens := res.Header["Content-Length"]; len(clens) == 1 {
9693 if cl, err := strconv.ParseUint(clens[0], 10, 63); err == nil {
9694 res.ContentLength = int64(cl)
9695 } else {
9696
9697
9698 }
9699 } else if len(clens) > 1 {
9700
9701
9702 } else if f.StreamEnded() && !cs.isHead {
9703 res.ContentLength = 0
9704 }
9705
9706 if cs.isHead {
9707 res.Body = http2noBody
9708 return res, nil
9709 }
9710
9711 if f.StreamEnded() {
9712 if res.ContentLength > 0 {
9713 res.Body = http2missingBody{}
9714 } else {
9715 res.Body = http2noBody
9716 }
9717 return res, nil
9718 }
9719
9720 cs.bufPipe.setBuffer(&http2dataBuffer{expected: res.ContentLength})
9721 cs.bytesRemain = res.ContentLength
9722 res.Body = http2transportResponseBody{cs}
9723
9724 if cs.requestedGzip && http2asciiEqualFold(res.Header.Get("Content-Encoding"), "gzip") {
9725 res.Header.Del("Content-Encoding")
9726 res.Header.Del("Content-Length")
9727 res.ContentLength = -1
9728 res.Body = &http2gzipReader{body: res.Body}
9729 res.Uncompressed = true
9730 }
9731 return res, nil
9732 }
9733
9734 func (rl *http2clientConnReadLoop) processTrailers(cs *http2clientStream, f *http2MetaHeadersFrame) error {
9735 if cs.pastTrailers {
9736
9737 return http2ConnectionError(http2ErrCodeProtocol)
9738 }
9739 cs.pastTrailers = true
9740 if !f.StreamEnded() {
9741
9742
9743 return http2ConnectionError(http2ErrCodeProtocol)
9744 }
9745 if len(f.PseudoFields()) > 0 {
9746
9747
9748 return http2ConnectionError(http2ErrCodeProtocol)
9749 }
9750
9751 trailer := make(Header)
9752 for _, hf := range f.RegularFields() {
9753 key := http2canonicalHeader(hf.Name)
9754 trailer[key] = append(trailer[key], hf.Value)
9755 }
9756 cs.trailer = trailer
9757
9758 rl.endStream(cs)
9759 return nil
9760 }
9761
9762
9763
9764 type http2transportResponseBody struct {
9765 cs *http2clientStream
9766 }
9767
9768 func (b http2transportResponseBody) Read(p []byte) (n int, err error) {
9769 cs := b.cs
9770 cc := cs.cc
9771
9772 if cs.readErr != nil {
9773 return 0, cs.readErr
9774 }
9775 n, err = b.cs.bufPipe.Read(p)
9776 if cs.bytesRemain != -1 {
9777 if int64(n) > cs.bytesRemain {
9778 n = int(cs.bytesRemain)
9779 if err == nil {
9780 err = errors.New("net/http: server replied with more than declared Content-Length; truncated")
9781 cs.abortStream(err)
9782 }
9783 cs.readErr = err
9784 return int(cs.bytesRemain), err
9785 }
9786 cs.bytesRemain -= int64(n)
9787 if err == io.EOF && cs.bytesRemain > 0 {
9788 err = io.ErrUnexpectedEOF
9789 cs.readErr = err
9790 return n, err
9791 }
9792 }
9793 if n == 0 {
9794
9795 return
9796 }
9797
9798 cc.mu.Lock()
9799 connAdd := cc.inflow.add(n)
9800 var streamAdd int32
9801 if err == nil {
9802 streamAdd = cs.inflow.add(n)
9803 }
9804 cc.mu.Unlock()
9805
9806 if connAdd != 0 || streamAdd != 0 {
9807 cc.wmu.Lock()
9808 defer cc.wmu.Unlock()
9809 if connAdd != 0 {
9810 cc.fr.WriteWindowUpdate(0, http2mustUint31(connAdd))
9811 }
9812 if streamAdd != 0 {
9813 cc.fr.WriteWindowUpdate(cs.ID, http2mustUint31(streamAdd))
9814 }
9815 cc.bw.Flush()
9816 }
9817 return
9818 }
9819
9820 var http2errClosedResponseBody = errors.New("http2: response body closed")
9821
9822 func (b http2transportResponseBody) Close() error {
9823 cs := b.cs
9824 cc := cs.cc
9825
9826 cs.bufPipe.BreakWithError(http2errClosedResponseBody)
9827 cs.abortStream(http2errClosedResponseBody)
9828
9829 unread := cs.bufPipe.Len()
9830 if unread > 0 {
9831 cc.mu.Lock()
9832
9833 connAdd := cc.inflow.add(unread)
9834 cc.mu.Unlock()
9835
9836
9837
9838 cc.wmu.Lock()
9839
9840 if connAdd > 0 {
9841 cc.fr.WriteWindowUpdate(0, uint32(connAdd))
9842 }
9843 cc.bw.Flush()
9844 cc.wmu.Unlock()
9845 }
9846
9847 select {
9848 case <-cs.donec:
9849 case <-cs.ctx.Done():
9850
9851
9852
9853 return nil
9854 case <-cs.reqCancel:
9855 return http2errRequestCanceled
9856 }
9857 return nil
9858 }
9859
9860 func (rl *http2clientConnReadLoop) processData(f *http2DataFrame) error {
9861 cc := rl.cc
9862 cs := rl.streamByID(f.StreamID)
9863 data := f.Data()
9864 if cs == nil {
9865 cc.mu.Lock()
9866 neverSent := cc.nextStreamID
9867 cc.mu.Unlock()
9868 if f.StreamID >= neverSent {
9869
9870 cc.logf("http2: Transport received unsolicited DATA frame; closing connection")
9871 return http2ConnectionError(http2ErrCodeProtocol)
9872 }
9873
9874
9875
9876
9877
9878
9879 if f.Length > 0 {
9880 cc.mu.Lock()
9881 ok := cc.inflow.take(f.Length)
9882 connAdd := cc.inflow.add(int(f.Length))
9883 cc.mu.Unlock()
9884 if !ok {
9885 return http2ConnectionError(http2ErrCodeFlowControl)
9886 }
9887 if connAdd > 0 {
9888 cc.wmu.Lock()
9889 cc.fr.WriteWindowUpdate(0, uint32(connAdd))
9890 cc.bw.Flush()
9891 cc.wmu.Unlock()
9892 }
9893 }
9894 return nil
9895 }
9896 if cs.readClosed {
9897 cc.logf("protocol error: received DATA after END_STREAM")
9898 rl.endStreamError(cs, http2StreamError{
9899 StreamID: f.StreamID,
9900 Code: http2ErrCodeProtocol,
9901 })
9902 return nil
9903 }
9904 if !cs.pastHeaders {
9905 cc.logf("protocol error: received DATA before a HEADERS frame")
9906 rl.endStreamError(cs, http2StreamError{
9907 StreamID: f.StreamID,
9908 Code: http2ErrCodeProtocol,
9909 })
9910 return nil
9911 }
9912 if f.Length > 0 {
9913 if cs.isHead && len(data) > 0 {
9914 cc.logf("protocol error: received DATA on a HEAD request")
9915 rl.endStreamError(cs, http2StreamError{
9916 StreamID: f.StreamID,
9917 Code: http2ErrCodeProtocol,
9918 })
9919 return nil
9920 }
9921
9922 cc.mu.Lock()
9923 if !http2takeInflows(&cc.inflow, &cs.inflow, f.Length) {
9924 cc.mu.Unlock()
9925 return http2ConnectionError(http2ErrCodeFlowControl)
9926 }
9927
9928
9929 var refund int
9930 if pad := int(f.Length) - len(data); pad > 0 {
9931 refund += pad
9932 }
9933
9934 didReset := false
9935 var err error
9936 if len(data) > 0 {
9937 if _, err = cs.bufPipe.Write(data); err != nil {
9938
9939
9940 didReset = true
9941 refund += len(data)
9942 }
9943 }
9944
9945 sendConn := cc.inflow.add(refund)
9946 var sendStream int32
9947 if !didReset {
9948 sendStream = cs.inflow.add(refund)
9949 }
9950 cc.mu.Unlock()
9951
9952 if sendConn > 0 || sendStream > 0 {
9953 cc.wmu.Lock()
9954 if sendConn > 0 {
9955 cc.fr.WriteWindowUpdate(0, uint32(sendConn))
9956 }
9957 if sendStream > 0 {
9958 cc.fr.WriteWindowUpdate(cs.ID, uint32(sendStream))
9959 }
9960 cc.bw.Flush()
9961 cc.wmu.Unlock()
9962 }
9963
9964 if err != nil {
9965 rl.endStreamError(cs, err)
9966 return nil
9967 }
9968 }
9969
9970 if f.StreamEnded() {
9971 rl.endStream(cs)
9972 }
9973 return nil
9974 }
9975
9976 func (rl *http2clientConnReadLoop) endStream(cs *http2clientStream) {
9977
9978
9979 if !cs.readClosed {
9980 cs.readClosed = true
9981
9982
9983
9984
9985 rl.cc.mu.Lock()
9986 defer rl.cc.mu.Unlock()
9987 cs.bufPipe.closeWithErrorAndCode(io.EOF, cs.copyTrailers)
9988 close(cs.peerClosed)
9989 }
9990 }
9991
9992 func (rl *http2clientConnReadLoop) endStreamError(cs *http2clientStream, err error) {
9993 cs.readAborted = true
9994 cs.abortStream(err)
9995 }
9996
9997 func (rl *http2clientConnReadLoop) streamByID(id uint32) *http2clientStream {
9998 rl.cc.mu.Lock()
9999 defer rl.cc.mu.Unlock()
10000 cs := rl.cc.streams[id]
10001 if cs != nil && !cs.readAborted {
10002 return cs
10003 }
10004 return nil
10005 }
10006
10007 func (cs *http2clientStream) copyTrailers() {
10008 for k, vv := range cs.trailer {
10009 t := cs.resTrailer
10010 if *t == nil {
10011 *t = make(Header)
10012 }
10013 (*t)[k] = vv
10014 }
10015 }
10016
10017 func (rl *http2clientConnReadLoop) processGoAway(f *http2GoAwayFrame) error {
10018 cc := rl.cc
10019 cc.t.connPool().MarkDead(cc)
10020 if f.ErrCode != 0 {
10021
10022 cc.vlogf("transport got GOAWAY with error code = %v", f.ErrCode)
10023 if fn := cc.t.CountError; fn != nil {
10024 fn("recv_goaway_" + f.ErrCode.stringToken())
10025 }
10026 }
10027 cc.setGoAway(f)
10028 return nil
10029 }
10030
10031 func (rl *http2clientConnReadLoop) processSettings(f *http2SettingsFrame) error {
10032 cc := rl.cc
10033
10034
10035 cc.wmu.Lock()
10036 defer cc.wmu.Unlock()
10037
10038 if err := rl.processSettingsNoWrite(f); err != nil {
10039 return err
10040 }
10041 if !f.IsAck() {
10042 cc.fr.WriteSettingsAck()
10043 cc.bw.Flush()
10044 }
10045 return nil
10046 }
10047
10048 func (rl *http2clientConnReadLoop) processSettingsNoWrite(f *http2SettingsFrame) error {
10049 cc := rl.cc
10050 cc.mu.Lock()
10051 defer cc.mu.Unlock()
10052
10053 if f.IsAck() {
10054 if cc.wantSettingsAck {
10055 cc.wantSettingsAck = false
10056 return nil
10057 }
10058 return http2ConnectionError(http2ErrCodeProtocol)
10059 }
10060
10061 var seenMaxConcurrentStreams bool
10062 err := f.ForeachSetting(func(s http2Setting) error {
10063 switch s.ID {
10064 case http2SettingMaxFrameSize:
10065 cc.maxFrameSize = s.Val
10066 case http2SettingMaxConcurrentStreams:
10067 cc.maxConcurrentStreams = s.Val
10068 seenMaxConcurrentStreams = true
10069 case http2SettingMaxHeaderListSize:
10070 cc.peerMaxHeaderListSize = uint64(s.Val)
10071 case http2SettingInitialWindowSize:
10072
10073
10074
10075
10076 if s.Val > math.MaxInt32 {
10077 return http2ConnectionError(http2ErrCodeFlowControl)
10078 }
10079
10080
10081
10082
10083 delta := int32(s.Val) - int32(cc.initialWindowSize)
10084 for _, cs := range cc.streams {
10085 cs.flow.add(delta)
10086 }
10087 cc.cond.Broadcast()
10088
10089 cc.initialWindowSize = s.Val
10090 case http2SettingHeaderTableSize:
10091 cc.henc.SetMaxDynamicTableSize(s.Val)
10092 cc.peerMaxHeaderTableSize = s.Val
10093 default:
10094 cc.vlogf("Unhandled Setting: %v", s)
10095 }
10096 return nil
10097 })
10098 if err != nil {
10099 return err
10100 }
10101
10102 if !cc.seenSettings {
10103 if !seenMaxConcurrentStreams {
10104
10105
10106
10107
10108 cc.maxConcurrentStreams = http2defaultMaxConcurrentStreams
10109 }
10110 cc.seenSettings = true
10111 }
10112
10113 return nil
10114 }
10115
10116 func (rl *http2clientConnReadLoop) processWindowUpdate(f *http2WindowUpdateFrame) error {
10117 cc := rl.cc
10118 cs := rl.streamByID(f.StreamID)
10119 if f.StreamID != 0 && cs == nil {
10120 return nil
10121 }
10122
10123 cc.mu.Lock()
10124 defer cc.mu.Unlock()
10125
10126 fl := &cc.flow
10127 if cs != nil {
10128 fl = &cs.flow
10129 }
10130 if !fl.add(int32(f.Increment)) {
10131
10132 if cs != nil {
10133 rl.endStreamError(cs, http2StreamError{
10134 StreamID: f.StreamID,
10135 Code: http2ErrCodeFlowControl,
10136 })
10137 return nil
10138 }
10139
10140 return http2ConnectionError(http2ErrCodeFlowControl)
10141 }
10142 cc.cond.Broadcast()
10143 return nil
10144 }
10145
10146 func (rl *http2clientConnReadLoop) processResetStream(f *http2RSTStreamFrame) error {
10147 cs := rl.streamByID(f.StreamID)
10148 if cs == nil {
10149
10150 return nil
10151 }
10152 serr := http2streamError(cs.ID, f.ErrCode)
10153 serr.Cause = http2errFromPeer
10154 if f.ErrCode == http2ErrCodeProtocol {
10155 rl.cc.SetDoNotReuse()
10156 }
10157 if fn := cs.cc.t.CountError; fn != nil {
10158 fn("recv_rststream_" + f.ErrCode.stringToken())
10159 }
10160 cs.abortStream(serr)
10161
10162 cs.bufPipe.CloseWithError(serr)
10163 return nil
10164 }
10165
10166
10167 func (cc *http2ClientConn) Ping(ctx context.Context) error {
10168 c := make(chan struct{})
10169
10170 var p [8]byte
10171 for {
10172 if _, err := rand.Read(p[:]); err != nil {
10173 return err
10174 }
10175 cc.mu.Lock()
10176
10177 if _, found := cc.pings[p]; !found {
10178 cc.pings[p] = c
10179 cc.mu.Unlock()
10180 break
10181 }
10182 cc.mu.Unlock()
10183 }
10184 var pingError error
10185 errc := make(chan struct{})
10186 go func() {
10187 cc.t.markNewGoroutine()
10188 cc.wmu.Lock()
10189 defer cc.wmu.Unlock()
10190 if pingError = cc.fr.WritePing(false, p); pingError != nil {
10191 close(errc)
10192 return
10193 }
10194 if pingError = cc.bw.Flush(); pingError != nil {
10195 close(errc)
10196 return
10197 }
10198 }()
10199 select {
10200 case <-c:
10201 return nil
10202 case <-errc:
10203 return pingError
10204 case <-ctx.Done():
10205 return ctx.Err()
10206 case <-cc.readerDone:
10207
10208 return cc.readerErr
10209 }
10210 }
10211
10212 func (rl *http2clientConnReadLoop) processPing(f *http2PingFrame) error {
10213 if f.IsAck() {
10214 cc := rl.cc
10215 cc.mu.Lock()
10216 defer cc.mu.Unlock()
10217
10218 if c, ok := cc.pings[f.Data]; ok {
10219 close(c)
10220 delete(cc.pings, f.Data)
10221 }
10222 return nil
10223 }
10224 cc := rl.cc
10225 cc.wmu.Lock()
10226 defer cc.wmu.Unlock()
10227 if err := cc.fr.WritePing(true, f.Data); err != nil {
10228 return err
10229 }
10230 return cc.bw.Flush()
10231 }
10232
10233 func (rl *http2clientConnReadLoop) processPushPromise(f *http2PushPromiseFrame) error {
10234
10235
10236
10237
10238
10239
10240
10241 return http2ConnectionError(http2ErrCodeProtocol)
10242 }
10243
10244 func (cc *http2ClientConn) writeStreamReset(streamID uint32, code http2ErrCode, err error) {
10245
10246
10247
10248
10249 cc.wmu.Lock()
10250 cc.fr.WriteRSTStream(streamID, code)
10251 cc.bw.Flush()
10252 cc.wmu.Unlock()
10253 }
10254
10255 var (
10256 http2errResponseHeaderListSize = errors.New("http2: response header list larger than advertised limit")
10257 http2errRequestHeaderListSize = errors.New("http2: request header list larger than peer's advertised limit")
10258 )
10259
10260 func (cc *http2ClientConn) logf(format string, args ...interface{}) {
10261 cc.t.logf(format, args...)
10262 }
10263
10264 func (cc *http2ClientConn) vlogf(format string, args ...interface{}) {
10265 cc.t.vlogf(format, args...)
10266 }
10267
10268 func (t *http2Transport) vlogf(format string, args ...interface{}) {
10269 if http2VerboseLogs {
10270 t.logf(format, args...)
10271 }
10272 }
10273
10274 func (t *http2Transport) logf(format string, args ...interface{}) {
10275 log.Printf(format, args...)
10276 }
10277
10278 var http2noBody io.ReadCloser = http2noBodyReader{}
10279
10280 type http2noBodyReader struct{}
10281
10282 func (http2noBodyReader) Close() error { return nil }
10283
10284 func (http2noBodyReader) Read([]byte) (int, error) { return 0, io.EOF }
10285
10286 type http2missingBody struct{}
10287
10288 func (http2missingBody) Close() error { return nil }
10289
10290 func (http2missingBody) Read([]byte) (int, error) { return 0, io.ErrUnexpectedEOF }
10291
10292 func http2strSliceContains(ss []string, s string) bool {
10293 for _, v := range ss {
10294 if v == s {
10295 return true
10296 }
10297 }
10298 return false
10299 }
10300
10301 type http2erringRoundTripper struct{ err error }
10302
10303 func (rt http2erringRoundTripper) RoundTripErr() error { return rt.err }
10304
10305 func (rt http2erringRoundTripper) RoundTrip(*Request) (*Response, error) { return nil, rt.err }
10306
10307
10308
10309 type http2gzipReader struct {
10310 _ http2incomparable
10311 body io.ReadCloser
10312 zr *gzip.Reader
10313 zerr error
10314 }
10315
10316 func (gz *http2gzipReader) Read(p []byte) (n int, err error) {
10317 if gz.zerr != nil {
10318 return 0, gz.zerr
10319 }
10320 if gz.zr == nil {
10321 gz.zr, err = gzip.NewReader(gz.body)
10322 if err != nil {
10323 gz.zerr = err
10324 return 0, err
10325 }
10326 }
10327 return gz.zr.Read(p)
10328 }
10329
10330 func (gz *http2gzipReader) Close() error {
10331 if err := gz.body.Close(); err != nil {
10332 return err
10333 }
10334 gz.zerr = fs.ErrClosed
10335 return nil
10336 }
10337
10338 type http2errorReader struct{ err error }
10339
10340 func (r http2errorReader) Read(p []byte) (int, error) { return 0, r.err }
10341
10342
10343
10344 func http2isConnectionCloseRequest(req *Request) bool {
10345 return req.Close || httpguts.HeaderValuesContainsToken(req.Header["Connection"], "close")
10346 }
10347
10348
10349
10350 func http2registerHTTPSProtocol(t *Transport, rt http2noDialH2RoundTripper) (err error) {
10351 defer func() {
10352 if e := recover(); e != nil {
10353 err = fmt.Errorf("%v", e)
10354 }
10355 }()
10356 t.RegisterProtocol("https", rt)
10357 return nil
10358 }
10359
10360
10361
10362
10363
10364 type http2noDialH2RoundTripper struct{ *http2Transport }
10365
10366 func (rt http2noDialH2RoundTripper) RoundTrip(req *Request) (*Response, error) {
10367 res, err := rt.http2Transport.RoundTrip(req)
10368 if http2isNoCachedConnError(err) {
10369 return nil, ErrSkipAltProtocol
10370 }
10371 return res, err
10372 }
10373
10374 func (t *http2Transport) idleConnTimeout() time.Duration {
10375
10376
10377
10378 if t.IdleConnTimeout != 0 {
10379 return t.IdleConnTimeout
10380 }
10381
10382 if t.t1 != nil {
10383 return t.t1.IdleConnTimeout
10384 }
10385
10386 return 0
10387 }
10388
10389 func http2traceGetConn(req *Request, hostPort string) {
10390 trace := httptrace.ContextClientTrace(req.Context())
10391 if trace == nil || trace.GetConn == nil {
10392 return
10393 }
10394 trace.GetConn(hostPort)
10395 }
10396
10397 func http2traceGotConn(req *Request, cc *http2ClientConn, reused bool) {
10398 trace := httptrace.ContextClientTrace(req.Context())
10399 if trace == nil || trace.GotConn == nil {
10400 return
10401 }
10402 ci := httptrace.GotConnInfo{Conn: cc.tconn}
10403 ci.Reused = reused
10404 cc.mu.Lock()
10405 ci.WasIdle = len(cc.streams) == 0 && reused
10406 if ci.WasIdle && !cc.lastActive.IsZero() {
10407 ci.IdleTime = time.Since(cc.lastActive)
10408 }
10409 cc.mu.Unlock()
10410
10411 trace.GotConn(ci)
10412 }
10413
10414 func http2traceWroteHeaders(trace *httptrace.ClientTrace) {
10415 if trace != nil && trace.WroteHeaders != nil {
10416 trace.WroteHeaders()
10417 }
10418 }
10419
10420 func http2traceGot100Continue(trace *httptrace.ClientTrace) {
10421 if trace != nil && trace.Got100Continue != nil {
10422 trace.Got100Continue()
10423 }
10424 }
10425
10426 func http2traceWait100Continue(trace *httptrace.ClientTrace) {
10427 if trace != nil && trace.Wait100Continue != nil {
10428 trace.Wait100Continue()
10429 }
10430 }
10431
10432 func http2traceWroteRequest(trace *httptrace.ClientTrace, err error) {
10433 if trace != nil && trace.WroteRequest != nil {
10434 trace.WroteRequest(httptrace.WroteRequestInfo{Err: err})
10435 }
10436 }
10437
10438 func http2traceFirstResponseByte(trace *httptrace.ClientTrace) {
10439 if trace != nil && trace.GotFirstResponseByte != nil {
10440 trace.GotFirstResponseByte()
10441 }
10442 }
10443
10444 func http2traceHasWroteHeaderField(trace *httptrace.ClientTrace) bool {
10445 return trace != nil && trace.WroteHeaderField != nil
10446 }
10447
10448 func http2traceWroteHeaderField(trace *httptrace.ClientTrace, k, v string) {
10449 if trace != nil && trace.WroteHeaderField != nil {
10450 trace.WroteHeaderField(k, []string{v})
10451 }
10452 }
10453
10454 func http2traceGot1xxResponseFunc(trace *httptrace.ClientTrace) func(int, textproto.MIMEHeader) error {
10455 if trace != nil {
10456 return trace.Got1xxResponse
10457 }
10458 return nil
10459 }
10460
10461
10462
10463 func (t *http2Transport) dialTLSWithContext(ctx context.Context, network, addr string, cfg *tls.Config) (*tls.Conn, error) {
10464 dialer := &tls.Dialer{
10465 Config: cfg,
10466 }
10467 cn, err := dialer.DialContext(ctx, network, addr)
10468 if err != nil {
10469 return nil, err
10470 }
10471 tlsCn := cn.(*tls.Conn)
10472 return tlsCn, nil
10473 }
10474
10475
10476 type http2writeFramer interface {
10477 writeFrame(http2writeContext) error
10478
10479
10480
10481
10482 staysWithinBuffer(size int) bool
10483 }
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495 type http2writeContext interface {
10496 Framer() *http2Framer
10497 Flush() error
10498 CloseConn() error
10499
10500
10501 HeaderEncoder() (*hpack.Encoder, *bytes.Buffer)
10502 }
10503
10504
10505
10506
10507 func http2writeEndsStream(w http2writeFramer) bool {
10508 switch v := w.(type) {
10509 case *http2writeData:
10510 return v.endStream
10511 case *http2writeResHeaders:
10512 return v.endStream
10513 case nil:
10514
10515
10516
10517 panic("writeEndsStream called on nil writeFramer")
10518 }
10519 return false
10520 }
10521
10522 type http2flushFrameWriter struct{}
10523
10524 func (http2flushFrameWriter) writeFrame(ctx http2writeContext) error {
10525 return ctx.Flush()
10526 }
10527
10528 func (http2flushFrameWriter) staysWithinBuffer(max int) bool { return false }
10529
10530 type http2writeSettings []http2Setting
10531
10532 func (s http2writeSettings) staysWithinBuffer(max int) bool {
10533 const settingSize = 6
10534 return http2frameHeaderLen+settingSize*len(s) <= max
10535
10536 }
10537
10538 func (s http2writeSettings) writeFrame(ctx http2writeContext) error {
10539 return ctx.Framer().WriteSettings([]http2Setting(s)...)
10540 }
10541
10542 type http2writeGoAway struct {
10543 maxStreamID uint32
10544 code http2ErrCode
10545 }
10546
10547 func (p *http2writeGoAway) writeFrame(ctx http2writeContext) error {
10548 err := ctx.Framer().WriteGoAway(p.maxStreamID, p.code, nil)
10549 ctx.Flush()
10550 return err
10551 }
10552
10553 func (*http2writeGoAway) staysWithinBuffer(max int) bool { return false }
10554
10555 type http2writeData struct {
10556 streamID uint32
10557 p []byte
10558 endStream bool
10559 }
10560
10561 func (w *http2writeData) String() string {
10562 return fmt.Sprintf("writeData(stream=%d, p=%d, endStream=%v)", w.streamID, len(w.p), w.endStream)
10563 }
10564
10565 func (w *http2writeData) writeFrame(ctx http2writeContext) error {
10566 return ctx.Framer().WriteData(w.streamID, w.endStream, w.p)
10567 }
10568
10569 func (w *http2writeData) staysWithinBuffer(max int) bool {
10570 return http2frameHeaderLen+len(w.p) <= max
10571 }
10572
10573
10574
10575 type http2handlerPanicRST struct {
10576 StreamID uint32
10577 }
10578
10579 func (hp http2handlerPanicRST) writeFrame(ctx http2writeContext) error {
10580 return ctx.Framer().WriteRSTStream(hp.StreamID, http2ErrCodeInternal)
10581 }
10582
10583 func (hp http2handlerPanicRST) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
10584
10585 func (se http2StreamError) writeFrame(ctx http2writeContext) error {
10586 return ctx.Framer().WriteRSTStream(se.StreamID, se.Code)
10587 }
10588
10589 func (se http2StreamError) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
10590
10591 type http2writePingAck struct{ pf *http2PingFrame }
10592
10593 func (w http2writePingAck) writeFrame(ctx http2writeContext) error {
10594 return ctx.Framer().WritePing(true, w.pf.Data)
10595 }
10596
10597 func (w http2writePingAck) staysWithinBuffer(max int) bool {
10598 return http2frameHeaderLen+len(w.pf.Data) <= max
10599 }
10600
10601 type http2writeSettingsAck struct{}
10602
10603 func (http2writeSettingsAck) writeFrame(ctx http2writeContext) error {
10604 return ctx.Framer().WriteSettingsAck()
10605 }
10606
10607 func (http2writeSettingsAck) staysWithinBuffer(max int) bool { return http2frameHeaderLen <= max }
10608
10609
10610
10611
10612 func http2splitHeaderBlock(ctx http2writeContext, headerBlock []byte, fn func(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error) error {
10613
10614
10615
10616
10617
10618
10619 const maxFrameSize = 16384
10620
10621 first := true
10622 for len(headerBlock) > 0 {
10623 frag := headerBlock
10624 if len(frag) > maxFrameSize {
10625 frag = frag[:maxFrameSize]
10626 }
10627 headerBlock = headerBlock[len(frag):]
10628 if err := fn(ctx, frag, first, len(headerBlock) == 0); err != nil {
10629 return err
10630 }
10631 first = false
10632 }
10633 return nil
10634 }
10635
10636
10637
10638 type http2writeResHeaders struct {
10639 streamID uint32
10640 httpResCode int
10641 h Header
10642 trailers []string
10643 endStream bool
10644
10645 date string
10646 contentType string
10647 contentLength string
10648 }
10649
10650 func http2encKV(enc *hpack.Encoder, k, v string) {
10651 if http2VerboseLogs {
10652 log.Printf("http2: server encoding header %q = %q", k, v)
10653 }
10654 enc.WriteField(hpack.HeaderField{Name: k, Value: v})
10655 }
10656
10657 func (w *http2writeResHeaders) staysWithinBuffer(max int) bool {
10658
10659
10660
10661
10662
10663
10664
10665 return false
10666 }
10667
10668 func (w *http2writeResHeaders) writeFrame(ctx http2writeContext) error {
10669 enc, buf := ctx.HeaderEncoder()
10670 buf.Reset()
10671
10672 if w.httpResCode != 0 {
10673 http2encKV(enc, ":status", http2httpCodeString(w.httpResCode))
10674 }
10675
10676 http2encodeHeaders(enc, w.h, w.trailers)
10677
10678 if w.contentType != "" {
10679 http2encKV(enc, "content-type", w.contentType)
10680 }
10681 if w.contentLength != "" {
10682 http2encKV(enc, "content-length", w.contentLength)
10683 }
10684 if w.date != "" {
10685 http2encKV(enc, "date", w.date)
10686 }
10687
10688 headerBlock := buf.Bytes()
10689 if len(headerBlock) == 0 && w.trailers == nil {
10690 panic("unexpected empty hpack")
10691 }
10692
10693 return http2splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
10694 }
10695
10696 func (w *http2writeResHeaders) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error {
10697 if firstFrag {
10698 return ctx.Framer().WriteHeaders(http2HeadersFrameParam{
10699 StreamID: w.streamID,
10700 BlockFragment: frag,
10701 EndStream: w.endStream,
10702 EndHeaders: lastFrag,
10703 })
10704 } else {
10705 return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
10706 }
10707 }
10708
10709
10710 type http2writePushPromise struct {
10711 streamID uint32
10712 method string
10713 url *url.URL
10714 h Header
10715
10716
10717
10718 allocatePromisedID func() (uint32, error)
10719 promisedID uint32
10720 }
10721
10722 func (w *http2writePushPromise) staysWithinBuffer(max int) bool {
10723
10724 return false
10725 }
10726
10727 func (w *http2writePushPromise) writeFrame(ctx http2writeContext) error {
10728 enc, buf := ctx.HeaderEncoder()
10729 buf.Reset()
10730
10731 http2encKV(enc, ":method", w.method)
10732 http2encKV(enc, ":scheme", w.url.Scheme)
10733 http2encKV(enc, ":authority", w.url.Host)
10734 http2encKV(enc, ":path", w.url.RequestURI())
10735 http2encodeHeaders(enc, w.h, nil)
10736
10737 headerBlock := buf.Bytes()
10738 if len(headerBlock) == 0 {
10739 panic("unexpected empty hpack")
10740 }
10741
10742 return http2splitHeaderBlock(ctx, headerBlock, w.writeHeaderBlock)
10743 }
10744
10745 func (w *http2writePushPromise) writeHeaderBlock(ctx http2writeContext, frag []byte, firstFrag, lastFrag bool) error {
10746 if firstFrag {
10747 return ctx.Framer().WritePushPromise(http2PushPromiseParam{
10748 StreamID: w.streamID,
10749 PromiseID: w.promisedID,
10750 BlockFragment: frag,
10751 EndHeaders: lastFrag,
10752 })
10753 } else {
10754 return ctx.Framer().WriteContinuation(w.streamID, lastFrag, frag)
10755 }
10756 }
10757
10758 type http2write100ContinueHeadersFrame struct {
10759 streamID uint32
10760 }
10761
10762 func (w http2write100ContinueHeadersFrame) writeFrame(ctx http2writeContext) error {
10763 enc, buf := ctx.HeaderEncoder()
10764 buf.Reset()
10765 http2encKV(enc, ":status", "100")
10766 return ctx.Framer().WriteHeaders(http2HeadersFrameParam{
10767 StreamID: w.streamID,
10768 BlockFragment: buf.Bytes(),
10769 EndStream: false,
10770 EndHeaders: true,
10771 })
10772 }
10773
10774 func (w http2write100ContinueHeadersFrame) staysWithinBuffer(max int) bool {
10775
10776 return 9+2*(len(":status")+len("100")) <= max
10777 }
10778
10779 type http2writeWindowUpdate struct {
10780 streamID uint32
10781 n uint32
10782 }
10783
10784 func (wu http2writeWindowUpdate) staysWithinBuffer(max int) bool { return http2frameHeaderLen+4 <= max }
10785
10786 func (wu http2writeWindowUpdate) writeFrame(ctx http2writeContext) error {
10787 return ctx.Framer().WriteWindowUpdate(wu.streamID, wu.n)
10788 }
10789
10790
10791
10792 func http2encodeHeaders(enc *hpack.Encoder, h Header, keys []string) {
10793 if keys == nil {
10794 sorter := http2sorterPool.Get().(*http2sorter)
10795
10796
10797
10798 defer http2sorterPool.Put(sorter)
10799 keys = sorter.Keys(h)
10800 }
10801 for _, k := range keys {
10802 vv := h[k]
10803 k, ascii := http2lowerHeader(k)
10804 if !ascii {
10805
10806
10807 continue
10808 }
10809 if !http2validWireHeaderFieldName(k) {
10810
10811
10812
10813 continue
10814 }
10815 isTE := k == "transfer-encoding"
10816 for _, v := range vv {
10817 if !httpguts.ValidHeaderFieldValue(v) {
10818
10819
10820 continue
10821 }
10822
10823 if isTE && v != "trailers" {
10824 continue
10825 }
10826 http2encKV(enc, k, v)
10827 }
10828 }
10829 }
10830
10831
10832
10833 type http2WriteScheduler interface {
10834
10835
10836
10837 OpenStream(streamID uint32, options http2OpenStreamOptions)
10838
10839
10840
10841
10842 CloseStream(streamID uint32)
10843
10844
10845
10846
10847
10848 AdjustStream(streamID uint32, priority http2PriorityParam)
10849
10850
10851
10852
10853 Push(wr http2FrameWriteRequest)
10854
10855
10856
10857
10858
10859 Pop() (wr http2FrameWriteRequest, ok bool)
10860 }
10861
10862
10863 type http2OpenStreamOptions struct {
10864
10865
10866 PusherID uint32
10867 }
10868
10869
10870 type http2FrameWriteRequest struct {
10871
10872
10873
10874 write http2writeFramer
10875
10876
10877
10878
10879 stream *http2stream
10880
10881
10882
10883
10884 done chan error
10885 }
10886
10887
10888
10889 func (wr http2FrameWriteRequest) StreamID() uint32 {
10890 if wr.stream == nil {
10891 if se, ok := wr.write.(http2StreamError); ok {
10892
10893
10894
10895
10896 return se.StreamID
10897 }
10898 return 0
10899 }
10900 return wr.stream.id
10901 }
10902
10903
10904
10905 func (wr http2FrameWriteRequest) isControl() bool {
10906 return wr.stream == nil
10907 }
10908
10909
10910
10911 func (wr http2FrameWriteRequest) DataSize() int {
10912 if wd, ok := wr.write.(*http2writeData); ok {
10913 return len(wd.p)
10914 }
10915 return 0
10916 }
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928 func (wr http2FrameWriteRequest) Consume(n int32) (http2FrameWriteRequest, http2FrameWriteRequest, int) {
10929 var empty http2FrameWriteRequest
10930
10931
10932 wd, ok := wr.write.(*http2writeData)
10933 if !ok || len(wd.p) == 0 {
10934 return wr, empty, 1
10935 }
10936
10937
10938 allowed := wr.stream.flow.available()
10939 if n < allowed {
10940 allowed = n
10941 }
10942 if wr.stream.sc.maxFrameSize < allowed {
10943 allowed = wr.stream.sc.maxFrameSize
10944 }
10945 if allowed <= 0 {
10946 return empty, empty, 0
10947 }
10948 if len(wd.p) > int(allowed) {
10949 wr.stream.flow.take(allowed)
10950 consumed := http2FrameWriteRequest{
10951 stream: wr.stream,
10952 write: &http2writeData{
10953 streamID: wd.streamID,
10954 p: wd.p[:allowed],
10955
10956
10957
10958 endStream: false,
10959 },
10960
10961
10962 done: nil,
10963 }
10964 rest := http2FrameWriteRequest{
10965 stream: wr.stream,
10966 write: &http2writeData{
10967 streamID: wd.streamID,
10968 p: wd.p[allowed:],
10969 endStream: wd.endStream,
10970 },
10971 done: wr.done,
10972 }
10973 return consumed, rest, 2
10974 }
10975
10976
10977
10978 wr.stream.flow.take(int32(len(wd.p)))
10979 return wr, empty, 1
10980 }
10981
10982
10983 func (wr http2FrameWriteRequest) String() string {
10984 var des string
10985 if s, ok := wr.write.(fmt.Stringer); ok {
10986 des = s.String()
10987 } else {
10988 des = fmt.Sprintf("%T", wr.write)
10989 }
10990 return fmt.Sprintf("[FrameWriteRequest stream=%d, ch=%v, writer=%v]", wr.StreamID(), wr.done != nil, des)
10991 }
10992
10993
10994
10995 func (wr *http2FrameWriteRequest) replyToWriter(err error) {
10996 if wr.done == nil {
10997 return
10998 }
10999 select {
11000 case wr.done <- err:
11001 default:
11002 panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wr.write))
11003 }
11004 wr.write = nil
11005 }
11006
11007
11008 type http2writeQueue struct {
11009 s []http2FrameWriteRequest
11010 prev, next *http2writeQueue
11011 }
11012
11013 func (q *http2writeQueue) empty() bool { return len(q.s) == 0 }
11014
11015 func (q *http2writeQueue) push(wr http2FrameWriteRequest) {
11016 q.s = append(q.s, wr)
11017 }
11018
11019 func (q *http2writeQueue) shift() http2FrameWriteRequest {
11020 if len(q.s) == 0 {
11021 panic("invalid use of queue")
11022 }
11023 wr := q.s[0]
11024
11025 copy(q.s, q.s[1:])
11026 q.s[len(q.s)-1] = http2FrameWriteRequest{}
11027 q.s = q.s[:len(q.s)-1]
11028 return wr
11029 }
11030
11031
11032
11033
11034
11035 func (q *http2writeQueue) consume(n int32) (http2FrameWriteRequest, bool) {
11036 if len(q.s) == 0 {
11037 return http2FrameWriteRequest{}, false
11038 }
11039 consumed, rest, numresult := q.s[0].Consume(n)
11040 switch numresult {
11041 case 0:
11042 return http2FrameWriteRequest{}, false
11043 case 1:
11044 q.shift()
11045 case 2:
11046 q.s[0] = rest
11047 }
11048 return consumed, true
11049 }
11050
11051 type http2writeQueuePool []*http2writeQueue
11052
11053
11054
11055
11056 func (p *http2writeQueuePool) put(q *http2writeQueue) {
11057 for i := range q.s {
11058 q.s[i] = http2FrameWriteRequest{}
11059 }
11060 q.s = q.s[:0]
11061 *p = append(*p, q)
11062 }
11063
11064
11065 func (p *http2writeQueuePool) get() *http2writeQueue {
11066 ln := len(*p)
11067 if ln == 0 {
11068 return new(http2writeQueue)
11069 }
11070 x := ln - 1
11071 q := (*p)[x]
11072 (*p)[x] = nil
11073 *p = (*p)[:x]
11074 return q
11075 }
11076
11077
11078 const http2priorityDefaultWeight = 15
11079
11080
11081 type http2PriorityWriteSchedulerConfig struct {
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094 MaxClosedNodesInTree int
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106 MaxIdleNodesInTree int
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116 ThrottleOutOfOrderWrites bool
11117 }
11118
11119
11120
11121
11122 func http2NewPriorityWriteScheduler(cfg *http2PriorityWriteSchedulerConfig) http2WriteScheduler {
11123 if cfg == nil {
11124
11125
11126 cfg = &http2PriorityWriteSchedulerConfig{
11127 MaxClosedNodesInTree: 10,
11128 MaxIdleNodesInTree: 10,
11129 ThrottleOutOfOrderWrites: false,
11130 }
11131 }
11132
11133 ws := &http2priorityWriteScheduler{
11134 nodes: make(map[uint32]*http2priorityNode),
11135 maxClosedNodesInTree: cfg.MaxClosedNodesInTree,
11136 maxIdleNodesInTree: cfg.MaxIdleNodesInTree,
11137 enableWriteThrottle: cfg.ThrottleOutOfOrderWrites,
11138 }
11139 ws.nodes[0] = &ws.root
11140 if cfg.ThrottleOutOfOrderWrites {
11141 ws.writeThrottleLimit = 1024
11142 } else {
11143 ws.writeThrottleLimit = math.MaxInt32
11144 }
11145 return ws
11146 }
11147
11148 type http2priorityNodeState int
11149
11150 const (
11151 http2priorityNodeOpen http2priorityNodeState = iota
11152 http2priorityNodeClosed
11153 http2priorityNodeIdle
11154 )
11155
11156
11157
11158
11159 type http2priorityNode struct {
11160 q http2writeQueue
11161 id uint32
11162 weight uint8
11163 state http2priorityNodeState
11164 bytes int64
11165 subtreeBytes int64
11166
11167
11168 parent *http2priorityNode
11169 kids *http2priorityNode
11170 prev, next *http2priorityNode
11171 }
11172
11173 func (n *http2priorityNode) setParent(parent *http2priorityNode) {
11174 if n == parent {
11175 panic("setParent to self")
11176 }
11177 if n.parent == parent {
11178 return
11179 }
11180
11181 if parent := n.parent; parent != nil {
11182 if n.prev == nil {
11183 parent.kids = n.next
11184 } else {
11185 n.prev.next = n.next
11186 }
11187 if n.next != nil {
11188 n.next.prev = n.prev
11189 }
11190 }
11191
11192
11193
11194 n.parent = parent
11195 if parent == nil {
11196 n.next = nil
11197 n.prev = nil
11198 } else {
11199 n.next = parent.kids
11200 n.prev = nil
11201 if n.next != nil {
11202 n.next.prev = n
11203 }
11204 parent.kids = n
11205 }
11206 }
11207
11208 func (n *http2priorityNode) addBytes(b int64) {
11209 n.bytes += b
11210 for ; n != nil; n = n.parent {
11211 n.subtreeBytes += b
11212 }
11213 }
11214
11215
11216
11217
11218
11219
11220
11221 func (n *http2priorityNode) walkReadyInOrder(openParent bool, tmp *[]*http2priorityNode, f func(*http2priorityNode, bool) bool) bool {
11222 if !n.q.empty() && f(n, openParent) {
11223 return true
11224 }
11225 if n.kids == nil {
11226 return false
11227 }
11228
11229
11230
11231 if n.id != 0 {
11232 openParent = openParent || (n.state == http2priorityNodeOpen)
11233 }
11234
11235
11236
11237
11238 w := n.kids.weight
11239 needSort := false
11240 for k := n.kids.next; k != nil; k = k.next {
11241 if k.weight != w {
11242 needSort = true
11243 break
11244 }
11245 }
11246 if !needSort {
11247 for k := n.kids; k != nil; k = k.next {
11248 if k.walkReadyInOrder(openParent, tmp, f) {
11249 return true
11250 }
11251 }
11252 return false
11253 }
11254
11255
11256
11257 *tmp = (*tmp)[:0]
11258 for n.kids != nil {
11259 *tmp = append(*tmp, n.kids)
11260 n.kids.setParent(nil)
11261 }
11262 sort.Sort(http2sortPriorityNodeSiblings(*tmp))
11263 for i := len(*tmp) - 1; i >= 0; i-- {
11264 (*tmp)[i].setParent(n)
11265 }
11266 for k := n.kids; k != nil; k = k.next {
11267 if k.walkReadyInOrder(openParent, tmp, f) {
11268 return true
11269 }
11270 }
11271 return false
11272 }
11273
11274 type http2sortPriorityNodeSiblings []*http2priorityNode
11275
11276 func (z http2sortPriorityNodeSiblings) Len() int { return len(z) }
11277
11278 func (z http2sortPriorityNodeSiblings) Swap(i, k int) { z[i], z[k] = z[k], z[i] }
11279
11280 func (z http2sortPriorityNodeSiblings) Less(i, k int) bool {
11281
11282
11283 wi, bi := float64(z[i].weight+1), float64(z[i].subtreeBytes)
11284 wk, bk := float64(z[k].weight+1), float64(z[k].subtreeBytes)
11285 if bi == 0 && bk == 0 {
11286 return wi >= wk
11287 }
11288 if bk == 0 {
11289 return false
11290 }
11291 return bi/bk <= wi/wk
11292 }
11293
11294 type http2priorityWriteScheduler struct {
11295
11296
11297 root http2priorityNode
11298
11299
11300 nodes map[uint32]*http2priorityNode
11301
11302
11303 maxID uint32
11304
11305
11306
11307
11308 closedNodes, idleNodes []*http2priorityNode
11309
11310
11311 maxClosedNodesInTree int
11312 maxIdleNodesInTree int
11313 writeThrottleLimit int32
11314 enableWriteThrottle bool
11315
11316
11317 tmp []*http2priorityNode
11318
11319
11320 queuePool http2writeQueuePool
11321 }
11322
11323 func (ws *http2priorityWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
11324
11325 if curr := ws.nodes[streamID]; curr != nil {
11326 if curr.state != http2priorityNodeIdle {
11327 panic(fmt.Sprintf("stream %d already opened", streamID))
11328 }
11329 curr.state = http2priorityNodeOpen
11330 return
11331 }
11332
11333
11334
11335
11336
11337 parent := ws.nodes[options.PusherID]
11338 if parent == nil {
11339 parent = &ws.root
11340 }
11341 n := &http2priorityNode{
11342 q: *ws.queuePool.get(),
11343 id: streamID,
11344 weight: http2priorityDefaultWeight,
11345 state: http2priorityNodeOpen,
11346 }
11347 n.setParent(parent)
11348 ws.nodes[streamID] = n
11349 if streamID > ws.maxID {
11350 ws.maxID = streamID
11351 }
11352 }
11353
11354 func (ws *http2priorityWriteScheduler) CloseStream(streamID uint32) {
11355 if streamID == 0 {
11356 panic("violation of WriteScheduler interface: cannot close stream 0")
11357 }
11358 if ws.nodes[streamID] == nil {
11359 panic(fmt.Sprintf("violation of WriteScheduler interface: unknown stream %d", streamID))
11360 }
11361 if ws.nodes[streamID].state != http2priorityNodeOpen {
11362 panic(fmt.Sprintf("violation of WriteScheduler interface: stream %d already closed", streamID))
11363 }
11364
11365 n := ws.nodes[streamID]
11366 n.state = http2priorityNodeClosed
11367 n.addBytes(-n.bytes)
11368
11369 q := n.q
11370 ws.queuePool.put(&q)
11371 n.q.s = nil
11372 if ws.maxClosedNodesInTree > 0 {
11373 ws.addClosedOrIdleNode(&ws.closedNodes, ws.maxClosedNodesInTree, n)
11374 } else {
11375 ws.removeNode(n)
11376 }
11377 }
11378
11379 func (ws *http2priorityWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {
11380 if streamID == 0 {
11381 panic("adjustPriority on root")
11382 }
11383
11384
11385
11386
11387 n := ws.nodes[streamID]
11388 if n == nil {
11389 if streamID <= ws.maxID || ws.maxIdleNodesInTree == 0 {
11390 return
11391 }
11392 ws.maxID = streamID
11393 n = &http2priorityNode{
11394 q: *ws.queuePool.get(),
11395 id: streamID,
11396 weight: http2priorityDefaultWeight,
11397 state: http2priorityNodeIdle,
11398 }
11399 n.setParent(&ws.root)
11400 ws.nodes[streamID] = n
11401 ws.addClosedOrIdleNode(&ws.idleNodes, ws.maxIdleNodesInTree, n)
11402 }
11403
11404
11405
11406 parent := ws.nodes[priority.StreamDep]
11407 if parent == nil {
11408 n.setParent(&ws.root)
11409 n.weight = http2priorityDefaultWeight
11410 return
11411 }
11412
11413
11414 if n == parent {
11415 return
11416 }
11417
11418
11419
11420
11421
11422
11423
11424
11425 for x := parent.parent; x != nil; x = x.parent {
11426 if x == n {
11427 parent.setParent(n.parent)
11428 break
11429 }
11430 }
11431
11432
11433
11434
11435 if priority.Exclusive {
11436 k := parent.kids
11437 for k != nil {
11438 next := k.next
11439 if k != n {
11440 k.setParent(n)
11441 }
11442 k = next
11443 }
11444 }
11445
11446 n.setParent(parent)
11447 n.weight = priority.Weight
11448 }
11449
11450 func (ws *http2priorityWriteScheduler) Push(wr http2FrameWriteRequest) {
11451 var n *http2priorityNode
11452 if wr.isControl() {
11453 n = &ws.root
11454 } else {
11455 id := wr.StreamID()
11456 n = ws.nodes[id]
11457 if n == nil {
11458
11459
11460
11461 if wr.DataSize() > 0 {
11462 panic("add DATA on non-open stream")
11463 }
11464 n = &ws.root
11465 }
11466 }
11467 n.q.push(wr)
11468 }
11469
11470 func (ws *http2priorityWriteScheduler) Pop() (wr http2FrameWriteRequest, ok bool) {
11471 ws.root.walkReadyInOrder(false, &ws.tmp, func(n *http2priorityNode, openParent bool) bool {
11472 limit := int32(math.MaxInt32)
11473 if openParent {
11474 limit = ws.writeThrottleLimit
11475 }
11476 wr, ok = n.q.consume(limit)
11477 if !ok {
11478 return false
11479 }
11480 n.addBytes(int64(wr.DataSize()))
11481
11482
11483
11484 if openParent {
11485 ws.writeThrottleLimit += 1024
11486 if ws.writeThrottleLimit < 0 {
11487 ws.writeThrottleLimit = math.MaxInt32
11488 }
11489 } else if ws.enableWriteThrottle {
11490 ws.writeThrottleLimit = 1024
11491 }
11492 return true
11493 })
11494 return wr, ok
11495 }
11496
11497 func (ws *http2priorityWriteScheduler) addClosedOrIdleNode(list *[]*http2priorityNode, maxSize int, n *http2priorityNode) {
11498 if maxSize == 0 {
11499 return
11500 }
11501 if len(*list) == maxSize {
11502
11503 ws.removeNode((*list)[0])
11504 x := (*list)[1:]
11505 copy(*list, x)
11506 *list = (*list)[:len(x)]
11507 }
11508 *list = append(*list, n)
11509 }
11510
11511 func (ws *http2priorityWriteScheduler) removeNode(n *http2priorityNode) {
11512 for n.kids != nil {
11513 n.kids.setParent(n.parent)
11514 }
11515 n.setParent(nil)
11516 delete(ws.nodes, n.id)
11517 }
11518
11519
11520
11521
11522
11523 func http2NewRandomWriteScheduler() http2WriteScheduler {
11524 return &http2randomWriteScheduler{sq: make(map[uint32]*http2writeQueue)}
11525 }
11526
11527 type http2randomWriteScheduler struct {
11528
11529 zero http2writeQueue
11530
11531
11532
11533
11534 sq map[uint32]*http2writeQueue
11535
11536
11537 queuePool http2writeQueuePool
11538 }
11539
11540 func (ws *http2randomWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
11541
11542 }
11543
11544 func (ws *http2randomWriteScheduler) CloseStream(streamID uint32) {
11545 q, ok := ws.sq[streamID]
11546 if !ok {
11547 return
11548 }
11549 delete(ws.sq, streamID)
11550 ws.queuePool.put(q)
11551 }
11552
11553 func (ws *http2randomWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {
11554
11555 }
11556
11557 func (ws *http2randomWriteScheduler) Push(wr http2FrameWriteRequest) {
11558 if wr.isControl() {
11559 ws.zero.push(wr)
11560 return
11561 }
11562 id := wr.StreamID()
11563 q, ok := ws.sq[id]
11564 if !ok {
11565 q = ws.queuePool.get()
11566 ws.sq[id] = q
11567 }
11568 q.push(wr)
11569 }
11570
11571 func (ws *http2randomWriteScheduler) Pop() (http2FrameWriteRequest, bool) {
11572
11573 if !ws.zero.empty() {
11574 return ws.zero.shift(), true
11575 }
11576
11577 for streamID, q := range ws.sq {
11578 if wr, ok := q.consume(math.MaxInt32); ok {
11579 if q.empty() {
11580 delete(ws.sq, streamID)
11581 ws.queuePool.put(q)
11582 }
11583 return wr, true
11584 }
11585 }
11586 return http2FrameWriteRequest{}, false
11587 }
11588
11589 type http2roundRobinWriteScheduler struct {
11590
11591 control http2writeQueue
11592
11593
11594 streams map[uint32]*http2writeQueue
11595
11596
11597
11598 head *http2writeQueue
11599
11600
11601 queuePool http2writeQueuePool
11602 }
11603
11604
11605
11606
11607
11608
11609 func http2newRoundRobinWriteScheduler() http2WriteScheduler {
11610 ws := &http2roundRobinWriteScheduler{
11611 streams: make(map[uint32]*http2writeQueue),
11612 }
11613 return ws
11614 }
11615
11616 func (ws *http2roundRobinWriteScheduler) OpenStream(streamID uint32, options http2OpenStreamOptions) {
11617 if ws.streams[streamID] != nil {
11618 panic(fmt.Errorf("stream %d already opened", streamID))
11619 }
11620 q := ws.queuePool.get()
11621 ws.streams[streamID] = q
11622 if ws.head == nil {
11623 ws.head = q
11624 q.next = q
11625 q.prev = q
11626 } else {
11627
11628
11629 q.prev = ws.head.prev
11630 q.next = ws.head
11631 q.prev.next = q
11632 q.next.prev = q
11633 }
11634 }
11635
11636 func (ws *http2roundRobinWriteScheduler) CloseStream(streamID uint32) {
11637 q := ws.streams[streamID]
11638 if q == nil {
11639 return
11640 }
11641 if q.next == q {
11642
11643 ws.head = nil
11644 } else {
11645 q.prev.next = q.next
11646 q.next.prev = q.prev
11647 if ws.head == q {
11648 ws.head = q.next
11649 }
11650 }
11651 delete(ws.streams, streamID)
11652 ws.queuePool.put(q)
11653 }
11654
11655 func (ws *http2roundRobinWriteScheduler) AdjustStream(streamID uint32, priority http2PriorityParam) {}
11656
11657 func (ws *http2roundRobinWriteScheduler) Push(wr http2FrameWriteRequest) {
11658 if wr.isControl() {
11659 ws.control.push(wr)
11660 return
11661 }
11662 q := ws.streams[wr.StreamID()]
11663 if q == nil {
11664
11665
11666
11667 if wr.DataSize() > 0 {
11668 panic("add DATA on non-open stream")
11669 }
11670 ws.control.push(wr)
11671 return
11672 }
11673 q.push(wr)
11674 }
11675
11676 func (ws *http2roundRobinWriteScheduler) Pop() (http2FrameWriteRequest, bool) {
11677
11678 if !ws.control.empty() {
11679 return ws.control.shift(), true
11680 }
11681 if ws.head == nil {
11682 return http2FrameWriteRequest{}, false
11683 }
11684 q := ws.head
11685 for {
11686 if wr, ok := q.consume(math.MaxInt32); ok {
11687 ws.head = q.next
11688 return wr, true
11689 }
11690 q = q.next
11691 if q == ws.head {
11692 break
11693 }
11694 }
11695 return http2FrameWriteRequest{}, false
11696 }
11697
View as plain text