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