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