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