Source file src/net/http/h2_bundle.go

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

View as plain text