Source file src/net/http/h2_bundle.go

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

View as plain text