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

View as plain text