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

View as plain text