github.com/Kolosok86/http@v0.1.2/h2_bundle.go (about)

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