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

View as plain text