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

View as plain text