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