Source file src/net/http/h2_bundle.go

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