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