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