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