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