Black Lives Matter. Support the Equal Justice Initiative.

Source file src/net/http/h2_bundle.go

Documentation: net/http

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

View as plain text