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