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