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

View as plain text