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

View as plain text